Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have included an executable in my project ( i.e. when you unfold the project in the Solution Explorer in VS2008, you see it along with all the other classes). This executable will need to be launched by my program. How can I retrieve its path programmatically? | I've never done this before with executables... However, if it's an embedded resource, you can enumerate through the list of embedded resources in your application (or refer directly to it by name), when you find the one appropriate, write it to disk, and then execute it.
To extract:
```
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream("resource name")
{
using FileStream fs= new FileStream("executable name")
{
byte[] buffer = new byte[32*1024];
int bytesRead;
while ((bytesRead= stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
}
```
To execute:
```
using System.Diagnostics;
Process someProc;
someProc= Process.Start("executable name");
```
As Daniel L points out, don't forget to mark the resources as an "embedded resource". | Here's an example of getting text from a text resource:
```
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("ResourceTextFileName");
StreamReader textStreamReader = new StreamReader( stream );
```
Hopefully you can glean how to do an executable with this. | How can I get the path of a compiled resource? | [
"",
"c#",
".net",
"resources",
""
] |
I wonder if anyone else has asked a similar question.
Basically, I have a huge tree I'm building up in RAM using LINQ objects, and then I dump it all in one go using `DataContext.SubmitChanges()`.
It works, but I can't find how to give the user a sort of visual indication of how far has the query progressed so far. If I could ultimately implement a sort of progress bar, that would be great, even if there is a minimal loss in performance.
Note that I have quite a large amount of rows to put into the DB, over 750,000 rows.
I haven't timed it exactly, but it does take a long while to put them in.
**Edit:** I thought I'd better give some indication of what I'm doing.
Basically, I'm building a suffix tree from the Lord of the Rings. Thus, there are a lot of Nodes, and certain Nodes have positions associated to them (Nodes that happen to be at the end of a suffix). I am building the Linq objects along these lines.
```
suffixTreeDB.NodeObjs.InsertOnSubmit(new NodeObj()
{
NodeID = 0,
ParentID = 0,
Path = "$"
});
```
After the suffix tree has been fully generated in RAM (which only takes a few seconds), I then call `suffixTreeDB.submitChanges();`
What I'm wondering is if there is any faster way of doing this. Thanks!
**Edit 2:** I've did a stopwatch, and apparently it takes precisely 6 minutes for the DB to be written. | I suggest you divide the calls you are doing, as they are sent in separate calls to the db anyway. This will also reduce the size of the transaction (which linq does when calling submitchanges).
If you divide them in 10 blocks of 75.000, you can provide a rough estimate on a 1/10 scale.
**Update 1:** After re-reading your post and your new comments, I think you should take a look at SqlBulkCopy instead. If you need to improve the time of the operation, that's the way to go. Check this related question/answer: [What's the fastest way to bulk insert a lot of data in SQL Server (C# client)](https://stackoverflow.com/questions/24200/whats-the-fastest-way-to-bulk-insert-a-lot-of-data-in-sql-server-c-client/24224#24224) | I was able to get percentage progress for ctx.submitchanges() by using ctx.Log and ActionTextWriter
```
ctx.Log = new ActionTextWriter(s => {
if (s.StartsWith("INSERT INTO"))
insertsCount++;
ReportProgress(insertsCount);
});
```
more details are available at my blog post
<http://epandzo.wordpress.com/2011/01/02/linq-to-sql-ctx-submitchanges-progress/>
and stackoverflow question
[LINQ to SQL SubmitChangess() progress](https://stackoverflow.com/questions/4563828/linq-to-sql-submitchangess-progress) | How can I get a percentage of LINQ to SQL submitchanges? | [
"",
"c#",
"sql-server",
"linq-to-sql",
""
] |
In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to X’s constructor?
```
new X( ++i )
``` | From my copy of n2798:
> **5.3.4 New**
>
> 21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation function returns the null pointer or exits using an exception.
Read in conjunction with (to avoid ambiguities):
> **5.3.4 New**
>
> 8 A new-expression obtains storage for the object by calling an allocation function (3.7.4.1). If the newexpression terminates by throwing an exception, it may release storage by calling a deallocation function (3.7.4.2). If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete. If the allocated type is an array type, the allocation
> function’s name is operator new[] and the deallocation function’s name is operator delete[]. [...]
This pretty much answers the question. The answer is 'No'. | In general, the C++ compiler is free to re-order function parameters as long as it does not alter the meaning.
See Martin's answer here: [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about)
There are actually 2 function calls going on here under the hood.
1. operator new
2. constructor call for X
Even though it's two separate calls, I do not believe there is a sequence point between these two operations. Wikipedia appears to [support this point](http://en.wikipedia.org/wiki/Sequence_point). Therefore the Compiler is free to reorder evaluation as it sees fit. | Evaluation order of new expression? | [
"",
"c++",
""
] |
This is probably going to turn out to be a case of just needing another pair of eyes. I must be missing something, but I cannot figure out why this kind of thing cannot be tested for. I'm basically trying to ensure that unauthenticated users cannot access the view by marking the controller with the [Authorize] attribute and I'm trying to tests this using the following code:
```
[Fact]
public void ShouldRedirectToLoginForUnauthenticatedUsers()
{
var mockControllerContext = new Mock<ControllerContext>()
{ DefaultValue = DefaultValue.Mock };
var controller = new MyAdminController()
{ControllerContext = mockControllerContext.Object};
mockControllerContext.Setup(c =>
c.HttpContext.Request.IsAuthenticated).Returns(false);
var result = controller.Index();
Assert.IsAssignableFrom<RedirectResult>(result);
}
```
The RedirectResult I'm looking for is some kind of indication that the user is being redirected to the login form, but instead a ViewResult is always returned and when debugging I can see that the Index() method is successfully hit even though the user is not authenticated.
Am I doing something wrong? Testing at the wrong level? Should I rather be testing at the route level for this kind of thing?
I know that the [Authorize] attribute is working, because when I spin up the page, the login screen is indeed forced upon me - but how do I verify this in a test?
The controller and index method are very simple just so that I can verify the behaviour. I've included them for completeness:
```
[Authorize]
public class MyAdminController : Controller
{
public ActionResult Index()
{
return View();
}
}
```
Any help appreciated... | You are testing at the wrong level. The [Authorize] attribute ensures that the *routing* engine will never invoke that method for an unauthorized user - the RedirectResult will actually be coming from the route, not from your controller method.
Good news is - there's already test coverage for this (as part of the MVC framework source code), so I'd say you don't need to worry about it; just make sure your controller method does the right thing *when* it gets called, and trust the framework not to call it in the wrong circumstances.
EDIT: If you want to verify the presence of the attribute in your unit tests, you'll need to use reflection to inspect your controller methods as follows. This example will verify the presence of the Authorize attribute on the ChangePassword POST method in the 'New ASP.NET MVC 2 Project' demo that's installed with MVC2.
```
[TestFixture]
public class AccountControllerTests {
[Test]
public void Verify_ChangePassword_Method_Is_Decorated_With_Authorize_Attribute() {
var controller = new AccountController();
var type = controller.GetType();
var methodInfo = type.GetMethod("ChangePassword", new Type[] { typeof(ChangePasswordModel) });
var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);
Assert.IsTrue(attributes.Any(), "No AuthorizeAttribute found on ChangePassword(ChangePasswordModel model) method");
}
}
``` | Well you might be testing at the wrong level but its the test that makes sense. I mean, if I flag a method with the authorize(Roles="Superhero") attribute, I don't really need a test if I flagged it. What I (think I) want is to test that an unauthorized user doesn't have access and that an authorized user does.
For a unauthorized user a test like this:
```
// Arrange
var user = SetupUser(isAuthenticated, roles);
var controller = SetupController(user);
// Act
SomeHelper.Invoke(controller => controller.MyAction());
// Assert
Assert.AreEqual(401,
controller.ControllerContext.HttpContext.Response.StatusCode, "Status Code");
```
Well, it's not easy and it took me 10 hours, but here it is. I hope someone can benefit from it or convince me to go into another profession. :) (BTW - I'm using rhino mock)
```
[Test]
public void AuthenticatedNotIsUserRole_Should_RedirectToLogin()
{
// Arrange
var mocks = new MockRepository();
var controller = new FriendsController();
var httpContext = FakeHttpContext(mocks, true);
controller.ControllerContext = new ControllerContext
{
Controller = controller,
RequestContext = new RequestContext(httpContext, new RouteData())
};
httpContext.User.Expect(u => u.IsInRole("User")).Return(false);
mocks.ReplayAll();
// Act
var result =
controller.ActionInvoker.InvokeAction(controller.ControllerContext, "Index");
var statusCode = httpContext.Response.StatusCode;
// Assert
Assert.IsTrue(result, "Invoker Result");
Assert.AreEqual(401, statusCode, "Status Code");
mocks.VerifyAll();
}
```
Although, thats not very useful without this helper function:
```
public static HttpContextBase FakeHttpContext(MockRepository mocks, bool isAuthenticated)
{
var context = mocks.StrictMock<HttpContextBase>();
var request = mocks.StrictMock<HttpRequestBase>();
var response = mocks.StrictMock<HttpResponseBase>();
var session = mocks.StrictMock<HttpSessionStateBase>();
var server = mocks.StrictMock<HttpServerUtilityBase>();
var cachePolicy = mocks.Stub<HttpCachePolicyBase>();
var user = mocks.StrictMock<IPrincipal>();
var identity = mocks.StrictMock<IIdentity>();
var itemDictionary = new Dictionary<object, object>();
identity.Expect(id => id.IsAuthenticated).Return(isAuthenticated);
user.Expect(u => u.Identity).Return(identity).Repeat.Any();
context.Expect(c => c.User).PropertyBehavior();
context.User = user;
context.Expect(ctx => ctx.Items).Return(itemDictionary).Repeat.Any();
context.Expect(ctx => ctx.Request).Return(request).Repeat.Any();
context.Expect(ctx => ctx.Response).Return(response).Repeat.Any();
context.Expect(ctx => ctx.Session).Return(session).Repeat.Any();
context.Expect(ctx => ctx.Server).Return(server).Repeat.Any();
response.Expect(r => r.Cache).Return(cachePolicy).Repeat.Any();
response.Expect(r => r.StatusCode).PropertyBehavior();
return context;
}
```
So that gets you confirmation that users not in a role don't have access. I tried writing a test to confirm the opposite, but after two more hours of digging through mvc plumbing I will leave it to manual testers. (I bailed when I got to the VirtualPathProviderViewEngine class. WTF? I don't want anything to do a VirtualPath or a Provider or ViewEngine much the union of the three!)
I am curious as to why this is so hard in an allegedly "testable" framework. | Unit testing ASP.Net MVC Authorize attribute to verify redirect to login page | [
"",
"c#",
"asp.net-mvc",
""
] |
I am hoping the regular expression experts can tell me why this is going wrong:
This regex:
```
$pattern = '/(?<percent>[0-9]{1,3}\.[0-9]{1,2})% of (?<filesize>.+) at/';
```
Should match this sort of string:
```
[download] 87.1% of 4.40M at 107.90k/s ETA 00:05
[download] 89.0% of 4.40M at 107.88k/s ETA 00:04
[download] 91.4% of 4.40M at 106.09k/s ETA 00:03
[download] 92.9% of 4.40M at 105.55k/s ETA 00:03
```
Correct? Is there anything that could go wrong with that regex that will not get it to match with the above input? Full usage here:
```
while(!feof($handle))
{
$progress = fread($handle, 8192);
$pattern = '/(?<percent>[0-9]{1,3}\.[0-9]{1,2})% of (?<filesize>.+) at/';
if(preg_match_all($pattern, $progress, $matches)){
//matched
}
}
```
Could how much that is being read by **fread** be effecting the regex to work correctly?
I really need confirmation as I am trying to identify why it isn't working on a new server. This question is related to [Change in Server Permits script not to work. Can this be due to PHP.ini being different?](https://stackoverflow.com/questions/664332/change-in-server-permits-script-not-to-work-can-this-be-due-to-php-ini-being-dif)
Thanks all
## Update 2
I have made a test script to test the regex but even on its own it doesn't work??
```
<?php
error_reporting(E_ALL);
echo 'Start';
$progress = "[download]75.1% of 4.40M at 115.10k/s ETA 00:09 [download] 77.2% of 4.40M at 112.36k/s ETA 00:09 [download] 78.6% of 4.40M at 111.41k/s ETA 00:08 [download] 80.3% of 4.40M at 110.80k/s ETA 00:07 [download] 82.3% of 4.40M at 110.30k/s ETA 00:07 [download] 84.3% of 4.40M at 108.33k/s ETA 00:06 [download] 85.7% of 4.40M at 107.62k/s ETA 00:05 [download] 87.5% of 4.40M at 107.21k/s ETA 00:05 [download] 89.5% of 4.40M at 105.10k/s ETA 00:04 [download] 90.7% of 4.40M at 106.45k/s ETA 00:03 [download] 93.2% of 4.40M at 104.92k/s ETA 00:02 [download] 94.8% of 4.40M at 104.40k/s ETA 00:02 [download] 96.5% of 4.40M at 102.47k/s ETA 00:01 [download] 97.7% of 4.40M at 103.48k/s ETA 00:01 [download] 100.0% of 4.40M at 103.15k/s ETA 00:00 [download] 100.0% of 4.40M at 103.16k/s ETA 00:00
";
$pattern = '/(?<percent>\d{1,3}\.\d{1,2})%\s+of\s+(?<filesize>[\d.]+[kBM]) at/';
if(preg_match_all($pattern, $progress, $matches)){
echo 'match';
}
echo '<br>Done<br>';
?>
``` | I am not that familiar with named capture, but I think in PHP it should be:
```
$pattern = '/(?P<percent>[0-9]{1,3}\.[0-9]{1,2})% of (?P<filesize>.+) at/';
```
Notice the **P** after the question mark.
**Source:**
* Mastering Regular Expressions
* [PCRE Regular Expression Pattern Syntax Refference](http://www.regextester.com/pregsyntax.html) | The regex seems okay to me.
However, there are some things I would improve:
* whitespace with `"\s+"`, instead of `" "`
* numbers with `"\d"`, not with `"[0-9]"` (same thing, it's just shorter)
* filesize not with `".+"`, but with something more specific
This would be my version:
```
(?<percent>\d{1,3}\.\d{1,2})%\s+of\s+(?<filesize>[\d.]+[kBM])
```
Depending on how much you expect to get wrong number formats (I would guess: not very likely), you can shorten it to:
```
(?<percent>[\d.]+)%\s+of\s+(?<filesize>[\d.]+[kBM])
``` | Does this regex in PHP actually work? | [
"",
"php",
"regex",
""
] |
Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements? | It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0. | Yes, this is the default. In fact, this is the basis of the classic "DSU" ([Decorate-Sort-Undecorate](https://docs.python.org/3/howto/sorting.html#decorate-sort-undecorate)) idiom in Python. See [Code Like a Pythonista](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html). | How does Python sort a list of tuples? | [
"",
"python",
""
] |
Is there a BitTorrent client written completely (I mean completely) written in C# ?
I am aware of the BitTorrent clients written in mono, I absolutely love it.
Are there any other opensource BitTorrent clients other than MonoTorrent & BitSharp written in C# which is under development?
Just wondering how much of an interest an "opensource bit torrent client in C#" would generate amongst C# programmer folks out there.
EDIT: Do check out Michael Stum's Pumpkin torrent on <http://pumpkintorrent.codeplex.com/>
@Michael: thanks for sharing the project url.
@Allan: thanks for MonoTorrent ;) | MonoTorrent is wonderful client and server library. There is a GUI written on GTK# - Monsoon for now it runs only at Linux. If you have a time to spend you could write a WPF GUI or with little modification to port Monsoon to Windows.
Look for Alan McGovern for more information. | Unfortunately i don't have 50 reputation to add comments, so I have to write another answer. My question was directed at this comment:
"but honeslty I feel it's still got a long way to go to be on par with other opensource bit torrent clients."
What features do you feel are missing that makes it inferior to other libraries/clients? An incomplete list of features includes:
1. 100% platform independent
2. IPV6 support
3. Super-seeding
4. A full bittorrent tracker
5. DHT
6. Peer exchange (utorrent style)
7. Encryption
8. Memory cache
9. Prioritised downloading
10. Selective downloading (technically this is just a subset of Prioritised downloading)
11. Fast Peer extensions
12. Local peer discovery,
13. Ban lists (whitelisting/blacklisting of IPs at the same time)
14. Magnet link downloads
15. Endgame mode
16. Libtorrent extension protocol
17. rate limiting (per torrent/global)
18. Http seeding (webseeding) - getright style
19. Individual file relocation
20. What else do you want ;)
So, is it just a case of you not realising the full potential of monotorrent or are there features missing that you consider critical? If so, patches are always welcome.
""written on mono" is never a bad thing. It just I was looking for something on MS .Net"
I think you misunderstand. MonoTorrent/bitsharp *does* build and run on MS.NET ;) All you have to do is check the code out from SVN, open MonoTorrent.sln and hit F5.
Hope that helps. | A BitTorrent client completely written in C#? | [
"",
"c#",
".net",
"bittorrent",
""
] |
I'm compiling a C++ static library and as all the classes are templated, the class definitions and implementations are all in header files. As a result, it seems (under visual studio 2005) that I need to create a .cpp file which includes all the other header files in order for it to compile correctly into the library.
Why is this? | The compiler doesn't compile header files since these are meant to be included into source files. Prior to any compilation taking place the preprocessor takes all the code from any included header files and places that code into the source files where they're included, at the very location they're included. If the compiler should compile the headerfiles as well, you'd for example have multiple definitions on many things.
**Example, this is what the preprocessor sees:**
```
[foo.h]
void foo();
```
--
```
[mysource.cpp]
#include "foo.h"
int main()
{
foo();
}
```
**And this is what the compiler sees:**
```
[mysource.cpp]
void foo();
int main()
{
foo();
}
``` | Even when you will create a .cpp file you still won't receive anything. You need to instantiate templates in order to put them in the library.
Take a look here
<http://www.parashift.com/c%2B%2B-faq-lite/templates.html#faq-35.13>
about how to instantiate templates with concrete types. | Compiling a C++ .lib with only header files? | [
"",
"c++",
"code-organization",
""
] |
I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form `[{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}]` ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: `{badname1:goodname1, badname2:goodname2,...}`.
So I'd like to get from:
```
{badname1:data1, badname2:data2,...}` to `{goodname1:data1, goodname2:data2,...}
```
I'd like to use something like `zip()` (although `zip()` yields `{badname1:badname1,...}`).
Seems like there should be an obvious solution that is alluding me.
If the data is in `a` and the mapping in `b`:
```
dict(zip(b,a.itervalues()))
```
I get close, but it will only work in cases where the fields are known to be in the same order I think. | ```
name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...}
for row in rows:
# Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'}
row = dict((name_map[name], val) for name, val in row.iteritems())
...
```
Or in Python2.7+ with [Dict Comprehensions](http://www.python.org/dev/peps/pep-0274/):
```
for row in rows:
row = {name_map[name]: val for name, val in row.items()}
``` | If you are using Python 2.7 or Python 3.x, you can use a [dictionary comprehension](http://en.wikipedia.org/wiki/List_comprehension#Dict_comprehension). This is equivalent elo80ka's answer (which used a list comprehension), but produces slightly more readable code.
```
name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...}
for row in rows:
# Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'}
row = {name_map[name]: val for name, val in row.iteritems()}
...
``` | How do I re-map python dict keys | [
"",
"python",
"dictionary",
"iterator",
""
] |
I was going through a legacy code and found the following snippet:
```
MyClass::~MyClass()
{
EnterCriticalSection(&cs);
//Access Data Members, **NO Global** members are being accessed here
LeaveCriticalSection(&cs);
}
```
I am wondering will it help by any chance to guard the destructor ?
Consider a scenario :
```
1. Thread1 - About to execute any of the member function which uses critical section
2. Thread2- About to execute destructor.
```
If the order of execution is 1=>2 then it might work. But what if the order is reversed ?
Is it a design issue ? | The destructor should **not be called when the object is in use**. If you're dealing with such a situation, **it needs a fundamental fix**. However, the destructor might want to alter some other thing (which is unrelated to the class being destructed) and it might need a critical section (e.g. like decrementing a *global* counter). | I think you have a more fundamental problem. It shouldn't be legal to destroy your object on one thread while another thread is still calling member functions. This in itself is wrong.
Even if you successfully guard your destructor with critical sections, what happens when the other thread starts executing the remainder of the function? It will be doing so on a deleted object which (depending on it's allocation location) will be garbage memory or simple an invalid object.
You need to alter your code to ensure the object is not destructed while still in use. | Should destructors be threadsafe? | [
"",
"c++",
"multithreading",
"destructor",
""
] |
How to Implement Drag and Drop Between my Program and Explorer
ya windows application only | As long as you're using WinForms, it's actually very straightforward. See these two articles to get you started:
* [Drag and Drop files from Windows Explorer to Windows Form](http://www.codeproject.com/KB/cs/dragdrop.aspx)
* [Drag and Drop Text Files from Windows Explorer to your Windows Form Application](http://www.dotnetcurry.com/ShowArticle.aspx?ID=192&AspxAutoDetectCookieSupport=1)
And just in case you're using WPF, [this tutorial](http://www.wpftutorial.net/DragAndDrop.html) and [this SO thread](https://stackoverflow.com/questions/316900/dragndrop-one-or-more-mails-from-outlook-to-c-wpf-application) should help. | There is a good article on CodeProject about how to do this:
> This sample project lists a folder
> full of files, and lets you drag and
> drop them into Explorer. You can also
> drag from Explorer into the sample,
> and you can use the Shift and Ctrl
> keys to modify the action, just like
> in Explorer.
[Drag and drop, cut/copy and paste files with Windows Explorer](http://www.codeproject.com/KB/shell/Explorer_Drag_Drop.aspx)
> To start a drag operation into
> Explorer, we implement the `ItemDrag`
> event from the `Listview`, which gets
> called after you drag an item more
> than a few pixels. We simply call
> `DoDragDrop` passing the files to be
> dragged wrapped in a `DataObject`. You
> don't really need to understand
> `DataObject` - it implements the
> `IDataObject` interface used in the
> communication. | Drag and Drop in C#? | [
"",
"c#",
"drag-and-drop",
""
] |
I must serialize a huge tree of objects (7,000) into disk. Originally we kept this tree in a database with Kodo, but it would make thousands upon thousands of Queries to load this tree into memory, and it would take a good part of the local universe available time.
I tried serialization for this and indeed I get a performance improvement. However, I get the feeling that I could improve this by writing my own, custom serialization code. I need to make loading this serialized object as fast as possible.
In my machine, serializing / deserializing these objects takes about 15 seconds. When loading them from the database, it takes around 40 seconds.
Any tips on what could I do to improve this performance, taking into consideration that because objects are in a tree, they reference each other? | One optimization is customizing the class descriptors, so that you store the class descriptors in a different database and in the object stream you only refer to them by ID. This reduces the space needed by the serialized data. See for example how in one project the classes [SerialUtil](http://fisheye4.atlassian.com/browse/sgs-server/trunk/sgs-server/src/main/java/com/sun/sgs/impl/service/data/SerialUtil.java?r=4884) and [ClassesTable](http://fisheye4.atlassian.com/browse/sgs-server/trunk/sgs-server/src/main/java/com/sun/sgs/impl/service/data/ClassesTable.java?r=4607) do it.
Making classes Externalizable instead of Serializable can give some performance benefits. The downside is that it requires lots of manual work.
Then there are other serialization libraries, for example [jserial](http://jserial.sourceforge.net/), which can give better performance than Java's default serialization. Also, if the object graph does not include cycles, then it can be serialized a little bit faster, because the serializer does not need to keep track of objects it has seen (see "How does it work?" in [jserial's FAQ](http://jserial.sourceforge.net/faq.html)). | Don't forget to use the 'transient' key word for instance variables that don't have to be serialized. This gives you a performance boost because you are no longer reading/writing unnecessary data. | Java Object Serialization Performance tips | [
"",
"java",
"serialization",
""
] |
I have just started working on a project and I am using zend framework and postgresql (normally use MySQL) however I am hitting a problem when I am trying to get the last inserted id when using the Zend\_Db insert command.
When using the function `$db->lastinsertid('users', 'userid');` I get the following error message:
```
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "users_userid_seq" does not exist LINE 1: SELECT CURRVAL('users_userid_seq') ^
```
I've checked the database and the sequence does exist, and both the table and the sequence is owned by the the same user that is being use to access the application.
I've even tried `$db->lastSequenceId('users_userid_seq');` but still get the same error message.
I am not sure if the problem is with postgresql (I think most likely) or with the framework.
Has anyone else had a similar problem to this? | I see you found your answer, it was simply a typographical error.
FWIW, I'll offer the following suggestion as another reason for the error you saw:
You need to spell the name of the sequence exactly as it is stored, including matching case if the sequence name is stored as anything other than lower-case.
In other words, if the sequence was created with the spelling "`Users_userid_seq`," but you queried it as "`users_userid_seq`," this doesn't match and you'll get the error.
Try listing sequences in the `psql` tool:
```
postgres=# \ds
```
This will show you the sequences defined, with their spelling as they are stored in the database. | Check if the schema of the table "users" is in the "search\_path" of the Zend\_Db session. | postgresql sequence problems with lastinsertid and zend framework | [
"",
"php",
"database",
"zend-framework",
"postgresql",
""
] |
We have that Flex app talking to the server. We need some kind of *FlexEvent.ON\_BROWSER\_WINDOW\_CLOSE* event but, unfortunately Flex does not provide such.
So I've got the advice to catch a javascript "onbeforeunload" event and call the flash client thru the ExternalInterface-registred method.
Is there any way to subscribe for a javascript event without any javascript code?
**Update** I'm want to do that is multiply flash app hosting pages. Certainly we could manage that by external javascript file, but it's unclear still... | You can compile the js code inject into your SWF file:
```
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.net.SharedObject;
public class CloseTest extends Sprite
{
private var so:SharedObject = SharedObject.getLocal("hello");
public function CloseTest()
{
if (ExternalInterface.available)
{
ExternalInterface.addCallback("onclose", onClose);
ExternalInterface.call(this.javascript);
}
this.so.data.count ||= 0;
trace(so.data.count);
}
private function onClose ():void
{
this.so.data.count++;
this.so.flush();
this.so.close();
}
private var javascript:XML = <javascript><![CDATA[function ()
{
window.onbeforeunload = function ()
{
alert("hello");
document.getElementById("CloseTest").onclose();
}
}]]></javascript>;
}
}
``` | You can use ExternalInterface to call Javascript functions defined in the container. See [this](http://livedocs.adobe.com/flex/3/html/help.html?content=19_External_Interface_06.html#126566).
[This](http://gregjessup.com/flex-3-catch-browser-exit-or-close-event-using-javascript-and-externalinterface/) post describes a situation similar to yours. Take a look. | How to subscribe for an javascript event form Flex 3 action script code? | [
"",
"javascript",
"apache-flex",
"actionscript-3",
"dom",
"actionscript",
""
] |
Let's say I create a class with a property:
```
public class User
{
private string _userID;
public string UserID
{
get { return _userID; }
set { _userID = value; }
}
}
```
What do I have to do with the class and property to be able to have a method attached to the UserID property, such as a method that generates Xml around the user ID with the "dot" syntax:
```
User u = new User();
u.UserID = "Mike";
string xml = u.UserID.ToXml();
```
I can figure out how to write a method to put Xml tags around the value of the UserID, the part that is eluding me is how to make the method work with the property using the "dot" syntax.
---
All of these answers are useful, and thanks to everyone for contributing. In fact, the answer I marked as "accepted" was precisely what I was looking for. I appreciate the cautionary remakrs on extension methods (which I had never heard of before this), and of course it could be a problem to apply the extension method to all strings in some circumstances, but in this case I definitely wanted to apply the method ToXml() to all string properties in the class. Just what the doctor ordered. I am quite familiar with XmlSerialization, but in this case needed to avoid it for various reasons. | You have to add the method to the **type** of the property. In this case the UserID is a string, so that will mean adding it to the string type and making it accessible from *all* strings. I'm not sure that's a good idea, but if that's really want you want to do:
```
public static class StringUtils
{
public string ToXmlElement(this string s, string elementName)
{
return string.Format("<{0}>{1}</{0}>", elementName, s);
}
}
```
This doesn't exactly match your function signature, but it's something that makes a little more sense to attach to the larger string class. The only other option is to use a different underlying type to hold your UserID, perhaps a custom class with an implicit conversion to string.
Finally, if you're just trying to write your user class to Xml in a generic way, look at the `System.Xml.Serialization` namespace. Then you can just mark up your class like this and use an `XmlSerializer` instance to read or write the class.
```
[Serializable]
public class User
{
private string _userID;
[XmlElement()]
public string UserID
{
get { return _userID; }
set { _userID = value; }
}
}
``` | There are two ways:
Either the object/value that you're operating on has to have that method (such as when you have control over the object definition.)
```
public class UserIDObject
{
public string ToXML() {}
}
public class User
{
private UserIDObject _userID;
public UserIDObject UserID
{
get { return _userID; }
set { _userID = value; }
}
}
User u = new User();
u.UserID = = new UserIDObject("Mike");
string xml = u.UserID.ToXml();
```
Or you can implement an [Extension Method (MSDN)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) for the object.
Geeks with blogs has a good tutorial on [Extension Methods](https://web.archive.org/web/20170115233708/http://geekswithblogs.net:80/robp/archive/2007/12/20/using-extension-methods-in-.net-2.0-with-visual-studio-2008.aspx) and they can be applied to .NET 2.0 if you're running VS2008.
```
public static class MyMethods
{
public static string ToXML(this string s) { }
}
```
Extension Methods are something that you want to weight heavily since an extension method applies to **ALL** objects of that class type. (IE. do I want all strings to be able to call .ToXML()?) | How do I add a method to a property? | [
"",
"c#",
".net",
""
] |
In Java, is there any functions that can emit a (motherboard) beep with a given frequency and duration? In many languages I've worked with, you can; Beeps are useful for indicating certain types of errors, also for easily generating music.
The standard way to beep would be either print the BEEP character (\007 or something) or to use Toolkit.beep(), neither of which allows you to specify frequency and duration.
I'm thinking of implementing a native method, but there should be a library somewhere to do this simple task. I'm looking for something like `SomeClass.beep(500,1000);`
My application will only be supported on Windows.
Thanks. | See this link here:
<http://mindprod.com/products2.html#SPEAKER>
It contains Java source and a DLL for achieving the functionality you require. It emits various sounds from the internal PC speaker at a specific frequency for a given duration. Check out the Auld Lang Syne example : ) It uses JNI to achieve this with the included DLL.
btw.. I don't believe using the toolkit is reliable. It didn't produce output on my PC. | If you are 100% sure that you will support only windows, you can always call the corresponding [os method](http://msdn.microsoft.com/en-us/library/ms679277(VS.85).aspx) using [JNA](https://github.com/twall/jna/) | Beep library for Java? | [
"",
"java",
"beep",
""
] |
Are there any good, portable, open-source, high-level, statically-typed, imperative, object-oriented, garbage collected, safe languages/runtimes with reasonable performance besides Mono and Java? Mono is nice, but it is a Microsoft technology, and I'm kind of afraid of using it (I'm not sure how rational this fear is). The problem with Java is that it is just too simple (no unsigned data types, no structs, etc.). | I'd like to point out [Vala](http://live.gnome.org/Vala), which is a language based on the syntax of C#, but which targets a C compiler (similar to Eiffel) and a lightweight, self-hosted runtime. It lacks garbace collection, though. | Mono isn't a Microsoft technology. .NET is, but Mono isn't - Mono is an open-source implementation of the ECMA-334 and ECMA-335 international standards. Yes, they originated from Microsoft, but Mono itself is *not* Microsoft technology.
Not that Mono is a language, of course - C# is the language. But then *languages* aren't really open-source or not - implementations are.
It does sound like you've probably got an irrational fear of C# - and likewise of Java. There are certainly things I'd like to see in Java (and I significantly prefer C#), but it's still perfectly possible to write very significant applications in it. | Open source managed programming languages | [
"",
"java",
"open-source",
"mono",
""
] |
I want to use google gears, not for functionality but for optimization.
I.e. if gears is detected in the browser side, then we will silently use it to do some optimizations and caching in the client side.
If it isn't installed we silently work against the server only.
Somewhere in the FAQ or help pages of our website we will tell the users that our site recommends gears for best performance - but it is not a must, we will not use "offline features".
Do you think this is a valid google-gears usage scenario? Do you recommend for it / against it? | Sounds like a valid usage scenario to me.. just realise that you won't be able to do it 100% transparently as the user will have to tell gears to allow your site to use it. With that in mind you should definitely make it an opt in thing ([as described in the gears faq](http://code.google.com/apis/gears/gears_faq.html#bestGearsPerms)), rather than just attempting to use it if you find it installed, otherwise you'll annoy your users more than the slightly worse performance ever would have. | I think its a good possibility, but why try to hide it? As mentioned in other responses, the process can never be truly transparent, since some initial setup will be required at some point. Instead of hiding the feature, (depending on your project) you could use it to generate some positive press regarding your application.
Maybe by default you serve content from the main server, but along the bottom or top, include a highlighted link (think of "What's New" in Gmail). It could say something like "Improve performance by 50%" etc. The next page might contain a quick summary of whats going on, and why a user would commit to Gears. Similarly, when this launches, you could use the opportunity to show off "what you're spending development time doing."
I understand why you might want Gears to be unobtrusive, but don't make it hard for the user to get the best experience on your site. | Transparent google gears scenario validation | [
"",
"javascript",
"architecture",
"web-applications",
"google-gears",
""
] |
I am working on a Sometimes Connected CRUD application that will be primarily used by teams(2-4) of Social Workers and Nurses to track patient information in the form of a plan. The application is a revisualization of a ASP.Net app that was created before my time. There are approx 200 tables across 4 databases. The Web App version relied heavily on SP's but since this version is a winform app that will be pointing to a local db I see no reason to continue with SP's. Also of note, I had planned to use Merge Replication to handle the Sync'ing portion and there seems to be some issues with those two together.
I am trying to understand what approach to use for the DAL. I originally had planned to use LINQ to SQL but I have read tidbits that state it doesn't work in a Sometimes Connected setting. I have therefore been trying to read and experiment with numerous solutions; SubSonic, NHibernate, Entity Framework. This is a relatively simple application and due to a "looming" verion 3 redesign this effort can be borderline "throwaway." The emphasis here is on getting a desktop version up and running ASAP.
What i am asking here is for anyone with any experience using any of these technology's(or one I didn't list) to lend me your hard earned wisdom. What is my best approach, in your opinion, for me to pursue. Any other insights on creating this kind of App? I am really struggling with the DAL portion of this program.
Thank you! | If the stored procedures do what you want them to, I would have to say I'm dubious that you will get benefits by throwing them away and reimplementing them. Moreover, it shouldn't matter if you use stored procedures or LINQ to SQL style data access when it comes time to replicate your data back to the master database, so worrying about which DAL you use seems to be a red herring.
The tricky part about sometimes connected applications is coming up with a good conflict resolution system. My suggestions:
* Always use RowGuids as your primary keys to tables. Merge replication works best if you always have new records uniquely keyed.
* Realize that merge replication can only do so much: it is *great* for bringing new data in disparate systems together. It can even figure out one sided updates. It *can't* magically determine that your new record and my new record are *actually the same* nor can it really deal with changes on both sides without human intervention or priority rules.
* Because of this, you will need "matching" rules to resolve records that are claiming to be new, but actually aren't. Note that this is a fuzzy step: rarely can you rely on a unique key to actually be entered exactly the same on both sides and without error. This means giving weighted matches where *many* of your indicators are the same or similar.
* The user interface for resolving conflicts and matching up "new" records with the original needs to be easy to operate. I use something that looks similar to the classic three way merge that many source control systems use: Record A, Record B, Merged Record. They can default the Merged Record to A or B by clicking a header button, and can select each field by clicking against them as well. Finally, Merged Records fields are open for edit, because sometimes you need to take parts of the address (say) from A *and* B.
None of this should affect your data access layer in the slightest: this is all either lower level (merge replication, provided by the database itself) or higher level (conflict resolution, provided by your business rules for resolution) than your DAL. | If by SP's you mean stored procedures... I'm not sure I understand your reasoning from trying to move away from them. Considering that they're fast, proven, and already written for you (ie. tested).
Surely, if you're making an app that will mimic the original, there are definite merits to keeping as much of the original (working) codebase as possible - the least of which is speed.
I'd try installing a local copy of the db, and then pushing all affected records since the last connected period to the master db when it does get connected. | Sometimes Connected CRUD application DAL | [
"",
"c#",
"winforms",
"linq",
"data-access-layer",
""
] |
Businessmen typically want a web application developed. They are aware of .net or J2EE by names, without much knowledge about either.
Altho' Rails and Django offer for a much better and faster development stack, it is a big task to convince businessmen to use these platforms.
The task begins with introducing Django (or Rails), quoting some blog/research. Then making a case for the use of the framework for the specific project.
Lot of the task is repetitive. What are the sources/blogs/whitepapers and other materials you use to make a case for django (or Rails)
Don't you think there should be a common brochure developed that many development agencies could use to make the same case, over and again. Are there any such ones, now?
There seems to be enough discussion on Django vs Rails. Whereas the need is (Django and Rails) vs (.net and J2EE), at least so, while making a business case. Both represent a faster pragmatic web development in a dynamic language. | It's easier to ask forgiveness than permission.
First, build the initial release in Django. Quickly. Build the model well (really well!). But use as much default admin functionality as you can.
Spend time only only reporting and display pages where the HTML might actually matter to the presentation.
Show this and they'll only want more. Once they've gotten addicted to fast turnaround and correct out-of-the box operation, you can discuss technology with them. By then it won't matter any more. | You need to speak the language of business: money.
**"If we do it Rails, it will cost you 50% less than the same functionality in Java."**
Your percentage may vary, and you might need to also include hosting and upkeep costs, to show how it balances out.
When you're convincing other programmers, sure, talk about development speed and automation of repetitive tasks. But talk bottom-line cost to a business person. | How do you make a case for Django [or Ruby on Rails] to non-technical clients | [
"",
"python",
"ruby-on-rails",
"ruby",
"django",
""
] |
I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation? | Please see [yappi](https://pypi.python.org/pypi/yappi/) (Yet Another Python Profiler). | Instead of running one `cProfile`, you could run separate `cProfile` instance in each thread, then combine the stats. `Stats.add()` does this automatically. | How can I profile a multithread program in Python? | [
"",
"python",
"multithreading",
"profiling",
""
] |
When I first posted this question I had strong coupling between my web service and application controller where the controller needed to open multiple threads to the service and as it received back data it had to do a lot of processing on the returned data and merge it into one dataset. I did not like the fact that the client had to so much processing and merge the returned data before it was ready to be used and wanted to move that layer to the service and let the service open the asynchronous threads to the suppliers and merge the results before returning them to the client.
One challenge I had was that I could not wait till all threads were complete and results were merged, I had to start receiving data as it was available. That called me to implement an observer pattern on the service so that it would notify my application when new set of results are merged and ready to be used and send them to the application.
I was looking for how to do this using either on ASMX webservices or WCF and so far I have found implementing it using WCF but this thread is always open for suggestions and improvements. | OK the solution to my problem came from [WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx)
In addition to classic request-reply operation of ASMX web services, WCF supports additional operation types like; one-way calls, duplex callbacks and streaming.
Not too hard to guess, duplex callback was what I was looking for.
Duplex callbacks simply allow the service to do call backs to the client. A callback contract is defined on the server and client is required to provide the callback endpoint on every call. Then it is up to the service to decide when and how many times to use the callback reference.
Only bidirectiona-capable bindings support callback operations. WCF offers the WSDualHttpBinding to support callbacks over HTTP (Callback support also exists by NetNamedPipeBinding and NetTcpBinding as TCP and IPC protocols support duplex communication)
One very important thing to note here is that duplex callbacks are nonstandard and pure Microsoft feature. This is not creating a problem on my current task at hand as both my web service and application are running on Microsoft ASP.NET
[Programming WCF Services](https://rads.stackoverflow.com/amzn/click/com/0596521308) gave me a good jump start on WCF. Being over 700 pages it delves deep into all WCF consepts and has a dedicated chapter on the Callback and other type of operations.
Some other good resources I found on the net are;
[Windows Communication Foundation (WCF) Screencasts](http://social.msdn.microsoft.com/content/en-us/msft/netframework/wcf/screencasts)
[MSDN Webcast: Windows Communication Foundation Top to Bottom](http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?culture=en-US&EventID=1032344313&CountryCode=US)
[Web Service Software Factory](http://www.codeplex.com/servicefactory)
[The Service Factory for WCF](http://msdn.microsoft.com/en-us/magazine/cc163481.aspx) | This sounds like a perfect use case for Windows Workflow Foundation. You can easily create a workflow to get information from each supplier, then merge the results when ready. It's much cleaner, and WF will do all the async stuff for you. | Implementing observer pattern using WCF | [
"",
"c#",
".net",
"asp.net",
"wcf",
"web-services",
""
] |
So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?
I've seen these two references: [Find unused code](https://stackoverflow.com/questions/245963) and [Tool to find unused functions in php project](https://stackoverflow.com/questions/11532), but they seem specific to C# and PHP, respectively.
Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)? | In Python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are [`coverage`](https://coverage.readthedocs.io/en/6.0/) and [`figleaf`](https://ctb.github.io/figleaf/doc/). They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable results.
Alternatively, you can use static code analyzers that just look at your code, but don't actually run it. They run much faster, but due to Python's dynamic nature the results may contain false positives.
Two tools in this category are [`pyflakes`](https://pypi.org/project/pyflakes/) and [`vulture`](https://pypi.org/project/vulture/). Pyflakes finds unused imports and unused local variables. Vulture finds all kinds of unused and unreachable code. (Full disclosure: I'm the maintainer of Vulture.)
The tools are available in the Python Package Index <https://pypi.org/>. | Another option is [deadcode](https://github.com/albertas/deadcode) Python package. It detects globally defined but unused variable, function and class names. This tool works as a static code checker: it first parses all globally defined names and then counts how many times are they referenced in a whole code base.
You can install it:
```
pip install deadcode
```
and run it
```
deadcode .
```
I have implemented this tool, since other ones didn't do the job for me. It should be convenient to use [deadcode](https://pypi.org/project/deadcode/) as part of CI/CD pipeline. I hope it helps. | How can you find unused functions in Python code? | [
"",
"python",
"refactoring",
"dead-code",
""
] |
I have recently tried to get going with [Netbeans](http://www.google.co.uk/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.netbeans.org%2F&ei=n1POSZS6HsONjAfRzKXcCQ&usg=AFQjCNGXEZrzV0QrmVNuy79PoebH7M4D7w&sig2=n-DjKReZuy7Us_MsWwNBbg) 6.5 after it rated so highly in the IDE review by Smashing magazine. <http://www.smashingmagazine.com/2009/02/11/the-big-php-ides-test-why-use-oneand-which-to-choose/>
My main reason for switching from Notepad++ is that I'd like to be able to debug my code and set through it.
I have followed the instructions about how to install xdebug from both the vendor <http://xdebug.org/> and the netbeans web site. <http://www.netbeans.org/kb/docs/php/debugging.html#gettingReady> but to no avail.
**How is it done, has anyone else got debugging working in netbeans?**
*(My setup is: Windows XP, Wamp server 2.0, PHP 5, Netbeans 6.5.1)* | I have since found that WAMP, when installed with Mod\_rewrite and cURL cannot cope with Xdebug.
It is a **known error** and crashes everytime.
<http://phphints.wordpress.com/2008/10/24/wampserver-phpini-settings-for-use-with-xdebugdll-pear-and-silverstripe-cms-framework/>
Unfortunately, I am using these 2 libraries too. | It's important to add this line in the php.ini:
```
xdebug.idekey="netbeans-xdebug"
```
Note: In NetBeans go to Settings and look where the xdebug stuff is set up. Look for that Session ID. In my case it was netbeans-xdebug. | How to debug PHP with netbeans and Xdebug | [
"",
"php",
"debugging",
"netbeans",
"xdebug",
""
] |
How can I use download.php?get=file.exe with without the get variable, like download.php?=file.exe, using the $\_GET in PHP? | You could use `$_SERVER['request_uri']` which would allow you to omit the ? completely, leaving you with URLs like example.com/download.php/file.exe
Then, with a bit of URL rewriting (or implementing a bootstrap controller) you could clean it up even more, resulting in example.com/download/file.exe | You can use $\_GET[0] or $\_REQUEST[0] | $_GET without foo | [
"",
"php",
"url",
"get",
""
] |
I'm using Spring for form input and validation. The form controller's command contains the model that's being edited. Some of the model's attributes are a custom type. For example, Person's social security number is a custom SSN type.
```
public class Person {
public String getName() {...}
public void setName(String name) {...}
public SSN getSocialSecurtyNumber() {...}
public void setSocialSecurtyNumber(SSN ssn) {...}
}
```
and wrapping Person in a Spring form edit command:
```
public class EditPersonCommand {
public Person getPerson() {...}
public void setPerson(Person person) {...}
}
```
Since Spring doesn't know how to convert text to a SSN, I register a customer editor with the form controller's binder:
```
public class EditPersonController extends SimpleFormController {
protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) {
super.initBinder(req, binder);
binder.registerCustomEditor(SSN.class, "person.ssn", new SsnEditor());
}
}
```
and SsnEditor is just a custom `java.beans.PropertyEditor` that can convert text to a SSN object:
```
public class SsnEditor extends PropertyEditorSupport {
public String getAsText() {...} // converts SSN to text
public void setAsText(String str) {
// converts text to SSN
// throws IllegalArgumentException for invalid text
}
}
```
If `setAsText` encounters text that is invalid and can't be converted to a SSN, then it throws `IllegalArgumentException` (per `PropertyEditor` `setAsText`'s specification). The issue I'm having is that the text to object conversion (via `PropertyEditor.setAsText()`) takes place **before** my Spring validator is called. When `setAsText` throws `IllegalArgumentException`, Spring simply displays the generic error message defined in `errors.properties`. What I want is a specific error message that depends on the exact reason why the entered SSN is invalid. `PropertyEditor.setAsText()` would determine the reason. I've tried embedded the error reason text in `IllegalArgumentException`'s text, but Spring just treats it as a generic error.
Is there a solution to this? To repeat, what I want is the specific error message generated by the `PropertyEditor` to surface to the error message on the Spring form. The only alternative I can think of is to store the SSN as text in the command and perform validation in the validator. The text to SSN object conversion would take place in the form's `onSubmit`. This is less desirable as my form (and model) has many properties and I don't want to have to create and maintain a command that has each and every model attribute as a text field.
The above is just an example, my actual code isn't Person/SSN, so there's no need to reply with "why not store SSN as text..." | You're trying to do validation in a binder. That's not the binder's purpose. A binder is supposed to bind request parameters to your backing object, nothing more. A property editor converts Strings to objects and vice versa - it is not designed to do anything else.
In other words, you need to consider separation of concerns - you're trying to shoehorn functionality into an object that was never meant to do anything more than convert a string into an object and vice versa.
You might consider breaking up your SSN object into multiple, validateable fields that are easily bound (String objects, basic objects like Dates, etc). This way you can use a validator after binding to verify that the SSN is correct, or you can set an error directly. With a property editor, you throw an IllegalArgumentException, Spring converts it to a type mismatch error because that's what it is - the string doesn't match the type that is expected. That's all that it is. A validator, on the other hand, can do this. You can use the spring bind tag to bind to nested fields, as long as the SSN instance is populated - it must be initialized with new() first. For instance:
```
<spring:bind path="ssn.firstNestedField">...</spring:bind>
```
If you truly want to persist on this path, however, have your property editor keep a list of errors - if it is to throw an IllegalArgumentException, add it to the list and then throw the IllegalArgumentException (catch and rethrow if needed). Because you can construct your property editor in the same thread as the binding, it will be threadsafe if you simply override the property editor default behavior - you need to find the hook it uses to do binding, and override it - do the same property editor registration you're doing now (except in the same method, so that you can keep the reference to your editor) and then at the end of the binding, you can register errors by retrieving the list from your editor if you provide a public accessor. Once the list is retrieved you can process it and add your errors accordingly. | As said:
> What I want is the **specific error message generated by the PropertyEditor** to surface to the error message on the Spring form
Behind the scenes, Spring MVC uses a BindingErrorProcessor strategy for processing missing field errors, and **for translating a PropertyAccessException to a FieldError**. So if you want to override default Spring MVC BindingErrorProcessor strategy, you must provide a BindingErrorProcessor strategy according to:
```
public class CustomBindingErrorProcessor implements DefaultBindingErrorProcessor {
public void processMissingFieldError(String missingField, BindException errors) {
super.processMissingFieldError(missingField, errors);
}
public void processPropertyAccessException(PropertyAccessException accessException, BindException errors) {
if(accessException.getCause() instanceof IllegalArgumentException)
errors.rejectValue(accessException.getPropertyChangeEvent().getPropertyName(), "<SOME_SPECIFIC_CODE_IF_YOU_WANT>", accessException.getCause().getMessage());
else
defaultSpringBindingErrorProcessor.processPropertyAccessException(accessException, errors);
}
}
```
In order to test, Let's do the following
```
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(SSN.class, new PropertyEditorSupport() {
public String getAsText() {
if(getValue() == null)
return null;
return ((SSN) getValue()).toString();
}
public void setAsText(String value) throws IllegalArgumentException {
if(StringUtils.isBlank(value))
return;
boolean somethingGoesWrong = true;
if(somethingGoesWrong)
throw new IllegalArgumentException("Something goes wrong!");
}
});
}
```
Now our Test class
```
public class PersonControllerTest {
private PersonController personController;
private MockHttpServletRequest request;
@BeforeMethod
public void setUp() {
personController = new PersonController();
personController.setCommandName("command");
personController.setCommandClass(Person.class);
personController.setBindingErrorProcessor(new CustomBindingErrorProcessor());
request = new MockHttpServletRequest();
request.setMethod("POST");
request.addParameter("ssn", "somethingGoesWrong");
}
@Test
public void done() {
ModelAndView mav = personController.handleRequest(request, new MockHttpServletResponse());
BindingResult bindingResult = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + "command");
FieldError fieldError = bindingResult.getFieldError("ssn");
Assert.assertEquals(fieldError.getMessage(), "Something goes wrong!");
}
}
```
regards, | Spring validation, how to have PropertyEditor generate specific error message | [
"",
"java",
"validation",
"spring",
""
] |
I've been coding tests in Junit4 with Spring, and I got this funny behavior:
If my tests are passing like this, everything is fine:
```
@Test
public void truthTest(){
assertTrue(true); //Ok
}
```
But, if my test fails:
```
@Test
public void truthTest(){
assertTrue(false); //ERROR
}
```
Then instead of a test failure I receive an ugly and cryptic stack trace, This is it:
<http://pastie.org/429912>
Sorry for this ugly dump, but its the only data I've got to explain the problem (I "pastied" it for readability)
I'm really puzzled, has anyone encountered this kind of problem before? Thanks in advance! | <http://jira.springframework.org/browse/SPR-5145>
It is an known issue with spring-test 2.5.x. It is incompatible with JUnit 4.5. Use 4.0-4.4.
Or you can try the patch in the issue tracker. | I had the same problem when I wrote my Spring JUnit tests. Like a lot of posts available online, there are only two alternatives
1) Stay up to date with the Spring version and use the latest version of JUnit
or
2) Leave your current Spring version and use JUnit version 4.4 or less.
I chose the option # 2 where we left our Spring version at 2.5 and downloaded JUnit 4.4. Everything worked fine after that.
Also another point to be aware of is that if your project i.e., the project A you are writing your tests in has a dependency on another project B that has another version of Spring, you would get a similar error too. I learnt it the hard way.
-Prashanth | Junit4 + Spring 2.5 : Asserts throw "NoClassDefFoundError" | [
"",
"java",
"spring",
"junit4",
""
] |
I'm having issues parsing dates after 01/01/2000. The results are being returned incorrectly. 1999 is getting parsed as the year 1999, when it gets to 2000 it is parsing it as 0100, and then 2001 as 0101, etc. Here is the test code to illustrate this issue:
```
<script type="text/javascript" language="javascript">
// functions incorrect changes year from 2010 to 0101
var d = (new Date("12/01/2009"));
if (d.getMonth() < 11)
{ d = new Date(d.getYear(), d.getMonth() + 1, 1); }
else
{ d = new Date(d.getYear() + 1, 0, 1); }
document.write(d);
// Result: Sat Jan 01 0101 00:00:00 GMT-0500 (Eastern Standard Time)
document.write('<br />');
document.write(Date.parse(Date()) < Date.parse(d));
//
// Result: false today should definitely be < 01/01/2010
document.write('<br />');
// Functions correctly if year is before 2000
var d = (new Date("12/01/1998"));
if (d.getMonth() < 11)
{ d = new Date(d.getYear(), d.getMonth() + 1, 1); }
else
{ d = new Date(d.getYear() + 1, 0, 1); }
document.write(d);
// Result: Fri Jan 01 1999 00:00:00 GMT-0500 (Eastern Standard Time)
document.write('<br />');
document.write(Date.parse(Date()) < Date.parse(d));
// false
</script>
``` | You need to use d.getFullYear() instead of d.getYear()
getYear() only gives the number of years since 1900, obviously ;) | You should be using `Date.parse()`. Part of why you're seeing odd results is because you use `new Date("12/01/2009")` up at the top and compare everything else to that. Note that `Date.parse()` returns a number, not a date object. Therefore, do this for your very first assignment:
```
var d = new Date(Date.parse("12/01/2009"));
```
The next part is that you need the `getFullYear()` function rather than just `getYear()`, though your problem there is only in your verification code, not in how you actually parse the date. | Why isn't my date parsing correctly? | [
"",
"javascript",
""
] |
Well I've written a basic lossless jpeg joiner thing in java now but I'd like to compare the files it produces with the original files.
I can only compare so much in a hex editor, does anyone know of an easy way, software or java based (preferably software as I dont feel like any more coding for now!) that I can compare two images and produce a "difference map" of where the pixels aren't the same?
Thanks. | Thanks for the suggestions.
I tried the Gimp approach first which works well except when the difference between the images are very small. I couldn't find an "enhance differences" option to make the differences obvious and the histogram also only gives a rough representation of the differences.
In the end I used [ImageMagick](http://www.imagemagick.org/script/index.php) something I'd installed a while ago and forgot all about. Creating a difference/comparison image is as easy as typing:
```
compare first.jpg second.png difference.gif
```
in the command line.
It's all nicely explained [here.](http://www.imagemagick.org/Usage/compare/#difference) | TortoiseIDiff is a free image diff viewer:
<http://tortoisesvn.tigris.org/TortoiseIDiff.html>
It is part of TortoiseSVN, but can be used without Subversion.
> Depending on your project, not all files which are under version
> control are text files. Most likely you will have images too, for
> example screenshots and diagrams for the documentation/helpfile.
>
> For those files it's not possible to use a common file diff tool,
> because they only work with text files and diff line-by-line. Here is
> where the Tortoise Image Diff tool (TortoiseIDiff) comes to the
> rescue. It can show two images side-by-side, or even show the images
> over each other alpha blended. | An easy way (tool?) to compare images pixel for pixel in different formats? | [
"",
"java",
"image",
"image-processing",
"comparison",
"jpeg",
""
] |
I have this query running in my PHP script:
```
$insertQuery = "INSERT INTO blog_articles
VALUES '$title', $tags', '$category', '$blog', '$author', '$date'";
```
I then run this script:
```
if ($result = $connector->query($insertQuery)){
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
}
```
I get this error:
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Title Number 1, General, Blogging, Kayaking, General, Tgis is blog number spelli' at line 2
But I cannot tell what the error is. | Your query should be more like this
```
INSERT INTO blog_articles (`title`, `tags`, `category`, `blog`, `author`, `date`)
VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
```
You should also look into sanitizing your query. Perhaps this way (but i don't know your exact setup, so results might vary)
```
$sql = sprintf("INSERT INTO blog_articles (`title`, `tags`, `category`,
`blog`, `author`, `date`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($title), mysql_real_escape_string($tags),
mysql_real_escape_string($category), mysql_real_escape_string($blog),
mysql_real_escape_string($author), mysql_real_escape_string($date));
```
This uses the [`sprintf()`](http://is.php.net/manual/en/function.sprintf.php) function, the php documentation has some great examples. | You have a single quote missing before `$tags`. | MYSQL ERROR: "You have an error in your SQL syntax" | [
"",
"php",
"mysql",
""
] |
I want to close a socket so I can reopen one on the same port but I do not have a handle on that socket.
How can I get the socket that is listening on localhost:873 to close it? | Without a kernel driver this is not possible. It is not legal in Windows to grab a socket handle in another process and close it proactively. | Only that process that owns the socket can close it, so all you could try is ending the process that owns the socket.
From the command line you can find the Process ID of the process using a particular socket using the `-o` option to `netstat`. For example:
```
netstat -noa | findstr LISTENING
```
I don't know how you do this programmatically in .NET though. | How to get a specific socket and close it | [
"",
"c#",
".net-3.5",
"sockets",
""
] |
I am looking to implement a WebDAV server in ASP.Net. the app will be deployed to IIS 6. I have seen a few frameworks that provide this functionality, but I can't seem to identify how they're able to accomplish it without (apparently) modifying IIS settings.
My specific question is how do I configure IIS and ASP.Net so that a IHttpModule/IHttpHandler might have an opportunity to handle any of the additional WebDAV verbs (i.e. LOCK, OPTIONS, PROFIND, etc.) | There is no way to configure WebDAV verbs in IIS 6 without modifying IIS settings. It is possible only with IIS 7 and later.
To handle all verbs required by WebDAV in IIS 6 you will need to create an application wildacrd map. Right click on your web application in IIS 6 MMC console and go to *Properties*->*Virtual Directory* Tab->*Configuration*. Click *Insert* to add new wildcard map.
* Executable - \Microsoft.NET\Framework\<.Net
Framework Version>\aspnet\_isapi.dll
* **Verify that file exists - Unchecked**

On *Home Directory* tab of your application properties set *Execute permissions* to *Scripts only* and allow reads.
Here is the web.config example: <http://www.webdavsystem.com/server/prev/v2/documentation/hosting_iis_asp_net/webconfig_example>
Please note that this web.config example was specifically created and tested with ASP.NET 2.0 on IIS 6 on Server 2003 and IIS 5.1 on XP. It does not handle &, %, + and trailing dots (.).
ASP.NET 4.x provides means for handling any special characters in your WebDAV server, [configuring web.config](http://www.webdavsystem.com/server/documentation/special_characters_asp_net_iis), including &, % and '.'. The web.config that supports IIS versions 6-8 is generated by [IT Hit WebDAV Server Engine Wizard](http://www.webdavsystem.com/server). | Check out Geoff Lane's articles on WebDAV:
* <http://www.zorched.net/2006/01/20/aspnet-web-application-without-aspx-extension/> - shows configuration of verbs in IIS and HttpModule setup.
* <http://www.zorched.net/2006/02/02/custom-webdav-server-using-net/>
* <http://www.zorched.net/2006/03/01/more-webdav-tips-tricks-and-bugs/> | .Net WebDAV Server | [
"",
"c#",
".net",
"webdav",
""
] |
ADO.NET Data service is the next generation of data access layer within applications. I have seen a lot of examples using it directly from a UI layer such as Silverlight or Ajax to get data. This is almost as having a two tiered system, with business layer completely removed. Should DAL be accessed by the Business layer, and not directly from UI? | ADO.NET Data Services is one more tool to be evaluated in order to move data.
.NET RIA Services is another one. Much better I would say.
I see ADO.NET Data Services as a low level services to be used by some
high level framework. I would not let my UI talk directly to it.
The main problem I see with ADO.NET Data Services has more to do with
security than with anything else.
For simple/quick tasks, in a Intranet, and if you are not too pick with your
design, it can be useful. (IMO)
It can be quite handy when you need to quickly expose data from an existing database.
I say handy, but it would not be my first choice as I avoid as much as I can
the "quick and dirty" solutions.
Those solutions are like ghosts, always come back to haunt you. | > ADO.NET Data service is the next generation of data access layer within applications
I have no idea where you got *that* from! Perhaps you're confusing ADO.NET Data Services with ADO.NET Entity Framework?
---
One shouldn't assume that everything Microsoft produces is of value to every developer. In my opinion, ADO.NET Data Services is a quick way to create CRUD services, which maybe have a few other operations defined on the entity, but the operations are all stored procedures. If all you need is a database-oriented service, then this may be what you want. Certainly, there's relatively little reason to do any coding for a service like this, except in the database.
But that doesn't mean that ADO.NET Data Services "has a place in the overall design" of every project. It's something that fills a need of enough customers that Microsoft thought it worthwhile to spend money developing and maintaining it.
For that matter, they also thought ASP.NET MVC was a good idea...
:-) | ADO.NET data services their place in overall design | [
"",
"c#",
"wcf-data-services",
""
] |
I'd like to pass a Linq query to a method, how do I specify the argument type?
My link query look something like:
```
var query =
from p in pointList
where p.X < 100
select new {X = p.X, Y = p.Y}
```
clearly I'm new to Linq, and will probably get rid of the receiving method eventually when I convert the rest of my code, but it seems like something I should know...
thanks | You'll need to either use a normal type for the projection, or make the method you're passing it to generic as well (which will mean you can't do as much with it). What exactly are you trying to do? If you need to use the X and Y values from the method, you'll definitely need to create a normal type. (There are horribly hacky ways of avoiding it, but they're not a good idea.)
Note: some other answers are currently talking about `IQueryable<T>`, but there's no indication that you're using anything more than LINQ to Objects, in which case it'll be an `IEnumerable<T>` instead - but the `T` is currently an anonymous type. That's the bit you'll need to work on if you want to use the individual values within each item. If you're *not* using LINQ to Objects, please clarify the question and I'll edit this answer.
For example, taking your current query (which is slightly broken, as you can't use two projection initializers twice with the same name X). You'd create a new type, e.g. `MyPoint`
```
public sealed class MyPoint
{
private readonly int x;
private readonly int y;
public int X { get { return x; } }
public int Y { get { return y; } }
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
}
```
Your query would then be:
```
var query =
from p in pointList
where p.X < 100
select new MyPoint(p.X, p.Y);
```
You'd then write your method as:
```
public void SomeMethod(IEnumerable<MyPoint> points)
{
...
}
```
And call it as `SomeMethod(query);` | I think what you are looking for is the Expression class. For instance,
```
public void DoSomething()
{
User user = GetUser(x => x.ID == 12);
}
IQueryable<User> UserCollection;
public User GetUser(Expression<Func<User,bool>> expression)
{
return UserCollection.expression;
}
``` | How do I pass a Linq query to a method? | [
"",
"c#",
".net",
"linq",
""
] |
I was wondering if it is possible to include SVG content inside a panel (or whatever would work in GWT), be able to add more to the SVG (like add a circle or a curve) programmatically , and handle mouse events (would this be in SVG or GWT?). I've tried creating an HTML object adding something along the lines of:
```
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="50" cy="50" r="30" />
</svg>
```
That didn't work (nothing visible in output) but I'm not sure if it was because I did it wrong or it's not allowed.
I was able to do a simple example in GWT with Google Visualization's LineChart but I'd like to move away from Google Visualization and be able to generate the SVG myself and customize it further. I've looked around and many resources points to using Canvas but I'm not sure if that's the best route yet.
I'm also a bit baffled about the example [here](https://developer.mozilla.org/en/SVG_In_HTML_Introduction). I tried a simple copy-paste of it to try locally and it didn't seem to work at all. I was however able to get another sample working with just HTM (embed with src pointing to SVG file) L + separate SVG file but I haven't been able to access it using GWT using RootPanel.get(...).
EDIT:
I've read about SVG not working with Hosted Browser and compiling it does work but I am uncertain how to refer to the SVG (which I have placed into the HTML via ). If I can access it then presumably I can add to its innerHTML. I've tried in RootPanel.get("hi").getElement().setInnerHTML("...") but that doesn't seem to work or did I mess up? **I guess the goal is to be able to manipulate a SVG file which I linked somehow (whether in GWT or in HTML) and be able to modify it based on user's input.**
**2nd EDIT**
So far, I've been programming functionality inside of the actual SVG file. In our setup, our SVG is an embedded object and we passed 'document' to the embedded SVG. Passing information from an embed object to and from HTML is quite doable since the HTML has access to our SVG functions and the SVG has access to the 'document'.
There are more transparent ways of doing so (Rapahel) where FireBug could see the SVG directly which is nice but now not quite necessary. Thus far, I don't think any of the solutions I've looked at were IFrames but I could be wrong. A little warning, SVG can be pretty slow sometimes.
I would say my issue is solved (sort of?) but I'm not using Raphael, jQuery, nor GWT at the moment but the method I described in my answer should still work if I want to use GWT. | After playing around a bit, I've been most successful with using [Raphaël](http://raphaeljs.com/) (which handles cross-browser compatibility) though I suspect anything along those lines would work just fine. Basically I do the following in **JavaScript**:
```
var r = Raphael("someID", WND_WIDTH, WND_HEIGHT);
// additional configuration and setup if needed....
```
Then I would do the following in **GWT**:
```
public native JavaScriptObject getRaphael() /*-{
return $wnd.r;
}-*/;
// I now have access to the JavaScript object and could do the following:
public native void drawCircle(JavaScriptObject obj, int x, int y, int r) /*-{
obj.circle(x, y, r);
}-*/;
```
I've also been reading around and it seems that porting Raphaël into GWT (this [article](http://googlewebtoolkit.blogspot.com/2008/08/getting-to-really-know-gwt-part-2.html) is a good read) will not only increase performance (as per some post I read on Google Groups but can't find at the moment - they mentioned the compiler does quite a bit of work) but also facilitate coding & debugging.
So I accomplished my goal of being able to manipulate the SVG directly (somewhat until I port Raphaël into Java or at least create wrappers). I have yet to look seriously into the Google Visualization API but I suspect it might work just as well but I'm not sure if it is robust enough for my needs.
An important thing I believe I was missing as stated on Raphaël's site was the following:
> This means every graphical object you
> create is also a DOM object, so you
> can attach JavaScript event handlers
> or modify them later. | I don't entirely understand why, but the createElementNS JavaScript method allows you to create and correctly format xhtml within html.
Because there is no equivalent in explorer, GWT does not implement createElementNS, but you can with a quick native method :
```
private static native Element createElementNS(final String ns,
final String name)/*-{
return document.createElementNS(ns, name);
}-*/;
```
It makes sense to put this into an SVGPanel class.
```
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
public class SVGPanel extends ComplexPanel{
private static final String SVG_NAMESPACE = "http://www.w3.org/2000/svg";
public SVGPanel() {
setElement(createElementNS(SVG_NAMESPACE, "svg"));
showcaseSVG(); //Demonstrate that SVG works! Inexplicably!
}
private void showcaseSVG(){
Element svgElement = createElementNS(SVG_NAMESPACE, "circle");
svgElement.setAttribute("cx", "50");
svgElement.setAttribute("cy", "50");
svgElement.setAttribute("r", "30");
getElement().appendChild(svgElement);
}
}
```
This should produce some simple SVG when added to your program. Congratulations! You are now sticking it to the xhtml man. | Using SVG in GWT | [
"",
"javascript",
"html",
"gwt",
"svg",
""
] |
I want to know if there is a design pattern for specifying options to a set of algorithms. I am using C++.
Let me describe my problem. I am having a set of algorithms and these algorithms have different options. I want to design a single point access to these algorithms. Something similar to a strategy pattern. This single point access is a controller class which takes input as a generic options class. Depending upon the options, a suitable algorithm will be used. I want to generalize these options so that i can extend algorithms and the client.
Thanks,
Amol | Building on [Konrad's suggestion of using policy types](https://stackoverflow.com/questions/602108/design-for-generic-options-to-algorithms/602119#602119), if your algorithms require parameters at construction time, you can handle this cleanly by requiring that any `Policy` class has a nested type called `Params`, and then provide a constructor inside `fancy_algorithm<Policy>` that takes an argument of this type and passes it to the contained `Policy` object:
```
template <typename Policy>
class fancy_algorithm : private Policy {
public:
typedef typename Policy::Params Params; // Need to redeclare :(
explicit fancy_algorithm(Params params = Params()) : Policy(params) {}
};
```
Any relevant parameters need to be packaged into a single object of type `Policy::Params`.
The `Policy` class is always constructed with a single argument of type `Policy::Params`. To work with policy classes that (may) require no parameters, provide a default constructor (or use the implicitly declared one) in `Params`, not in `Policy`. This way, by using a default value for the `fancy_algorithm<Policy>` constructor as above, we enable convenient default-construction of a `fancy_algorithm<Policy>` whenever `Policy::Params` has a default constructor (i.e. when the `Policy` doesn't require any parameters). No safety is lost: if `Policy::Params` lacks a default constructor (indicating that some parameters are *required*), any attempt to default-construct a `fancy_algorithm<Policy>` object will fail at compile time.
Example:
```
struct multiply_by_params {
multiply_by_params(int x /* = 42 */) : _x(x) {} // See bottom
int get() const { return _x; } // Or, just make multiply_by a friend
private:
int _x;
};
struct multiply_by {
typedef multiply_by_params Params;
multiply_by(Params p) : _x(p.get()) { /* Other initialisation */ }
// Other code implementing the strategy (e.g. an operator()())
...
private:
int _x;
};
fancy_algorithm<multiply_by> a(69); // Always compiles
fancy_algorithm<multiply_by> b; // Compiles iff /* = 42 */ is uncommented
``` | An often-used pattern is to create a policy class which is passed as a template type to your class and then inherited from privately:
```
template <typename Policy>
class fancy_algorithm : private Policy {
};
```
One famous example of this is the `std::allocator` class which is often inherited in that manner:
```
template <typename T, typename Alloc = std::allocator<T> >
class my_container : private Alloc {
public:
typedef Alloc allocator;
// It's necessary to make the base class names available explicitly.
typedef typename allocator::pointer pointer;
using allocator::construct;
// …
};
``` | Design for generic options to algorithms | [
"",
"c++",
"design-patterns",
""
] |
I need to specify an `OutputStream` for an API I'm using, but I don't actually have a need for the output. Does Java have an `OutputStream` equivalent to `> /dev/null`? | Since Java 11, there is a static utility that does exactly what you need, a static factory method [`OutputStream.nullOutputStream()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/OutputStream.html#nullOutputStream()):
> Returns a new OutputStream which discards all bytes. The returned stream is initially open. The stream is closed by calling the close() method. Subsequent calls to close() have no effect. | Java 11+:
[OutputStream.nullOutputStream()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/OutputStream.html#nullOutputStream())
Java 11-:
```
/** Writes to nowhere. */
public class NullOutputStream extends OutputStream {
@Override
public void write(int b) throws IOException {}
}
``` | Is there a Null OutputStream in Java? | [
"",
"java",
"outputstream",
""
] |
i have a POST request
```
firstname=1&lastname=10&firstname=2&lastname=20&firstname=3&lastname=30.
```
then i get comma-delimited lists of names and values
```
Request.Form["firstname"] // 1,2,3
Request.Form["lastname"] //10,20,30
```
it seems that NameValueCollection does not contain a method to access specified firstname value directly?
the task looks standard, like Request.Form index property in ASP.
of course i can implement a custom helper enumerator or simply parse strings someway, but i'm not sure there are no any standard solution.
to be honest, i would prefer to have direct access to each firstname-lastname pair, but i cannot ask impossible:). | `GetValues()` will return a `string[]` | But how could you specify first firstname to the second one ?
they are not specific in this case. so you should write your own helper method to get the one you want.
Or replace keys with something like firstname1, firstname2.
Or if you get these from an radiolist control or listbox control, just use instance of the control to get the values, it's better solution I think. | how to get a particular value from NameValueCollection's comma-delimited string? | [
"",
"c#",
""
] |
why in C++, for objects A,B
```
//interface, case #1
class A {
B bb;
}
A::A()
{ //constructor
bb = B();
}
//interface, case #2
class A {
B *bb;
}
A::A()
{ //constructor
bb = new B();
}
```
Why case #2 work but not #1??
Edit: I got it now. But for case #1, if an instance of A is freed, will its bb also be **automatically** freed? Case #2 you have to explicitly call bb = NULL right? | The question **as for me** was how to make
```
A::A()
{ //constructor
bb = new B();
}
```
but without new. And I suppose the code in the question is not a real code. Just why 'new' works but simple assignment doesn't.
And **my answer** is following. If I understood the question in a wrong way or the answer itself is wrong - please let me know.
Change
```
A::A()
{ //constructor
bb = B();
}
```
to
```
A::A():
bb()
{
// some logic
}
```
and to have a consistence in the case with 'new' it is better to implement like
```
A::A():
bb( new B() )
{
// some logic
}
```
In these both cases when 'some logic' will start its execution you can be sure that object bb either initialized or exception will be thrown.
To make your case compilable B should has implemented assign operator.
**To your edit:** Your guess about case 1 is correct. in case 2 you have to call delete bb in the class destructor.
Please leave a message **of the '-1' reason**. I am really confused. | Both have syntax errors so 'does not work' isn't specific to one or the other. You also haven't declared the `A::A` constructor, so you will get a semantic error when you attempt to define it.
If the full declaration of B is available before the declaration of class A, then it will compile:
```
class B {};
//interface
class A {
A();
B bb;
};
A::A()
{ //constructor
bb = B();
}
```
In the `bb=B()` line, bb has already been constructed, as it is a member of A. You are then constructing another B, then copying that B's values to bb. That's a bit of a waste. If you want to pass arguments to bb's constructor, use an initialiser.
If, on the other hand, you don't want to put the definition of B before the definition of A, and only have a forward reference to it, the compiler can't work out how big the B object it is. It needs to know how big a B is to determine how much space to allow for bb in A. So it won't be able to compile A without B.
In your second case, you instead use a pointer to a B. Pointers are the same size whatever they point at. That way the complier can work out how big A is, and only needs the full declaration of B before it actually uses one, for example by calling B's constructor in the `new B()` expression. | pointer to objects within a class, C++ newbie question | [
"",
"c++",
"class",
"pointers",
"oop",
""
] |
I'd like to write a service that periodically checks a POP3 account for new messages and based on custom business logic forwards the messages to an appropriate "To", and possibly changes the "From" as well. I might need to keep some messages on the server until certain conditions are ready for them to be forwarded.
I found a sample using Chilkat .NET components that might work:
<http://www.example-code.com/csharp/pop3_forwarder.asp>
My question is: Are there any other examples of this in the .NET space using any other components?
Thanks! | The following SO questions/answers might help finding components for the POP3 part of your porject:
* [Reading Email using Pop3 in C#](https://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c#102135)
* [Free POP3 .NET library?](https://stackoverflow.com/questions/26606/free-pop3-net-library)
And you can use [SmtpClient](http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx) in *System.Net.Mail* for sending the mails:
* [Sending E-mail using C#](https://stackoverflow.com/questions/449887/sending-e-mail-using-c) | Try [Mail.dll .NET email component](http://www.lesnikowski.com/mail/). It has SSL support, POP3 and SMTP clients.
```
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("mail.host.com"); // Connect to the server
pop3.Login("user", "password");
foreach(string uid in pop3.GetAll())
{
// Receive mail
IMail mail = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(mail.Subject);
}
pop3.Close(true);
}
```
You can [download it here](http://www.lesnikowski.com/mail/) | Pop3 to SMTP message custom forwarder in C# | [
"",
"c#",
"smtp",
"pop3",
"forwarding",
""
] |
I need to quickly implement a very small C or C++ TCP server/client solution. This is simply to transfer literally an array of bytes from one computer to another - doesn't need to be scalable / over-complicated. The simpler the better. Quick and dirty if you can.
I tried to use the code from this tutorial, but I couldn't get it to build using g++ in Linux: <http://www.linuxhowtos.org/C_C++/socket.htm>
If possible, I'd like to avoid 3rd party libraries, as the system I'm running this on is quite restricted. This must be C or C++ as the existing application is already implemented.
Thanks to **emg-2**'s answer, I managed to make the above mentioned code sample compatible with C++ using the following steps:
Add these headers to both client and server:
```
#include <cstdlib>
#include <cstring>
#include <unistd.h>
```
In [server.c](http://www.linuxhowtos.org/data/6/server.c), change the type of clilen to socklen\_t.
```
int sockfd, newsockfd, portno/*, clilen*/;
socklen_t clilen;
```
In [client.c](http://www.linuxhowtos.org/data/6/client.c), change the following line:
```
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) { ... }
```
To:
```
if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
``` | I've used [Beej's Guide to Network Programming](https://www.beej.us/guide/bgnet/html) in the past. It's in C, not C++, but the examples are good. Go directly to [section 6](https://www.beej.us/guide/bgnet/html/#client-server-background) for the simple client and server example programs. | If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like `boost::asio` are imho quite complicated when it comes to short and simple "hello world" example.
To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
<http://www.linuxhowtos.org/data/6/server.c>
<http://www.linuxhowtos.org/data/6/client.c>
from: <http://www.linuxhowtos.org/C_C++/socket.htm>
1. Add following includes to both files:
```
#include <cstdlib>
#include <cstring>
#include <unistd.h>
```
2. In [client.c](http://www.linuxhowtos.org/data/6/client.c), change the line:
```
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
```
to:
```
if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
```
As you can see in C++ an explicit cast is needed. | What is a simple C or C++ TCP server and client example? | [
"",
"c++",
"tcp",
"client-server",
""
] |
New to unit testing and have an app that is spread out over several dlls. What are some suggestions for unit testing the app? If I put the unit tests in their own project, i can only test the published interface for each dll. Is that what most people do? Or should I put the unit tests in with the code in the dlls and test there? What would be the best way to coordinate all the tests at that point?
Most of the examples I've seen for using the various frameworks don't really address this and I've search elsewhere but haven't found much information.
Thanks.
Update:
I guess to clarify a bit I have class A and class B in a dll. Class B is used by Class A, but only Class A is exposed. I'm wanting to get unit tests in place before refactoring this existing code.
So the question is should I put unit tests in with the dll code to test class A and class B directly and/or have the unit tests in a separate project and test class A and class B through the exposed class A? | Unit testing in C++ means rather class testing. DLL testing would be rather integration testing. Both are necessary, but it's better to test things at as low level as possible. Take a look on v-model: <http://en.wikipedia.org/wiki/V-Model_(software_development)>. | My home-rolled approach to this is to build two different targets:
* the DLL itself
* a test executable
The code base is the same except for main.cpp which will contain a DLL main for the DLL and a standard C/C++ **int main()** for the test executable. All the unit tests are in-line with the actual code, controlled by a preprocessor #define:
```
#ifdef TESTING
tests here
#endif
```
The main() for the executable calls all the tests via a registration framework.
Most of the time I work with the executable version with TESTING defined. When I want to build the DLL, I switch targets and undefine TESTING. | Seeking suggestions for Unit Testing C++ app spread over several dlls | [
"",
"c++",
"unit-testing",
"dll",
""
] |
Why is it that non-integral enums cannot be created? I want to know if this
is a language design decision, or if there are issues with implementing this in the compiler.
In other words, is it feasible to implement non-integral enums into the language, but there just isn't a justifiable need? Or if it isn't feasible but is justifiable, what impediment are in the way?
Someone give me the skinny on what the reason or rationale is for not having this available in C#, pretty please. | Only the designers of the language can tell you why they didn't allow for non-integral enumerations but I can tell you the most likely explanation.
The original C didn't do it because it was unnecessary for its purposes (a systems programming language). C++ didn't do it since it was based on C and you could emulate it with classes anyway. C# probably doesn't do it for the same reasons.
This is just guesswork on my part since I wasn't involved in the design of any of those languages.
Once you've decided to go the way of classes (DateTime), there's little reason to not go all the way. If you want to use enum's, you can create the enums as sequential integers starting with zero and have an array of DateTime values using those enums as indexes.
But I'd just have a Holiday class which provided the whole kit and kaboodle within the class: the constants, the get() routine to return a DateTime based on those constants and so on.
That gives you true encapsulation and the ability to chage the implementation totally without affecting the interface. Why toss away one of the benefits of OOP? | There's no technical reason why it couldn't be done, but then, we are really more talking about a set of constants (perhaps within a common namespace, if they're related).
In an enum, the numerical value is generally secondary.
In the following:
```
enum Fruit {
Apple,
Orange,
Pear,
Peach
}
```
we are only describing a set of named constants. We are saying that a variable of type Fruit can take one of these four values. What the integer value of each one is, is really not relevant. As long as I only refer to them by name, it doesn't matter if the value representing Apple is 0, 1, 32, -53 or 0.002534f.
Most languages do allow you to specify the value that should represent each, but that's really secondary. It's sometimes useful, but it's not part of the core purpose with enums. They are simply there to give you a set of related named constants without having to specify an integer ID for each.
Further, enums are often used to specify optional flags that can be combined with bitwise operations. That is trivial to implement if each value is represented by an integer (then you just have to pick an integer that uses the bit pattern you want).
Floating-point values wouldn't be useful in this context. (bit-wise and/or operations don't make much sense on floating-point values) | Why no non-integral enums? | [
"",
"c#",
"enums",
"language-design",
""
] |
I have the following code inside main method:
```
List<Rectangle> rects = new List<Rectangle>();
for (int i = 0; i < 5; i++)
{
rects.Add(new Rectangle(1, 1, 1, 1));
}
foreach (Rectangle item in rects)
{
Console.WriteLine(item);
}
rects[1].Inflate(100, 100);
foreach (Rectangle item in rects)
{
Console.WriteLine(item);
}
```
In the presented code rects[1] remains unchanged. This is because indexer (which still is a special method) returned the *copy* of the rectangle structure. In this case the elements were located on *heap*. The indexer returned the new *copy* of the element by placing the new *copy* on the stack (since the Rectangle is a value type).
So far so good...
Later I have created an array of Rectangle structures in the Program class:
```
Rectangle[] rect = new Rectangle[] { new Rectangle(1, 1, 1, 1), new Rectangle(1, 1, 1, 1) };
```
In the main method:
```
Program p = new Program();
p.rect[1].Inflate(100, 100);
foreach (var item in p.rect)
{
Console.WriteLine(item);
}
```
I expected the indexer of rect array also to return *copy* of the rectangle structure, but this time the original element (which was also located on the *heap*) was changed.
Why is that? Does the array indexer works in a different way?
Kind Regards
PK | From this you conclude that the indexer on a list is a method call that places the value of a value type on the stack when returning from a method and that the array indexer is actually translated in code to the calculation of an offset from the start of the array and is a direct memory reference. | Yes. An array indexer represents the variable to be changed directly. An indexer is basically a method with an index parameter with syntactic sugar applied to it.
The same difference applies to fields and properties.
If you were returning a reference type from the indexer, it wouldn't make much a difference since it would refer to the same object nevertheless. But when you return a `struct` instance (or any value type for that matter), the value is copied when returned and you are trying to modify the copy, which is pretty much useless. | C# Indexer memory question | [
"",
"c#",
"stack",
"heap-memory",
"indexer",
""
] |
I'm working on building my own base user interface classes. On them, I want them to all have similar "common" properties and methods. I could define an interface class, but interface appears to only allow abstract methods, and no properties.
I don't want to copy the otherwise exact same code to each class, but not sure how to implement... Ex: I want this common stuff to be applicable to Buttons, Textbox, Checkbox, Listbox, etc user controls.
Suggestions??? | I myself come from a C++-background where multi-inheritance is allowed and used extensibly, so I often ran into the same problems as you.
The first thing you need to do is to read up on mix-ins - here you'll prolly notice that you've used them yourself all along, without ever naming them.
Second step is to start to recognize your mixins whenever you need them, and you'll often find out that you might as well use them via composition.
Third step is to implement them using composition... Yes, i hate this too, but there's no way around it if you wanna go .NET (or Java or...) :)
What you should use inheritence for is not for your mixins, but for stuff that actually identifies your items. I recommend looking at the .NET hierachy for some of the common controls (textbox and the likes) to get some inspiration.
Good luck | In this situation I usually use abstract classes. Create your base abstract class and then inherit it from your new controls. | Common Properties and Methods assigned to different subclass types | [
"",
"c#",
"multiple-inheritance",
""
] |
This seems like a fundamentally simple question. I have a WinForms dialog box with a listbox. This control is *not* populated via data-binding but is filled with calls to
```
listBox.Items.Add (obj);
```
It is possible that this call can be made asynchronously from various places and I would like to hook the listbox and watch for changes in its data members so that I can perform other UI changes (such as enable or disable controls which interact with the listbox based on the number of items in the list).
Unfortunately, unless I'm being completely clueless, there does not seem to be an event or virtual method which can be hooked to detect this. I can hook for select changes and (for CheckedListBox) I can hook for check-state changes. But not for changes to the underlying data collection.
I know this is possible in Win32 (there is a window message for this). What am I missing?
---
[Edited by Simon]
## Solution
I was pointed to the correct solution (which I have marked as the accepted answer) which is to override the WndProc method of the ListBox and handle the listbox messages manually. Here is the solution that I settled on (and works). It could be modified to provide more details in the event, or split the messages into separate events, but for my needs this is sufficient.
```
using System;
using System.Windows.Forms;
public class CheckedListBoxEx : CheckedListBox
{
public CheckedListBoxEx() { }
private const int LB_ADDSTRING = 0x180;
private const int LB_INSERTSTRING = 0x181;
private const int LB_DELETESTRING = 0x182;
private const int LB_RESETCONTENT = 0x184;
protected override void WndProc(ref Message m)
{
if (m.Msg == LB_ADDSTRING ||
m.Msg == LB_INSERTSTRING ||
m.Msg == LB_DELETESTRING ||
m.Msg == LB_RESETCONTENT)
{
ItemsChanged(this, EventArgs.Empty);
}
base.WndProc(ref m);
}
public event EventHandler ItemsChanged = delegate { };
}
``` | I don't know of any event that you can watch to show that an item has been added to a ListBox. Perhaps you can use the Win32 method you described instead (i.e. grab a handle, use WndProc, etc.).
Alternately, perhaps you can use another class that adds items instead. For example, rather than calling the Add method on the ListBox directly, you could have user-actions call the Add method inside the new class which then adds the item to the ListBox. You could set an event inside that class that would allow you to watch what's been added.
I also like the idea of subclassing the ListBox as mentioned by another poster.... | Here's a post on another forum that recommends creating a child class that includes that behaviour.
[<http://www.eggheadcafe.com/forumarchives/netframeworkcompactframework/jul2005/post23265940.asp>](http://www.eggheadcafe.com/forumarchives/netframeworkcompactframework/jul2005/post23265940.asp) | How to detect if items are added to a ListBox (or CheckedListBox) control | [
"",
"c#",
".net",
"winforms",
"listbox",
"checkedlistbox",
""
] |
I have a website with PHP files and other. I would like to do one-click synchronisation between my local copy of a website and my website on the server. It would be nice if there was be a command line utility or plugin to Eclipse PDT to do this. | I've found WinSCP. It's FTP, free and Open Source:
<http://winscp.net/eng/docs/start>
And it works from command line with comparision of files (to synchronise it) | I would recommend [lftp](http://lftp.yar.ru/). It's a sophisticated, scriptable command-line FTP client.
> ```
> lftp has builtin mirror which can download or update a whole
> directory tree. There is also reverse mirror (mirror -R)
> which uploads or updates a directory tree on server. Mirror
> can also synchronize directories between two remote servers,
> using FXP if available.
> ```
lftp -f mirror.sh
**mirror.sh**
```
open sftp://<username>:<password>@<ip address>
mirror -c /<source> /<destination>
exit
``` | How to synchronise FTP directory from command line? | [
"",
"php",
"ftp",
"synchronization",
"copy",
""
] |
I always used `Nullable<>.HasValue` because I liked the semantics. However, recently I was working on someone else's existing codebase where they used `Nullable<> != null` exclusively instead.
Is there a reason to use one over the other, or is it purely preference?
1. ```
int? a;
if (a.HasValue)
// ...
```
vs.
2. ```
int? b;
if (b != null)
// ...
``` | The compiler replaces `null` comparisons with a call to `HasValue`, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues. | I prefer `(a != null)` so that the syntax matches reference types. | What is the difference between Nullable<T>.HasValue or Nullable<T> != null? | [
"",
"c#",
".net",
"null",
"nullable",
""
] |
im doing some queries in Zend Framework and i need to make sure no SQL injection is possible in the next kind of formats. I can use mysql\_escape(deprecated) and wont do all the work. If i try to use real\_mysql\_escape it wont be able to grab the conection with the database and i cant find how zend\_filter would solve the problem.
The query im doing (simplied) have the next sintaxes:
```
$db = Zend_Registry::get('db');
$select = "SELECT COUNT(*) AS num
FROM message m
WHERE m.message LIKE '".$username." %'";
$row = $db->fetchRow($select);
```
What is the best way to prevent SQL INJECTION with this framework? | Easy:
```
$db->quote($username);
```
So:
```
$username = $db->quote($username . '%');
$select = 'SELECT COUNT(*) AS num
FROM message m
WHERE m.message LIKE ' . $username;
$row = $db->fetchRow($select);
``` | ```
$sql = 'SELECT * FROM messages WHERE username LIKE ?';
$row = $db->fetchRow($sql, $username);
```
**Reference**: <http://framework.zend.com/manual/en/zend.db.html> | Php on zend, how to escape a variable for a query? | [
"",
"php",
"mysql",
"zend-framework",
"sql-injection",
""
] |
```
INSERT INTO `tableA`
SELECT `Col1`,
`Col2`,
NOW()
FROM `tableB`
WHERE tableA.Col1 is not already in tableB.Col1
```
I can't get the WHERE clause right to ensure that the record copied from tableA only appears in table B once... | should read:
where tableA.col1 not in (select col1 from table B) | You really want the SQL-2003 MERGE statement. I've included the BNF for the MERGE statement (section 14.9, p837) from the standard (grotesque, but that's the SQL standard for you) below. When translated, that might translate to:
```
MERGE INTO TableA
USING TableB ON TableA.Col1 = TableB.Col1
WHEN NOT MATCHED INSERT (Col1, Col2, Col3)
VALUES(TableB.Col1, TableB.Col2, NOW());
```
I have not run that past an SQL DBMS that knows about the MERGE statement - that means there are probably bugs in it. Note that there is a WHEN MATCHED clause which can take an UPDATE in the standard; IBM DB2 also supports a DELETE clause which is not in the 2003 standard (not sure about the 2008 standard).
---
### 14.9 `<merge statement>` (p837)
> Conditionally update rows of a table, or insert new rows into a table, or both.
```
<merge statement> ::=
MERGE INTO <target table> [ [ AS ] <merge correlation name> ]
USING <table reference> ON <search condition>
<merge operation specification>
<merge correlation name> ::=
<correlation name>
<merge operation specification> ::=
<merge when clause> ...
<merge when clause> ::=
<merge when matched clause> |
<merge when not matched clause>
<merge when matched clause> ::=
WHEN MATCHED THEN <merge update specification>
<merge when not matched clause> ::=
WHEN NOT MATCHED THEN <merge insert specification>
<merge update specification> ::= UPDATE SET <set clause list>
<merge insert specification> ::=
INSERT [ <left paren> <insert column list> <right paren> ]
[ <override clause> ] VALUES <merge insert value list>
<merge insert value list> ::=
<left paren> <merge insert value element>
[ { <comma> <merge insert value element> }... ] <right paren>
<merge insert value element> ::=
<value expression> |
<contextually typed value specification>
``` | SQL INSERT/SELECT where not in insert table | [
"",
"sql",
"insert",
""
] |
```
function Gadget(name, color)
{
this.name = name;
this.color = color;
}
Gadget.prototype.rating = 3
var newtoy = new Gadget("webcam", "black")
newtoy.constructor.prototype.constructor.prototype.constructor.prototype
```
It always returns the object with rating = 3.
But if I do the following:
```
newtoy.__proto__.__proto__.__proto__
```
The chain ends up returning `null`.
Also in Internet Explorer how would I check the null if there is not a `__proto__` property? | I've been trying to wrap my head around this recently and finally came up with this "map" that I think sheds full light over the matter
<https://i.stack.imgur.com/KFzI3.png>

I know I'm not the first one making this up but it was more interesting figuring it out that finding it :-). Anyway, after that I found e.g. this another diagram that I think says basicly the same:
[Javascript object layout](http://www.mollypages.org/tutorials/js.mp)
The most surprising thing for me was discovering that `Object.__proto__` points to `Function.prototype`, instead of `Object.prototype`, but I'm sure there's a good reason for that :-)
I paste the code mentioned in the image here as well for if anyone wants to test it. Note that some properties are added to the objects for making easy to know where we are after some jumps:
```
Object.O1='';
Object.prototype.Op1='';
Function.F1 = '';
Function.prototype.Fp1 = '';
Cat = function(){};
Cat.C1 = '';
Cat.prototype.Cp1 = '';
mycat = new Cat();
o = {};
// EDITED: using console.dir now instead of console.log
console.dir(mycat);
console.dir(o);
``` | `constructor` is a pre-defined [[DontEnum]] property of the object pointed to by the `prototype` property of a function object and will initially point to the function object itself.
`__proto__` is equivalent to the internal [[Prototype]] property of an object, ie its actual prototype.
When you create an object with the `new` operator, its internal [[Prototype]] property will be set to the object pointed to by the constructor function's `prototype` property.
This means that `.constructor` will evaluate to `.__proto__.constructor`, ie the constructor function used to create the object, and as we have learned, the `protoype` property of this function was used to set the object's [[Prototype]].
It follows that `.constructor.prototype.constructor` is identical to `.constructor` (as long as these properties haven't been overwritten); see [here](http://joost.zeekat.nl/constructors-considered-mildly-confusing.html) for a more detailed explanation.
If `__proto__` is available, you can walk the actual prototype chain of the object. There's no way to do this in plain ECMAScript3 because JavaScript wasn't designed for deep inheritance hierarchies. | How does __proto__ differ from constructor.prototype? | [
"",
"javascript",
"inheritance",
"prototype-programming",
""
] |
I have a count variable that should get counted up by a few processes I forked and used/read by the mother process.
I tried to create a pointer in my main() function of the mother process and count that pointer up in the forked children. That does not work! Every child seems to have it's own copy even though the address is the same in every process.
What is the best way to do that? | Each child gets its own copy of the parent processes memory (at least as soon as it trys to modify anything). If you need to share betweeen processes you need to look at shared memory or some similar IPC mechanism.
BTW, why are you making this a community wiki - you may be limiting responses by doing so. | 2 processes cannot share the same memory. It is true that a forked child process will share the same underlying memory after forking, but an attempt to write to this would cause the operating system to allocate a new writeable space for it somewhere else.
Look into another form of [IPC](http://en.wikipedia.org/wiki/Inter-process_communication) to use. | C++: Is it possible to share a pointer through forked processes? | [
"",
"c++",
"pointers",
"fork",
""
] |
I'm using this code to prevent a second instance of my program from running at the same time, is it safe?
```
Mutex appSingleton = new System.Threading.Mutex(false, "MyAppSingleInstnceMutx");
if (appSingleton.WaitOne(0, false)) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
appSingleton.Close();
} else {
MessageBox.Show("Sorry, only one instance of MyApp is allowed.");
}
```
I'm worried that if something throws an exception and the app crashes that the Mutex will still be held. Is that true? | In general yes this will work. However the devil is in the details.
Firstly you want to close the mutex in a `finally` block. Otherwise your process could abruptly terminate and leave it in a signaled state, like an exception. That would make it so that future process instances would not be able to start up.
Unfortunately though, even with a `finally` block you must deal with the potential that a process will be terminated without freeing up the mutex. This can happen for instance if a user kills the process through TaskManager. There is a race condition in your code that would allow for a second process to get an `AbandonedMutexException` in the `WaitOne` call. You'll need a recovery strategy for this.
I encourage you to read up on [the details of the Mutex class](http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx). Using it is not always simple.
---
Expanding upon the race condition possibility:
The following sequence of events can occur which would cause a second instance of the application to throw:
1. Normal process startup.
2. Second process starts up and aquires a handle to the mutex but is switched out before the `WaitOne` call.
3. Process #1 is abruptly terminated. The mutex is not destroyed because process #2 has a handle. It is instead set to an abandoned state.
4. The second process starts running again and gets an `AbanonedMutexException`. | It is more usual and convenient to use Windows events for this purpose. E.g.
```
static EventWaitHandle s_event ;
bool created ;
s_event = new EventWaitHandle (false,
EventResetMode.ManualReset, "my program#startup", out created) ;
if (created) Launch () ;
else Exit () ;
```
When your process exits or terminates, Windows will close the event for you, and destroy it if no open handles remain.
*Added*: to manage sessions, use `Local\` and `Global\` prefixes for the event (or mutex) name. If your application is per-user, just append a suitably mangled logged-on user's name to the event name. | Is using a Mutex to prevent multiple instances of the same program from running safe? | [
"",
"c#",
"winforms",
"mutex",
"single-instance",
""
] |
I spawn a thread using `AfxBeginThread` which is just an infinite while loop:
```
UINT CMyClass::ThreadProc( LPVOID param )
{
while (TRUE)
{
// do stuff
}
return 1;
}
```
How do I kill off this thread in my class destructor?
I think something like
```
UINT CMyClass::ThreadProc( LPVOID param )
{
while (m_bKillThread)
{
// do stuff
}
return 1;
}
```
and then set `m_bKillThread` to `FALSE` in the destructor. But I still need to wait in the destructor until the thread is dead. | **Actively killing the thread:**
Use the return value of `AfxBeginThread` (`CWinThread*`) to get the thread handle (`m_hThread`) then pass that handle to the TerminateThread Win32 API. This is not a safe way to terminate threads though, so please read on.
**Waiting for the thread to finish:**
Use the return value of `AfxBeginThread` (`CWinThread*`) to get the member m\_hThread, then use `WaitForSingleObject(p->m_hThread, INFINITE);` If this function returns `WAIT_OBJECT_0`, then the thread is finished. Instead of `INFINITE` you could also put the number of milliseconds to wait before a timeout happens. In this case `WAIT_TIMEOUT` will be returned.
**Signaling to your thread that it should end:**
Before doing the `WaitForSingleObject` just set some kind of flag that the thread should exit. Then in your main loop of the thread you would check for that bool value and break the infinite loop. In your destructor you would set this flag then do a `WaitForSingleObject`.
**Even better ways:**
If you need even more control you can use something like [boost conditions](http://www.boost.org/doc/libs/1_34_0/doc/html/boost/condition.html). | BTW, About TerminateThread(), use it this way.
```
DWORD exit_code= NULL;
if (thread != NULL)
{
GetExitCodeThread(thread->m_hThread, &exit_code);
if(exit_code == STILL_ACTIVE)
{
::TerminateThread(thread->m_hThread, 0);
CloseHandle(thread->m_hThread);
}
thread->m_hThread = NULL;
thread = NULL;
}
``` | How to kill a MFC Thread? | [
"",
"c++",
"multithreading",
"mfc",
""
] |
i've written a console application deploy.exe which runs a batch script.
```
Process p1 = new Process();
p1.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "installer.bat";
p1.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p1.Start();
p1.WaitForExit();
p1.Close();
```
the installer.bat conatins the following command.
\shared1\lists\list1.cmd
If i run the executable byitself it runs successfully.
However i needed it to run in a windows installer project. So i made a setup and deployment project and added the deploy.exe successfully as custom action upon install.
It runs fine but when it starts to execute the command i get this error
"The filename, directory name, or volume label syntax is incorrect".
any help? | the error seems to be inside the script which was being executed. It contained environment variables %kind%, which were not acceptable by the installer for some reason. So it was working properly outside the installer and not properly when the installer was calling it. | Try printing out what the value of `AppDomain.CurrentDomain.BaseDirectory` is. It may not be where `installer.bat` is when you are installing it.
Also, you tried adding the bat file to a custom action (if that is even possible)?
And, would it possible to move what is in the bat to the exe? | The filename, directory name, or volume label syntax is incorrect, c# | [
"",
"c#",
".net",
"batch-file",
""
] |
Here is an interesting issue I noticed when using the `Except` Operator:
I have list of users from which I want to exclude some users:
The list of users is coming from an XML file:
The code goes like this:
```
interface IUser
{
int ID { get; set; }
string Name { get; set; }
}
class User: IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" +Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("Users.xml");
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
```
When I call `User.GetMatchingUsers(users)` I get 2 matches as expected.
The issue is that when I call `users.Except(matches)` The matching users are not being excluded at all! I am expecting 6 users ut "excludes" contains all 8 users instead.
Since all I'm doing in `GetMatchingUsers(IEnumerable<IUser> users)` is taking the `IEnumerable<IUser>` and just returning
the `IUsers` whose ID's match( 2 IUsers in this case), my understanding is that by default `Except` will use reference equality
for comparing the objects to be excluded. Is this not how `Except` behaves?
What is even more interesting is that if I materialize the objects using `.ToList()` and then get the matching users, and call `Except`,
everything works as expected!
Like so:
```
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>().ToList(); //explicity materializing all objects by calling ToList()
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes now contains 6 users as expected
```
I don't see why I should need to materialize objects for calling `Except` given that its defined on `IEnumerable<T>`?
Any suggesstions / insights would be much appreciated. | I think I know why this fails to work as expected. Because the initial user list is a LINQ expression, it is re-evaluated each time it is iterated (once when used in `GetMatchingUsers` and again when doing the `Except` operation) and so, new user objects are created. This would lead to different references and so no matches. Using `ToList` fixes this because it iterates the LINQ query once only and so the references are fixed.
I've been able to reproduce the problem you have and having investigated the code, this seems like a very plausible explanation. I haven't proved it yet, though.
***Update***
I just ran the test but outputting the `users` collection before the call to `GetMatchingUsers`, in that call, and after it. Each time the hash code for the object was output and they do indeed have different values each time indicating new objects, as I suspected.
Here is the output for each of the calls:
```
==> Start
ID=1, Name=Jeff, HashCode=39086322
ID=2, Name=Alastair, HashCode=36181605
ID=3, Name=Anthony, HashCode=28068188
ID=4, Name=James, HashCode=33163964
ID=5, Name=Tom, HashCode=14421545
ID=6, Name=David, HashCode=35567111
<== End
==> Start
ID=1, Name=Jeff, HashCode=65066874
ID=2, Name=Alastair, HashCode=34160229
ID=3, Name=Anthony, HashCode=63238509
ID=4, Name=James, HashCode=11679222
ID=5, Name=Tom, HashCode=35410979
ID=6, Name=David, HashCode=57416410
<== End
==> Start
ID=1, Name=Jeff, HashCode=61940669
ID=2, Name=Alastair, HashCode=15193904
ID=3, Name=Anthony, HashCode=6303833
ID=4, Name=James, HashCode=40452378
ID=5, Name=Tom, HashCode=36009496
ID=6, Name=David, HashCode=19634871
<== End
```
And, here is the modified code to show the problem:
```
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System;
interface IUser
{
int ID
{
get;
set;
}
string Name
{
get;
set;
}
}
class User : IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" + Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
OutputUsers(users);
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
public static void OutputUsers(IEnumerable<IUser> users)
{
Console.WriteLine("==> Start");
foreach (IUser user in users)
{
Console.WriteLine("ID=" + user.ID.ToString() + ", Name=" + user.Name + ", HashCode=" + user.GetHashCode().ToString());
}
Console.WriteLine("<== End");
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = new XDocument(
new XElement(
"Users",
new XElement("User", new XAttribute("id", "1"), new XAttribute("name", "Jeff")),
new XElement("User", new XAttribute("id", "2"), new XAttribute("name", "Alastair")),
new XElement("User", new XAttribute("id", "3"), new XAttribute("name", "Anthony")),
new XElement("User", new XAttribute("id", "4"), new XAttribute("name", "James")),
new XElement("User", new XAttribute("id", "5"), new XAttribute("name", "Tom")),
new XElement("User", new XAttribute("id", "6"), new XAttribute("name", "David"))));
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{
ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
User.OutputUsers(users);
var matches = User.GetMatchingUsers(users);
User.OutputUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
``` | a) You need to override GetHashCode function. **It MUST return equal values for equal IUser objects**. For example:
```
public override int GetHashCode()
{
return ID.GetHashCode() ^ Name.GetHashCode();
}
```
b) You need to override object.Equals(object obj) function in classes that implement IUser.
```
public override bool Equals(object obj)
{
IUser other = obj as IUser;
if (object.ReferenceEquals(obj, null)) // return false if obj is null OR if obj doesn't implement IUser
return false;
return (this.ID == other.ID) && (this.Name == other.Name);
}
```
c) As an alternative to *(b)* IUser may inherit IEquatable:
```
interface IUser : IEquatable<IUser>
...
```
User class will need to provide bool Equals(IUser other) method in that case.
That's all. Now it works without calling .ToList() method. | LINQ Except operator and object equality | [
"",
"c#",
"linq",
""
] |
I'm trying to display Japanese characters on a PHP page. No loading from the database, just stored in a language file and echo'ed out.
I'm running into a weird scenario. I have the page properly setup with UTF-8 and I test a sample page on my local WAMP server and it works.
The moment I tested it out our development and production servers the characters don't display properly.
This leads me to believe then that it's a setting in php.ini. But I haven't found much information about this so I'm not really sure if this is the issue.
Is there something fundamental I'm missing?
Thanks | Since you've stated that it is working in your development environment and not in your live, you might want to check Apache's [AddDefaultCharset](http://httpd.apache.org/docs/2.0/mod/core.html#AddDefaultCharset) and set this to UTF-8, if it's not already.
I tend to make sure the following steps are checked
1. PHP Header is sent in UTF-8
2. Meta tag is set to UTF-8 (Content-Type)
3. Storage is set to UTF-8
4. Server output is set to UTF-8
That seems to work for me. Hope this helps. | You have to deliver the documents with the proper encoding declaration in the [HTTP header field `Content-Type`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17).
In PHP you do this via the [`header` function](http://docs.php.net/header) before the first data has been send to the client, so preferably as one of the first statements:
```
<?php
header('Content-Type: text/html;charset=utf-8');
// the rest
``` | How to display Japanese characters on a php page? | [
"",
"php",
"unicode",
"character-encoding",
""
] |
I'm trying to make a small GUI app and I want to use MigLayout with it.
As Java newbie I don't know how to get MigLayout to work with my code and I'm running out of ideas.
My project source code is in ~/git/project/src/qdb/
The qdb is my java package name. I downloaded miglayout-3.7-swing.jar and miglayout-3.7.jar and placed them to my project sources and tried to compile the code but I get errors pointing to "`new MigLayout()`" stating "cannot find symbol".
I was in src dir and used "`javac qdb/*.java`" to compile (`*` gets expanded).
I also tried to point classpath to my sources like: "`javac -classpath /home/user/git/project/src/qdb/ qdb/*.java`" but I still get the error.
Then I've also tried to put the jar files to ~/jars/ and use that as classpath but still the same error follows.
So, how to get MigLayout working? | Simply add the `miglayout-3.7-swing.jar` to your classpath:
```
javac -classpath /your/path/to/miglayout-3.7-swing.jar qdb/*.java
```
(as illustrating in this thread [Installing Mig Layout](http://www.migcalendar.com/forums/viewtopic.php?f=8&t=2307&sid=762dc6bd988a69f6b13c0b91331d3781))
---
If you can compile them (with the above line),
but can not *execute* the resulting program, you also need to add to the `java` classpath the library
```
java -classpath /your/path/to/miglayout-3.7-swing.jar:/your/project/compiledClass/dir qdb.yourMainClass
``` | If you are going to put it into a .jar file, you'll need to specify the Class-Path in the manifest file:
`Class-Path: /your/path/to/miglayout.jar` | How to get MigLayout to work with my project? | [
"",
"java",
"classpath",
"miglayout",
""
] |
I have the following tables (and example values):
```
**user:**
user_id (1, 2, 3)
username (john33, reddiamond...)
password (pass1, pass2...)
**session:**
session_id (4,5, 6)
user_id (1, 2, 3)
**activity**
activity_id (1, 2)
name (running, walking...)
**user_activity**
user_activity_id (1, 2, 3, 4, 5)
session_id (4, 5)
activity_id (1, 2)
```
All columns with the same name are related. In the table `user_activity` there are rows which describe what is the session's activity and the activity refers to users.
However I would like to get the table which describes what the user is currently doing:
```
**result**
username(john33)
activity.name(walking)
```
What is the SQL statement that gets the result table?
(I'm using MSSQL). | ```
SELECT u.username, a.name
FROM user_activity ua
INNER JOIN session s
ON ua.session_id = s.session_id
INNER JOIN user u
ON s.user_id = u.user_id
INNER JOIN activity a
ON ua.activity_id = a.activity_id
``` | I assume `session.session_id` and `user_activity.user_activity_id` are `IDENTITY` columns, so they are monotonically increasing. Therefore they are unique and the greatest value indicates the most recent entry.
So what you need to do is:
* Match `user` to a corresponding row in `session` with the greatest `session_id` value (that is, no other row is found with the same `user_id` and a greater `session_id`).
* Then match that row in `session` to a corresponding row in `user_activity` with the greatest `user_activity_id`.
* Then match that row in `user_activity` to a correspond row in `activity` to get the `name`.
Here's a query that should achieve this (though I have not tested it):
```
SELECT u.username, a.name
FROM user u
JOIN session s1 ON (u.user_id = s1.user_id)
LEFT OUTER JOIN session s2 ON (u.user_id = s2.user_id
AND s1.session_id < s2.session_id)
JOIN user_activity ua1 ON (ua1.session_id = s1.session_id)
LEFT OUTER JOIN user_activity ua2 ON (ua2.session_id = s1.session_id
AND ua1.user_activity_id < ua2.user_activity_id)
JOIN activity a ON (a.activity_id = ua1.activity_id)
WHERE s2.session_id IS NULL AND ua2.user_activity_id IS NULL;
```
Here's an alternative form of query that should get the same result, and might be easier to visualize:
```
SELECT u.username, a.name
FROM user u
JOIN session s1 ON (u.user_id = s1.user_id)
JOIN user_activity ua1 ON (ua1.session_id = s1.session_id)
JOIN activity a ON (a.activity_id = ua1.activity_id)
WHERE s1.session_id = (
SELECT MAX(s2.session_id) FROM session s2
WHERE s2.user_id = u.user_id)
AND ua1.user_activity_id = (
SELECT MAX(ua2.user_activity_id) FROM user_activity ua2
WHERE ua2.session_id = s1.session_id);
``` | How do I join multible tables? | [
"",
"sql",
"sql-server",
"join",
""
] |
What is the safe method to access an array element, without throwing `IndexOutOfRangeException`, something like `TryParse`, `TryRead`, using extension methods or LINQ? | You could use the following extension method.
```
public static bool TryGetElement<T>(this T[] array, int index, out T element) {
if ( index < array.Length ) {
element = array[index];
return true;
}
element = default(T);
return false;
}
```
Example:
```
int[] array = GetSomeArray();
int value;
if ( array.TryGetElement(5, out value) ) {
...
}
``` | Use the `System.Linq` [`ElementAtOrDefault`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.elementatordefault) method. It handles an out-of-range access without throwing an exception.
It returns a default value in the case of an invalid index.
```
int[] array = { 4, 5, 6 };
int a = array.ElementAtOrDefault(0); // output: 4
int b = array.ElementAtOrDefault(1); // output: 5
int c = array.ElementAtOrDefault(-1); // output: 0
int d = array.ElementAtOrDefault(1000); // output: 0
```
**See Also**: [DotNetPearls - ElementAt](https://www.dotnetperls.com/elementatordefault) | Safe element of array access | [
"",
"c#",
".net",
"arrays",
"tryparse",
""
] |
What is the best data type to use for money in C#? | As it is described at [decimal](https://msdn.microsoft.com/en-us/library/364x0z75(v=vs.140).aspx) as:
> The decimal keyword indicates a 128-bit data type. Compared to
> floating-point types, the decimal type has more precision and a
> smaller range, which makes it **appropriate for financial and monetary**
> calculations.
You can use a decimal as follows:
```
decimal myMoney = 300.5m;
``` | [System.Decimal](http://msdn.microsoft.com/en-us/library/system.decimal.aspx)
> The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.
I'd like to point to [this excellent answer](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency/3730040#3730040) by zneak on why double shouldn't be used. | What is the best data type to use for money in C#? | [
"",
"c#",
"types",
"currency",
""
] |
I am using Silverlight with a DDD approach. I have a Person domain object that has properties such as FirstName, LastName, Address, etc. The Person needs to have an Image.
What is the best way to handle this?
I don't really want to put an Windows.Controls.Image property on the Person object because this it will be coupled to Silverlight/WPF and I might want to use this object with some other technology in the future (ASP, WinForms, the next new thing, etc).
I also need to be able to save and load the image somewhere. Is it best practice to save the image to a database or to a file system? I am currently using nHibernate with Microsoft SQL Server, but I also want to be able to support nHibernate with mySql and possibly some other databases. It is also possible that I may some day want to replace nHibernate with entity framework or some other technology (I am abstracting this out using a repository).
Given this information, how should I handle Images for my Person? | Well, `byte[]` (or something wrapping a `byte[]`) is fairly portable... most anything else is going to be implementation specific.
Re database vs file... for the purposes of the client apps (Silverlight, WPF, etc) I would probably expose them via a web page rather than a WCF (etc) call - i.e. some ASP.NET handler (or ASP.NET MVC route) that returns the image via an http call. Then all you **actually** need in the client is the path to the image (`/people/images/12345` or whatever).
For storage - either is usually fine... in SQL Server 2008 you can do both at once with the file-stream type. One of the problems with storing BLOBs in the database is increasing the size, but a few (small) images won't usually hurt (unless you are using SQL Express and have a capped db size). But using the database has the advantage that a single backup includes everything.
Saying that, though: almost every implementation I've done like this has used files. | Are you actually using the binary blob for anything? If not, pass around a reference to something on the filesystem. I'd be worried about pissing things off if you start carrying around `byte[]`'s or something.
If you are WPF, everything takes a URI as an ImageSource:
```
BitmapImage pic = new BitmapImage(new Uri("YourAssembly;components/images/something.jpg"));
```
Keep in mind that if you go my suggested route and move this to Silverlight, you'll need a `crossdomain.xml` file on the domain you are dishing these things out.
If you do need to mess with the binary blob, then keep all that as a `Stream` of some form and have your `Person.Image` class offer a way to get a `StreamReader`/`StreamWriter` like `GetImageStream()`. Then your database stuff can get a `StreamReader` and go write that stuff into the database. Without checking, my guess is just about every database out there that has binary blobs writes out using a `Stream`, not `byte[]`.
...Just some thoughts. Dont forget BitmapImage lets you tap into its Stream too, but you'll have to look that up in the docs :-) Hope that helps. | What data type should I use for an Image in my domain model? | [
"",
"c#",
"domain-driven-design",
""
] |
I hear a lot about boost here and I am beginning to think it could help a lot with my software development. More so in concurrency and memory management in my particular case as we have had a lot of bugs in this area.
What are the key language features I need to polish up on to effectively benefit from using boost and to shorten the learning curve? I have seen that ***function objects*** are commonly used so I would probably need to polish up on that.
Additionally, are there any tutorials and 101 resources I can quickly look at to just get a feel and understanding on using boost.
I realise there is a lot boost offers and I have to pick the right tools for the right job but any leads will help.
### Related
* [How to learn boost](https://stackoverflow.com/questions/379290/how-to-learn-boost) (no longer valid; HTTP return status 404) | Boost has an unimaginable number of libraries.
Easy ones to get started on are
* noncopyable
* array
* circular\_buffer
* foreach
* operators (one of my personal favorites)
* smart\_ptr
* date\_time
More advanced ones include
* lambda
* bind
* iostreams
* serialization
* threads
Getting used to boost takes time, but I assure you it will make your life much better. Plus, looking at how the boost libraries are coded will help you get better at c++ coding, especially templates.
You mentioned what should you look up before trying boost. I agree that function objects are a great thing to research. Also, make sure to look up about template programming. A common problem to make sure you know is when to use the `typename` qualifier for dependent types. For the most part, however, the libraries are very well documented, with examples and reference materials. | Learning boost is discussed [here](https://stackoverflow.com/questions/379290/how-to-learn-boost/). As for language features that are useful? All of them. C++ is a dangerous language to use if you don't know enough of it. RAII, functors/function objects and templates probably cover the most important aspects. Boost is designed similarly to the STL, so knowing your standard library is essential. Boost itself uses a lot of template metaprogramming, but as a library user, you won't often need that (unless you start playing with Boost.MPL)
Bugs related to memory management are a good indicator that it's C++, rather than Boost you need to brush up on. The techniques for handling memory safely are well known, and not specific to Boost. (With the obvious exception of Boost's smart pointers). [RAII](http://en.wikipedia.org/wiki/RAII) is probably the most important concept to understand to deal with this kind of issues. | how do i get started using boost | [
"",
"c++",
"boost",
""
] |
One of the ways to implement Dependency Injection correctly is to separate object creation from business logic. Typically, this involves using a Factory for object creation.
Up until this point, I've never seriously considered using a Factory so I apologize if this question seems a little simplistic:
In all the examples of the Factory Pattern that I've run across, I always see very simple examples that have no parameterization. For example, here's a Factory stolen from [Misko Hevery's](http://misko.hevery.com/) excellent [How To Think About the "new" Operator](http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/) article.
```
class ApplicationBuilder {
House build() {
return new House(new Kitchen(
new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
```
However, what happens if I want each house that I build to have a name? Am I still using the Factory pattern if I re-write this code as follows?
```
class ApplicationBuilder {
House build( const std::string & house_name) {
return new House( house_name,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
```
Note that my Factory method call has changed from this:
```
ApplicationBuilder builder;
House * my_house = builder.build();
```
To this:
```
ApplicationBuilder builder;
House * my_house = builder.build("Michaels-Treehouse");
```
By the way: I think the concept of separating object instantiation from business logic is great, I'm just trying to figure out how I can apply it to my own situation. What confuses me is that all the examples I've seen of the Factory pattern never pass any parameters into the build() function.
To be clear: I don't know the name of the house until the moment before I need to instantiate it. | I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.
However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is *practically* impossible to forward arbitrary number of arguments (even for a sane limit like 6 arguments). Each parameter you forward has to be accepted as `const T&` and `T&` if you want to do it generic.
For more complicated examples, however, you need an exponentially growing set of overloads (for each parameter, a const and a nonconst version) and [perfect forwarding](http://blogs.msdn.com/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx) is not possible at all (so that temporaries are forwarded as temporaries, for example). For the next C++ Standard that issue is solved:
```
class ApplicationBuilder {
template<typename... T>
House *build( T&&... t ) {
return new House( std::forward<T>(t)...,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
};
```
That way, you can call
```
builder.build("Hello", 13);
```
And it will return
```
new House("Hello", 13, new Kitchen(new Sink(...
```
Read the article i linked above. | Not only is is acceptable, but it's *common* to pass parameters to a factory method. Check out [some examples](http://en.wikipedia.org/wiki/Factory_method_pattern). Normally the parameter is a type telling the factory what to make, but there's no reason you can't add other information you need to build an object. I think what you're doing is fine. | Is it OK to pass parameters to a Factory method? | [
"",
"c++",
"dependency-injection",
"factory",
""
] |
I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".
If it matters, Python is installed in this format:
```
/Program Files
/Python
/2.6
python.exe and everything else
/3.0
python.exe and everything else
```
I'm wondering if anyone else has experienced this and what they did to correct the problem. | Yep- it's actually very easy. The scripts in the plugin use 'print' as a keyword which has been changed in Python 3; you just have to convert all 'print' statements in the console.py and platform\_ info.py files under the 'python1' folder in your NetBeans installation directory to use parenthesis. For instance, in platform\_info.py the first print line says:
```
print "platform.name="+ "Jython " + version
```
Change it to:
```
print("platform.name="+ "Jython " + version)
```
And do this for all print statements. Then go into the NetBeans and import your Python30 directory into the Python Platform Manager; it will work just fine.
I haven't run into any other issues yet, but there might be some other small syntax issues in the plugin; they should be very easy to fix. | It doesn't let me comment back here so I'll answer your comment in an post.
Yes, it will let you use Python 2.x as well; the 'print' method was both a keyword and function prior to Python 3, so the parenthesis were optional. As on 3 they are required, so this change is backwards compatible. | Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development? | [
"",
"python",
"ide",
"netbeans",
""
] |
I want to make a method:
```
object Execute()
{
return type.InvokeMember(..);
}
```
to accept a generic parameter:
```
T Execute<T>()
{
return Execute() as T;
/* doesn't work:
The type parameter 'T' cannot be used with the 'as' operator because
it does not have a class type constraint nor a 'class' constraint */
// also neither typeof(T), nor T.GetType() are possible
return (T) Execute(); // ok
}
```
But I think operator `as` will be very useful: if result type isn't `T` method will return `null`, instead of an exception! Is it possible to do? | You need to add
```
where T : class
```
to your method declaration, e.g.
```
T Execute<T>() where T : class
{
```
By the way, as a suggestion, that generic wrapper doesn't really add much value. The caller can write:
```
MyClass c = whatever.Execute() as MyClass;
```
Or if they want to throw on fail:
```
MyClass c = (MyClass)whatever.Execute();
```
The generic wrapper method looks like this:
```
MyClass c = whatever.Execute<MyClass>();
```
All three versions have to specify exactly the same three entities, just in different orders, so none are any simpler or any more convenient, and yet the generic version hides what is happening, whereas the "raw" versions each make it clear whether there will be a throw or a `null`.
(This may be irrelevant to you if your example is simplified from your actual code). | You cannot use the `as` operator with a generic type with no restriction. Since the `as` operator uses null to represent that it was not of the type, you cannot use it on value types. If you want to use `obj as T`, `T` will **have** to be a reference type.
```
T Execute<T>() where T : class
{
return Execute() as T;
}
``` | Operator as and generic classes | [
"",
"c#",
".net",
"generics",
"operators",
"on-the-fly",
""
] |
I've been playing with PostSharp a bit and I ran into a nasty problem.
Following IL in Silverlight assembly:
```
.method public hidebysig specialname newslot virtual final instance void
set_AccountProfileModifiedAt(valuetype [mscorlib]System.DateTime 'value') cil managed
{
.maxstack 2
.locals (
[0] bool ~propertyHasChanged,
[1] bool CS$4$0000)
L_0000: nop
L_0001: nop
L_0002: ldarg.0
L_0003: call instance valuetype [mscorlib]System.DateTime
Accounts.AccountOwner::get_AccountProfileModifiedAt()
L_0008: ldarg.1
L_0009: call bool [mscorlib]System.DateTime::op_Inequality(valuetype
[mscorlib]System.DateTime, valuetype [mscorlib]System.DateTime)
L_000e: stloc.0
L_000f: ldarg.0
L_0010: ldarg.1
L_0011: stfld valuetype [mscorlib]System.DateTime
Accounts.AccountOwner::accountProfileModifiedAt
L_0016: br.s L_0018
L_0018: ldloc.0
L_0019: ldc.i4.0
L_001a: ceq
L_001c: stloc.1
L_001d: ldloc.1
L_001e: brtrue.s L_002b
L_0020: ldarg.0
L_0021: ldstr "AccountProfileModifiedAt"
L_0026: call instance void
Accounts.AccountOwner::NotifyPropertyChanged(string)
L_002b: nop
L_002c: leave.s L_002e
L_002e: ret
}
```
triggers System.Security.VerificationException: Operation could destabilize the runtime. exception.
Reflector parses it OK. What could be wrong with it?
**Update 1**
Code is intended to work as follows:
```
public void set_AccountProfileModifiedAt(DateTime value)
{
bool propertyHasChanged = this.AccountProfileModifiedAt != value;
this.accountProfileModifiedAt = value;
if (propertyHasChanged)
{
this.NotifyPropertyChanged("AccountProfileModifiedAt");
}
}
```
**Update 2**
I get specified exception inside the setter itself
**Update 3**
Making non-static calls as callvirt (NotifyPropertyChanged) does not help
**Update 4**
Commenting out (for test purposes) code:
```
L_0018: ldloc.0
L_0019: ldc.i4.0
L_001a: ceq
L_001c: stloc.1
L_001d: ldloc.1
```
and replacing L\_001e: brtrue.s L\_002b with L\_001e: br.s L\_002b does the trick but it's an unconditional return - not what I want.
**Update 5**
If I use C# compiler to mimic required behavior (I still need to do that with Postsharp)
I get following IL:
```
.method public hidebysig specialname newslot virtual final instance void
set_AccountProfileModifiedAt(valuetype [mscorlib]System.DateTime 'value') cil managed
{
.maxstack 2
.locals init (
[0] bool val,
[1] bool CS$4$0000)
L_0000: nop
L_0001: ldarg.0
L_0002: call instance valuetype [mscorlib]System.DateTime
Accounts.AccountOwner::get_AccountProfileModifiedAt()
L_0007: ldarg.1
L_0008: call bool [mscorlib]System.DateTime::op_Inequality(valuetype
[mscorlib]System.DateTime, valuetype [mscorlib]System.DateTime)
L_000d: stloc.0
L_000e: ldarg.0
L_000f: ldarg.1
L_0010: stfld valuetype [mscorlib]System.DateTime
Accounts.AccountOwner::accountProfileModifiedAt
L_0015: ldloc.0
L_0016: ldc.i4.0
L_0017: ceq
L_0019: stloc.1
L_001a: ldloc.1
L_001b: brtrue.s L_0029
L_001d: ldarg.0
L_001e: ldstr "AccountProfileModifiedAt"
L_0023: call instance void
Accounts.AccountOwner::NotifyPropertyChanged(string)
L_0028: nop
L_0029: ret
}
```
Note there are minor differences - extra br.s jump at L\_0016 and some strange jump L\_001e: brtrue.s L\_002b. In compiler version I get direct jump to ret. | Did you use peverify? You should always run this utility when playing directly with MSIL (you can use the msbuild flag /p:PostSharpVerify=true).
Looking at your code:
1. Your local variables are not initialized (missing "init" keyword). This is a property of MethodBodyDeclaration.
2. You are using a 'leave' instead of a 'jmp' out of a protected block; this is useless but should not matter. | It is difficult to say - do you have a stack trace? This exception is usually thrown when the CLR is unable to verify the type-safety of your code. As this could have come from this code or from any of the methods or types you are using it will be difficult to say what the issue is without a stack trace. | CIL: "Operation could destabilize the runtime" exception | [
"",
"c#",
"silverlight",
"clr",
"postsharp",
"cil",
""
] |
What's the point of JAAS if I have to write my own {whatever}LoginModule and everything else? | JAAS provides an abstraction layer between your application and the underlying authentication mechanism. Therefore, you could change the authentication mechanism used by your application without having to change any of your application code. | Well that is the beauty of it really..
We used JAAS in a big mortgage application system, and while we used a LoginModule based on properties, the big mortage bank used an own implemented LoginModule based on active directory, without we ever having to change something in code. | What's the point of JAAS | [
"",
"java",
"security",
"jakarta-ee",
"jaas",
""
] |
We can bundle all files into an Amazon Machine Instance and upload it. But I'd like to see if there is a more efficient way to regularly upload source code on to test our app and constantly have the latest version up and running. Thanks! | I am not sure I understand your question correctly, but an Amazon Machine Instance is just like any other machine running Linux (or Windows). You can use the same tools you would use if the machine was in your network. Of course you need to do this remotely. From a windows machine you can connect to an instance using tools like [Putty](http://www.chiark.greenend.org.uk/~sgtatham/putty/) or [WinScp](http://winscp.net/) - you probably know about these, if you are able to create a new image. Use these tools to configure your instance as you would have configured a machine in your local network. | A while ago I discovered an easy way to deploy PHP using Git's push. The one caveat is that the process assumes you're already using Git as your VCS, and that you've installed it on both your development machine and the server:
[Deploy a project using Git push](https://stackoverflow.com/questions/279169/deploy-php-using-git/327315#327315) | What tools can I use to deploy PHP code to an EC2 instance | [
"",
"php",
"amazon-s3",
"amazon-ec2",
"amazon-web-services",
"amazon-ami",
""
] |
A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don't, to send nice, informative error messages. This kind of code gets repeated over and over, and we often try to create helpers for it. However, in C#, it seems those helpers are forced to deal with some duplication forced upon us by the language and compiler. To show what I mean, let me present some some raw code with no helpers, followed by one possible helper. Then, I'll point out the duplication in the helper and phrase my question precisely.
**First, the code without any helpers:**
```
public void SomeMethod(string firstName, string lastName, int age)
{
if(firstName == null)
{
throw new WhateverException("The value for firstName cannot be null.");
}
if(lastName == null)
{
throw new WhateverException("The value for lastName cannot be null.");
}
// Same kind of code for age, making sure it is a reasonable range (< 150, for example).
// You get the idea
}
```
}
**Now, the code with a reasonable attempt at a helper:**
```
public void SomeMethod(string firstName, string lastName, int age)
{
Helper.Validate( x=> x !=null, "firstName", firstName);
Helper.Validate( x=> x!= null, "lastName", lastName);
}
```
**The main question is this:** Notice how the code has to pass the value of the parameter **and** the name of the parameter ("firstName" **and** firstName). This is so the error message can say, "Blah blah blah the value for the **firstName** parameter." Have you found any way to get around this using reflection or anything else? Or a way to make it less painful?
And more generally, have you found any other ways to streamline this task of validating parameters while reducing code duplication?
EDIT: I've read people talking about making use of the Parameters property, but never quite found a way around the duplication. Anyone have luck with that?
Thanks! | This may be somewhat helpful:
[Design by contract/C# 4.0/avoiding ArgumentNullException](https://stackoverflow.com/questions/434088/design-by-contract-c-4-0-avoidng-argumentnullexception) | You should check out [**Code Contracts**](http://weblogs.asp.net/podwysocki/archive/2008/11/08/code-contracts-for-net-4-0-spec-comes-alive.aspx); they do pretty much exactly what you're asking. Example:
```
[Pure]
public static double GetDistance(Point p1, Point p2)
{
CodeContract.RequiresAlways(p1 != null);
CodeContract.RequiresAlways(p2 != null);
// ...
}
``` | What is the smoothest, most appealing syntax you've found for asserting parameter correctness in c#? | [
"",
"c#",
"c#-3.0",
"lambda",
""
] |
Here is the code.
A Few notes about it. DStr is an string class that is internal to our company. It functions much like CString. I can connect to the database and run non-parameterized queries. Also this insert works fine if I do not use parameters. The cmd->Execute statment throws an exception. This is where I am getting the error msg from.
```
void CEmailArchiveDatabase::TestAddUser( DStr username, DStr displayname )
{
DStr sql = "INSERT INTO [User] (UserName, DisplayName) VALUES (@Param1, @Param2)";
_variant_t vUser;
_variant_t vDisp;
vUser.vt = VT_BSTR;
vUser.bstrVal = username.AllocSysString();
vDisp.vt = VT_BSTR;
vDisp.bstrVal = displayname.AllocSysString();
_CommandPtr cmd = NULL;
_ConnectionPtr conn = NULL;
_ParameterPtr prm = NULL;
DStr connStr = "driver={SQL Server};server=DEMETER\\SQLEXPRESS;database=ExtractoMundo";
try
{
conn.CreateInstance(__uuidof(Connection));
cmd.CreateInstance(__uuidof(Command));
if( !(conn->GetState() & adStateOpen) )
{
conn->ConnectionString = connStr.AllocSysString();
conn->Open("", "", "", NULL);
conn->CursorLocation = adUseClient;
}
cmd->ActiveConnection = conn;
cmd->CommandText = sql.AllocSysString();
cmd->CommandType = adCmdText;
prm = cmd->CreateParameter("@Param1", adLongVarChar, adParamInput, -1, vUser);
cmd->Parameters->Append(prm);
prm = cmd->CreateParameter("@Param2", adLongVarChar, adParamInput, -1, vDisp);
cmd->Parameters->Append(prm);
_variant_t recAff;
cmd->Execute(&recAff, NULL, adExecuteNoRecords);
}
catch(_com_error &ex)
{
//ClearParameters();
DStr err;
err += PrintProviderError(conn);
err += PrintComError(ex);
}
SysFreeString(vUser.bstrVal);
SysFreeString(vDisp.bstrVal);
SysFreeString(cmd->CommandText);
SysFreeString(conn->ConnectionString);
}
``` | ADO refuses to work with named parameters in dynamic queries. You have to either convert named parameters into parameter placeholders:
```
DStr sql = "INSERT INTO [User] (UserName, DisplayName) VALUES (?, ?)";
```
or use a stored procedure instead. Create the procedure:
```
CREATE PROCEDURE spUserInsert
@Param1 nvarchar(50),
@Param2 nvarchar(50)
AS
SET NOCOUNT ON;
INSERT INTO [User] (UserName, DisplayName) VALUES (@Param1, @Param2)
GO
```
and modify your code to call it:
```
DStr sql = "spUserInsert";
...
cmd->CommandType = adCmdStoredProcedure;
``` | Perhaps `cmd->CreateParameter(_bstr_t("Param1"), ...)` ?
The "@" is a SQL Server specific operator, it may be messing with you. | Why do I keep getting "Must declare the Scalar variable "@Param1"" when performing a parameterized query in C++ using ADO? | [
"",
"c++",
"com",
"ado",
""
] |
Has anyone had any success setting up Zend\_Test? What was your method/approach and how do you run your tests/test suites?
I already have PHPUnit installed and working. Now I'm trying to write some simple controller tests. The Zend Framework documentation assumes that autoloading is setup, which I haven't done. What method do **you** use to autoload the appropriate files? I do so in my normal bootstrap file, but I don't want to clutter up my Test with a bunch of includes and setting up paths. Would an abstract controller test case class be the way to go?
What about the bootstrap plugin like the documentation uses...is that how you bootstrap your tests, or do you like to do it a different way? I would like to re-use as much of the regular bootstrap file as I can. How should I DRY up my bootstrap for testing and normal use?
Here's my test so far:
```
<?php
class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
$this->frontController->registerPlugin(new Bootstrapper('testing'));
}
public function testIndexAction()
{
$this->dispatch('/index');
$this->assertController('index');
$this->assertAction('index');
}
}
//straight from the documentation
class Bootstrapper extends Zend_Controller_Plugin_Abstract
{
/**
* @var Zend_Config
*/
protected static $_config;
/**
* @var string Current environment
*/
protected $_env;
/**
* @var Zend_Controller_Front
*/
protected $_front;
/**
* @var string Path to application root
*/
protected $_root;
/**
* Constructor
*
* Initialize environment, root path, and configuration.
*
* @param string $env
* @param string|null $root
* @return void
*/
public function __construct($env, $root = null)
{
$this->_setEnv($env);
if (null === $root) {
$root = realpath(dirname(__FILE__) . '/../../../');
}
$this->_root = $root;
$this->initPhpConfig();
$this->_front = Zend_Controller_Front::getInstance();
}
/**
* Route startup
*
* @return void
*/
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$this->initDb();
$this->initHelpers();
$this->initView();
$this->initPlugins();
$this->initRoutes();
$this->initControllers();
}
// definition of methods would follow...
}
```
What should I do? | Here's what I did to get it to work:
First, we need to resolve the autoloading issue. We'll do this by creating a file that all the tests will include, and put it in the tests directory. Note: I pretty much copied all of this from my /public/index.php.
```
# /tests/loader.php
<?php
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application/'));
set_include_path( APPLICATION_PATH . '/../library' . PATH_SEPARATOR .
APPLICATION_PATH . '/models' . PATH_SEPARATOR .
APPLICATION_PATH . '/forms' . PATH_SEPARATOR .
get_include_path() );
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
```
Second, we need to include this file in our test. Our test file is in /tests/application/controllers/ . I'm not going to use my bootstrap as a plugin since my bootstrap file works the same way as the [QuickStart tutorial](http://framework.zend.com/docs/quickstart "QuickStart tutorial"). I'll just link to it by setting the location as the public $bootstrap. When `Zend_Test_PHPUnit_ControllerTestCase` constructs, it will look for the bootstrap file that we set here.
```
<?php
require_once '../../loader.php';
class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public $bootstrap = '../../../application/bootstrap.php';
public function testIndexAction()
{
$this->dispatch('/index');
$this->assertController('index');
$this->assertAction('index');
}
}
```
And that's it! If my bootstrap file was already a plugin, this might be a little more complicated, but since it's not, it's super easy. | Instead of using
```
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
```
change it into
```
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
```
registerAutoLoad() is deprecated as of 1.8.0 | Zend Framework: Getting started with Zend_Test | [
"",
"php",
"unit-testing",
"zend-framework",
"testing",
"phpunit",
""
] |
I have a div containing some text that I would like the user to be able to easily copy from the page (via the clipboard). Is there a cross browser way to select all of the text within a div on a mouseclick? | Have a look at these both:
<http://yangshuai.googlepages.com/jquerycopyplugin>
<http://plugins.jquery.com/project/clipboard> | Cross browser support for clipboard copying via Javascript requires using Flash to get around Firefox/Netscape's security, which denies access to the clipboard. If you are using [jQuery](http://jquery.com) you can easily make use of the [clipboard](http://plugins.jquery.com/project/clipboard) plugin. If you are rolling your own Javascript without using jQuery then this [blog post](http://www.jeffothy.com/weblog/clipboard-copy/) may help.
In addition, you can actually adjust Firefox's security permissions to allow scripts access to your clipboard. A good [walkthrough](http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit/advanced-editing-and-display/editor-rich-text/setup-clipboard-action) is available at dojotoolkit.org. This usually isn't the path pursued as it would require each of your users to make this adjustment. Much easier to use Flash as it works with all modern browsers (Safari, IE, Firefox, and Opera). | How can you select the text in a div (for copying into the clipboard) from javascript? | [
"",
"javascript",
"html",
""
] |
I have a wpf window that has a height of 2000 with an actual desktop height of about 1000. Obviously about half of the window is off screen. Even though the window extends below the screen, the mouse will not move down to that area. I do want this content to be off-screen, and I want the mouse to be able to move over it and click on elements if the mouse is positioned over an element at that position. I don't want to change my screen resolution as some content absolutely has to be off the screen. Not sure how to go about this. | Cursor delimiting is not done by the application, but by Windows itself. To my knowledge there is no way to have your cursor pointing off the screen.
You could simulate what you want by doing what many games do. Do not draw the Windows cursor, draw a custom one in your app window. Force the real cursor (not being drawn) to stay in the center of the monitor. Every time the user moves the real cursor, move your application's cursor accordingly and re-place the real cursor to the center of the screen.
This will give the illusion of what you'd like, but I don't think WPF can handle this. | There is not an off the screen cursor position in Windows. I think the mouse is bounded by the screen resolution, even if windows are not. | moving mouse cursor off screen in C# | [
"",
"c#",
"wpf",
"windows",
"mouse-cursor",
""
] |
Are lambda expressions multi-threaded?
Say when you write a mathematical formula as a lambda method, when you pass it to another method, would it be multi-threaded? | Not 100% clear on what you're asking.
**Are you asking if lambdas are naturally run on a different thread?**
If so no, they are just another instance of System.Delegate and run on the main thread unless specifically asked to do otherwise.
**Are you asking if they are safe to run on multiple threads?**
This is a question that can only be answered by knowing the contents of the lambda expression. They are not inherently thread safe. In my experience the are much less likely to be thread safe than you would expect. | No, they are executed on the thread they are created on unless you pass it to another thread, just like any other method. You would not want them to run on a different thread automatically, trust me. | Are lambda expressions multi-threaded? | [
"",
"c#",
".net",
"lambda",
"parallel-processing",
""
] |
I need to create a regex that can match multiple strings. For example, I want to find all the instances of "good" or "great". I found some examples, but what I came up with doesn't seem to work:
```
\b(good|great)\w*\b
```
Can anyone point me in the right direction?
**Edit:** I should note that I don't want to just match whole words. For example, I may want to match "ood" or "reat" as well (parts of the words).
**Edit 2:** Here is some sample text: *"This is a really great story."*
I might want to match "this" or "really", or I might want to match "eall" or "reat". | If you can guarantee that there are no reserved regex characters in your word list (or if you escape them), you could just use this code to make `a big word list` into `@"(a|big|word|list)"`. There's nothing wrong with the `|` operator as you're using it, as long as those `()` surround it. It sounds like the `\w*` and the `\b` patterns are what are interfering with your matches.
```
String[] pattern_list = whatever;
String regex = String.Format("({0})", String.Join("|", pattern_list));
``` | ```
(good)*(great)*
```
after your edit:
```
\b(g*o*o*d*)*(g*r*e*a*t*)*\b
``` | Regex to match multiple strings | [
"",
"c#",
"regex",
""
] |
I'm looking for a fast and easy way to plot arbitrarily colored pixels in an SWT Canvas.
So far I'm using something like that:
```
// initialization:
GC gc = new GC(canvas);
// inside the drawing loop:
Color cc = new Color(display, r, g, b);
gc.setForeground(cc);
gc.drawPoint(x, y);
cc.dispose();
```
This is horribly horribly slow. it takes about a second and a half to fill a 300x300 canvas with pixels.
I could create an image off-screen, set the pixels in it and then draw the image. This will be faster but I specifically want the gradual painting effect of plotting the image pixel by pixel on the canvas. | You could draw several offscreen images where you gradually fill the 300x300 area. This way you can control how fast the image should appear. | I bet that what is killing performance is allocating and releasing 90,000 `Color` objects. Remember, in SWT, each `Color` object allocates native resources, which is why you have to `dispose()` it. This means each time you allocate and dispose a `Color` object, you have to transition from the JVM to native code and back.
Can you cache your `Color` instances while in the 300x300 pixel loop and then dispose of the objects after your loop? You'd need a somewhat intelligent cache that only holds a maximum of so many objects, and after that will dispose of some of its entries, but this should speed things up **greatly**. | Fast pixel plotting using SWT? | [
"",
"java",
"canvas",
"swt",
"plot",
"pixel",
""
] |
In my master page, I have a language dropdown menu. When the user selects a language from the dropdown, a submit sends the currently selected language to the "Translate" method in my controller. After which it should redirect to the url it was before the translation submit so it can show the exact same page, but now in the newly selected language.
How would I best go about this? Should I send the current url somehow in a hidden field? Or can I maybe send the current routevaluedictionary, so my translate method can redirectToRoute directly?
Or maybe there is an entirely better way?
**--EDIT--**
Because I want my bookmarks to include the site language too, all my exposed actions have a siteLanguage parameter too. If I could somehow efficiently show the user a bunch of regular (GET) links where the siteLanguage parameter is filled in with the relevant value, that would be even better. But as far as I know, there is no way to put links in a dropdown except with java maybe. | I have a similar situation, and I solved it slightly differently.
Because my master page had *functionality* in it, I created a new base controller class (that inherits from Controller) and all my real controllers inherit from my custom class.
Then, I implement OnActionExecuting in the base class to do some common work.
Then, in your masterpage, if you have a form like this, it will submit to the current URL with a GET request and add the language as a querystring parameter:
```
<form id="language" method="get" >
<select name="language">
<option value="en">English</option>
<option value="es">Spanish</option>
...
</select>
</form>
```
Use jQuery to wire it up to autosubmit, etc.
You could look for a language parameter in the querystring in your base controller class and set the flag that tells the real controller method which language to use. In the model, you directly go to the real controller to regenerate the page and avoid a redirect.
Note, this only works universally, if you are not already using querystring parameters.
If this doesn't work for you, you could also use your current method, but include the URL to be redirected to in a hidden field like this:
```
<%= Html.Hidden("redirect", Request.Url %>
``` | ```
public ActionResult Translate(string _lang){
switch(_lang){
case "English":
return View("English");
case: "French":
return View("French");
default:
return View("English");
}
```
I would personally do it like this | Put current route values/url in form post | [
"",
"c#",
".net",
"asp.net-mvc",
""
] |
In C#, the Changed event for a control (say, a numericupdown) gets fired whether the value was change directly by the user or if it was changed programatically as the result of some other event.
Is there a way to determine whether the event occurred as a result of user input? For example, both manually changing the value of numericUpDown1 and clicking on button1 will display "value changed". What if I only wanted to display "value changed" if it was changed through the user clicking on the up/down arrows in the control and not as a result of clicking on button1?
```
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
MessageBox.Show("value changed");
}
private void button1_Click_1(object sender, EventArgs e)
{
numericUpDown1.Value = 3;
}
``` | There is no nice way to do it. You can find workarounds for specific cases, e.g.
* listen to MouseDown or something instead of valueChanged on the numeric drop down.
* Set a flag in button click event handler that will prohibit the message box from showing.
In general you should try to organize your form in a way that it doesn't matter where the value got changed. | You could check to see if the numericUpDown is the ActiveControl. When you set the value of the numericUpDown during the button click, button1 should be the ActiveControl. When the user changes the value via the numericUpDown, then the numericUpDown should be the ActiveControl.
```
if(numericUpDown1 == this.ActiveControl)
{
MessageBox.Show("value changed");
}
``` | Determine If Changed Event Occurred from User Input Or Not | [
"",
"c#",
".net",
""
] |
I am looking for free/open or closed forum software for asp.net. Most of the ones I have found require PHP and MySql. | <http://www.yetanotherforum.net/> - Yet Another Forum is a pretty popular ASP.NET based forum package. | You might wanna try "Jitbit AspNetForum" <http://www.jitbit.com/asp-net-forum/> We used it for years and they have a free evaluation version (fully functional). It also received a good review from Scott Hanselman here <http://www.hanselman.com/blog/HanselmanForumsAspNetForumFromJitBit.aspx> | Forum software for asp.net c# that I can integrate into my asp.net project? | [
"",
"c#",
"asp.net",
""
] |
I have an app that was compiled with the built-in Eclipse "Compile" task. Then I decided to move the build procedure into Ant's `javac`, and the result ended being smaller files.
Later I discovered that adjusting the debuglevel to `"vars,lines,source"` I could embed the same debug information that Eclipse did, and in a lot of cases files stayed exactly the same size but the internal layout was different. And as a consequence, I couldn't use md5sum signatures to determine if they were exactly the same version.
Besides debug information, what can be the reason that 2 supposedly equal files get a different internal layout or size?
And how can you compare compiled .class files? | THere is no required order for things such as the order of the constant pool entries (essentially all of the symbol info) as well as the attributes for each field/method/class. Different compilers are free to write out in whatever order they want.
You can compared compiled classes, but you would need to dig into the class file structure and parse it. There are libraries out there for doing that, like [BCEL](http://jakarta.apache.org/bcel/) or [ASM](http://asm.objectweb.org/), but I am not 100% sure they will help you with what you want to do. | The ASM Eclipse [plugin](http://andrei.gmxhome.de/bytecode/index.html) has a bytecode comparer in it. You select two classes, right click, and do Compare With / Each Other Bytecode. | What settings affect the layout of compiled java .class files? How can you tell if two compiled classes are equal? | [
"",
"java",
"compiler-construction",
"comparison",
"bytecode",
"javac",
""
] |
As per 'unobtrusive JavaScript' recommendations I want to separate my JavaScript logic into
separate files. However I don't know how to organize them.
Should I:
1. Just throw all application javascript into Application.js file and load it with layout page? This is simple approach but I will end up with a bloated Application.js. Some users might want to visit only a couple of pages, but this entire file would preloaded which is not good.
2. Or should I create a separate javaScript file for each view and load them independently? This creates a set of questions. How to link each js file to corresponding view?
Thanks. | Load the main JavaScript in application.js every time. Now create files for different needs. Create a form.js file, a myfancypart.js file etc. Don't load them in the application.html.erb layout. Load them dynamically when you need them:
application.html.erb:
```
<%= javascript_include_tag "application" %>
<%= yield :javascript_includes %>
```
top of your view.html.erb:
```
<% content_for :javascript_includes do %>
<%= javascript_include_tag "forms.js" %>
<% end %>
```
Everything in the content\_for block will be loaded at yield :javascript\_includes. | I suggest putting it all into one file, which you can then minify and gzip. The client will only have to download it once, as it'll be cached on all subsequent requests.
Another thing that might interest you is sprockets, a javascript dependency manager, which you can install using gem. You can get more information on sprockets from the website (<http://getsprockets.org/>) or from the github page (<https://github.com/rails/sprockets>). It makes writing big javascript applications much more manageable. | JavaScript file per view in Rails | [
"",
"javascript",
"ruby-on-rails",
"ruby",
""
] |
For a videogame I'm implementing in my spare time, I've tried implementing my own versions of sinf(), cosf(), and atan2f(), using lookup tables. The intent is to have implementations that are faster, although with less accuracy.
My initial implementation is below. The functions work, and return good approximate values. The only problem is that they are *slower* than calling the standard sinf(), cosf(), and atan2f() functions.
So, what am I doing wrong?
```
// Geometry.h includes definitions of PI, TWO_PI, etc., as
// well as the prototypes for the public functions
#include "Geometry.h"
namespace {
// Number of entries in the sin/cos lookup table
const int SinTableCount = 512;
// Angle covered by each table entry
const float SinTableDelta = TWO_PI / (float)SinTableCount;
// Lookup table for Sin() results
float SinTable[SinTableCount];
// This object initializes the contents of the SinTable array exactly once
class SinTableInitializer {
public:
SinTableInitializer() {
for (int i = 0; i < SinTableCount; ++i) {
SinTable[i] = sinf((float)i * SinTableDelta);
}
}
};
static SinTableInitializer sinTableInitializer;
// Number of entries in the atan lookup table
const int AtanTableCount = 512;
// Interval covered by each Atan table entry
const float AtanTableDelta = 1.0f / (float)AtanTableCount;
// Lookup table for Atan() results
float AtanTable[AtanTableCount];
// This object initializes the contents of the AtanTable array exactly once
class AtanTableInitializer {
public:
AtanTableInitializer() {
for (int i = 0; i < AtanTableCount; ++i) {
AtanTable[i] = atanf((float)i * AtanTableDelta);
}
}
};
static AtanTableInitializer atanTableInitializer;
// Lookup result in table.
// Preconditions: y > 0, x > 0, y < x
static float AtanLookup2(float y, float x) {
assert(y > 0.0f);
assert(x > 0.0f);
assert(y < x);
const float ratio = y / x;
const int index = (int)(ratio / AtanTableDelta);
return AtanTable[index];
}
}
float Sin(float angle) {
// If angle is negative, reflect around X-axis and negate result
bool mustNegateResult = false;
if (angle < 0.0f) {
mustNegateResult = true;
angle = -angle;
}
// Normalize angle so that it is in the interval (0.0, PI)
while (angle >= TWO_PI) {
angle -= TWO_PI;
}
const int index = (int)(angle / SinTableDelta);
const float result = SinTable[index];
return mustNegateResult? (-result) : result;
}
float Cos(float angle) {
return Sin(angle + PI_2);
}
float Atan2(float y, float x) {
// Handle x == 0 or x == -0
// (See atan2(3) for specification of sign-bit handling.)
if (x == 0.0f) {
if (y > 0.0f) {
return PI_2;
}
else if (y < 0.0f) {
return -PI_2;
}
else if (signbit(x)) {
return signbit(y)? -PI : PI;
}
else {
return signbit(y)? -0.0f : 0.0f;
}
}
// Handle y == 0, x != 0
if (y == 0.0f) {
return (x > 0.0f)? 0.0f : PI;
}
// Handle y == x
if (y == x) {
return (x > 0.0f)? PI_4 : -(3.0f * PI_4);
}
// Handle y == -x
if (y == -x) {
return (x > 0.0f)? -PI_4 : (3.0f * PI_4);
}
// For other cases, determine quadrant and do appropriate lookup and calculation
bool right = (x > 0.0f);
bool top = (y > 0.0f);
if (right && top) {
// First quadrant
if (y < x) {
return AtanLookup2(y, x);
}
else {
return PI_2 - AtanLookup2(x, y);
}
}
else if (!right && top) {
// Second quadrant
const float posx = fabsf(x);
if (y < posx) {
return PI - AtanLookup2(y, posx);
}
else {
return PI_2 + AtanLookup2(posx, y);
}
}
else if (!right && !top) {
// Third quadrant
const float posx = fabsf(x);
const float posy = fabsf(y);
if (posy < posx) {
return -PI + AtanLookup2(posy, posx);
}
else {
return -PI_2 - AtanLookup2(posx, posy);
}
}
else { // right && !top
// Fourth quadrant
const float posy = fabsf(y);
if (posy < x) {
return -AtanLookup2(posy, x);
}
else {
return -PI_2 + AtanLookup2(x, posy);
}
}
return 0.0f;
}
``` | "Premature optimization is the root of all evil" - Donald Knuth
Nowadays compilers provide very efficient intrinsics for trigonometric functions that get the best from modern processors (SSE etc.), which explains why you can hardly beat the built-in functions. Don't lose too much time on these parts and instead concentrate on the real bottlenecks that you can spot with a profiler. | Remember you have a co-processor ... you would have seen an increase in speed if it were 1993 ... however today you will struggle to beat native intrinsics.
Try viewing the disassebly to sinf. | Implementing Table-Lookup-Based Trig Functions | [
"",
"c++",
"optimization",
"trigonometry",
""
] |
The JavaDoc of [`ConcurrentHashMap`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) says this:
> Like `Hashtable` but unlike `HashMap`, this class does *not* allow `null` to be used as a key or value.
My question: Why?
2nd question: Why doesn't `Hashtable` allow null?
I've used a lot of HashMaps for storing data. But when changing to `ConcurrentHashMap` I got several times into trouble because of NullPointerExceptions. | [From the author of `ConcurrentHashMap` himself (Doug Lea)](http://cs.oswego.edu/pipermail/concurrency-interest/2006-May/002485.html):
> The main reason that nulls aren't allowed in ConcurrentMaps
> (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that
> may be just barely tolerable in non-concurrent maps can't be
> accommodated. The main one is that if `map.get(key)` returns `null`, you
> can't detect whether the key explicitly maps to `null` vs the key isn't
> mapped. In a non-concurrent map, you can check this via
> `map.contains(key)`, but in a concurrent one, the map might have changed
> between calls. | I believe it is, at least in part, to allow you to combine `containsKey` and `get` into a single call. If the map can hold nulls, there is no way to tell if `get` is returning a null because there was no key for that value, or just because the value was null.
Why is that a problem? Because there is no safe way to do that yourself. Take the following code:
```
if (m.containsKey(k)) {
return m.get(k);
} else {
throw new KeyNotPresentException();
}
```
Since `m` is a concurrent map, key k may be deleted between the `containsKey` and `get` calls, causing this snippet to return a null that was never in the table, rather than the desired `KeyNotPresentException`.
Normally you would solve that by synchronizing, but with a concurrent map that of course won't work. Hence the signature for `get` had to change, and the only way to do that in a backwards-compatible way was to prevent the user inserting null values in the first place, and continue using that as a placeholder for "key not found". | Why does ConcurrentHashMap prevent null keys and values? | [
"",
"java",
"concurrenthashmap",
""
] |
I am creating this JS function that creates an element
The function takes two parameters strName and objAttributes
```
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem.setAttribute(i, objAttributes[i]);
return elem;
}
```
This works fine in Fx, but not in MSIE
I know that the setAttibute method is buggy and the proposed workaround is
```
elem.attr = 'val';
```
But right now I have no idea how to write this inside my loop.
I have tried both elem.style and elem['style'] but none of them works.
Can anyone give me some advice,
thanks in advance
t | Use `elem[i]`.
```
function createElement( strName, objAttributes )
{
var elem = document.createElement(strName);
for ( var i in objAttributes )
elem[i] = objAttributes[i];
return elem;
}
``` | You can't just swap setting properties and setAttribute.
You have to be careful with setting properties on an element in place of using setAttribute.
Style properties and event handlers need to be carefully written, and those attributes that used to be minimized in html (disabled, multiple, readonly) have browser specific valid values.
Also, if you set element.class="mynewclass", you'll get an error, because class is a reserved javascript word, though it is perfectly safe to use it as a string in a setAttribute assignment. THe property name is '.className', and the proper name for a label's 'for' attribute is 'htmlFor'. | JavaScript setAttribute alternative | [
"",
"javascript",
"dom",
""
] |
I suspect this is a very dumb question: what is the correct syntax for an interruptible lock statement in C#? E.g. get lock; if lock is interrupted before locked code finishes, return false out of the enclosing method. Probably totally the wrong terminology... Thanks. | You can have a timeout while *aquiring* a lock using `Monitor.TryEnter`; and likewise, within a lock you can do things like `Monitor.Wait`/`Monitor.Pulse` to temporarily yield the lock, but you can't be interrupted as such.
The main time interrupt applies might be in Thread.Sleep, which can be interrupted with Thread.Interrupt - but again, this won't yank control out of an executing method block.
What exactly is it that you are trying to achieve? With more context we can probably help more... | What you mean by "interrupted" is unclear.
**Interruption by Exception**
```
private bool SomeLockingMethod(object foo)
{
// Verify foo is valid
try
{
lock(foo)
{
while(something)
{
// Do stuff
Thread.Sleep(1); // Possibly yield to another
// thread calling Thread.Interrupt
}
}
return true;
}
catch(ThreadInterruptedException ex)
{
// Handle exception
}
return false;
}
```
If the `return true` isn't reached, then something happened while the lock on `foo` was held, and the code returns `false`. The lock is automatically released, either way.
Another thread can interrupt this one by calling [`Thread.Interrupt`](http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx).
**"Interruption" from code**
If you're the one "interrupting" the code, it could be as simple as
```
private bool SomeLockingMethod(object foo)
{
// Verify foo is valid
lock(foo)
{
// Do stuff
if(shouldInterrupt)
{
return false;
}
// Do more stuff
}
return true;
}
```
Again, the lock is automatically released, whether or not there is an "interruption".
**Interruption because someone else is trying to acquire the lock**
Possibly this is what you're looking for; in this case you may want to use something else, like a [`Semaphore`](http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx) or [`ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx). | Syntax for interruptible lock in C# | [
"",
"c#",
"locking",
"interrupt",
""
] |
I am using `DATETIME` as a column type and using `NOW()` to insert. When it prints out, it is three hours behind. What can I do so it works three hours ahead to EST time?
I am using php date to format the `DATETIME` on my page. | If the date stored in your database by using NOW() is incorrect, then you need to [change your MySQL server settings to the correct timezone](http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html). If it's only incorrect once you print it, you need to [modify your php script to use the correct timezone](https://www.php.net/manual/en/function.date-default-timezone-set.php).
Edit:
Refer to [W3schools' convenient php date overview](http://www.w3schools.com/php/func_date_date.asp) for information on how to format the date using date().
Edit 2:
Either you get GoDaddy to change the setting (doubtful), or you add 3 hours when you insert into the table. Refer to the [MySQL date add function](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add) to modify your date when you set it in the table. Something like date\_add(now(), interval 3 hour) should work.
Your exact problem is described [here](http://www.webmasterworld.com/forum88/3069.htm). | Give [gmdate()](http://us.php.net/gmdate) and [gmmktime()](http://us.php.net/gmmktime) a look. I find timestamp arithmetic much easier if you use GMT, especially if your code runs on multiple machines, or modifying MySQL server settings isn't an option, or you end up dealing with different timezones, day light savings, etc. | Datetime value from database is three hours behind | [
"",
"php",
"mysql",
"datetime",
"timezone",
""
] |
I have a producer app that generates an index (stores it in some in-memory tree data structure). And a consumer app will use the index to search for partial matches.
I don't want the consumer UI to have to block (e.g. via some progress bar) while the producer is indexing the data. Basically if the user wishes to use the partial index, it will just do so. In this case, the producer will potentially have to stop indexing for a while until the user goes away to another screen.
Roughly, I know I will need the wait/notify protocol to achieve this. My question: is it possible to interrupt the producer thread using wait/notify while it is doing its business ? What java.util.concurrent primitives do I need to achieve this ? | In your producer thread, you are likely to have some kind of main loop. This is probably the best place to interrupt your producer. Instead of using wait() and notify() I suggest you use the java synchronization objects introduced in java 5.
You could potentially do something like that
```
class Indexer {
Lock lock = new ReentrantLock();
public void index(){
while(somecondition){
this.lock.lock();
try{
// perform one indexing step
}finally{
lock.unlock();
}
}
}
public Item lookup(){
this.lock.lock();
try{
// perform your lookup
}finally{
lock.unlock();
}
}
}
```
You need to make sure that each time the indexer releases the lock, your index is in a consistent, legal state. In this scenario, when the indexer releases the lock, it leaves a chance for a new or waiting lookup() operation to take the lock, complete and release the lock, at which point your indexer can proceed to its next step. If no lookup() is currently waiting, then your indexer just reaquires the lock itself and goes on with its next operation.
If you think you might have more that one thread trying to do the lookup at the same time, you might want to have a look at the ReadWriteLock interface and ReentrantReadWriteLock implementation.
Of course this solution is the simple way to do it. It will block either one of the threads that doesn't have the lock. You may want to check if you can just synchronize on your data structure directly, but that might prove tricky since building indexes tends to use some sort of balanced tree or B-Tree or whatnot where node insertion is far from being trivial.
I suggest you first try that simple approach, then see if the way it behaves suits you. If it doesn't, you may either try breaking up the the indexing steps into smaller steps, or try synchronizing on only parts of your data structure.
Don't worry too much about the performance of locking, in java uncontended locking (when only one thread is trying to take the lock) is cheap. As long as most of your locking is uncontented, locking performance is nothing to be concerned about. | The way you've described this, there's no reason that you need wait/notify. Simply synchronize access to your data structure, to ensure that it is in a consistent state when accessed.
Edit: by "synchronize access", I do not mean synchronize the entire data structure (which would end up blocking either producer or consumer). Instead, synchronize only those bits that are being updated, and only at the time that you update them. You'll find that most of the producer's work can take place in an unsynchronized manner: for example, if you're building a tree, you can identify the node where the insert needs to happen, synchronize on that node, do the insert, then continue on. | design of a Producer/Consumer app | [
"",
"java",
"multithreading",
"concurrency",
""
] |
I have been scouring the Internet looking for a Java package/class that will allow me to parse the UNIX /etc/group file. While it really wouldn't be so hard to write this from scratch, I'm quite surprised not to find something already out there. There is a POSIX passwd class (see <http://www.bmsi.com/java/posix/docs/posix.Passwd.html>), but I'm not finding a similar class for /etc/group. Does such a thing exist? | Heres my code that tofubeer updated that I updated again. His didn't compile. missing InvalidGroupException class. Also, no package was specified. Switched EMPTY\_LIST to emptyList() to avoid lack of parameterization.
```
package fileutils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GroupReader2 {
public static class InvalidGroupException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidGroupException(String string) {
super(string);
}
}
public static GroupReader2 parseGroup(final String groupLine)
throws InvalidGroupException {
final String line;
final String[] parts;
if (groupLine == null) {
throw new IllegalArgumentException("groupLine cannot be null");
}
line = groupLine.trim();
if (line.startsWith("#") || line.isEmpty()) {
return null;
}
parts = line.split(":");
if (parts.length < 3) {
throw new InvalidGroupException(groupLine
+ "must be in the format of name:passwd:gid[:userlist]");
}
try {
final GroupReader2 group;
final String name;
final String passwd;
final int gid;
final List<String> userList;
name = parts[0];
passwd = parts[1];
gid = Integer.parseInt(parts[2]);
if (parts.length == 4) {
userList = Arrays.asList(parts[3].split(","));
} else {
userList = Collections.emptyList();
}
group = new GroupReader2(name, passwd, gid, userList);
return group;
} catch (final NumberFormatException ex) {
throw new InvalidGroupException(groupLine + " gid must be a number");
}
}
private final int gid;
private final String name;
private final String passwd;
private final List<String> userList;
public GroupReader2(final String nm, final String pw, final int id,
final List<String> users) {
name = nm;
passwd = pw;
gid = id;
userList = Collections.unmodifiableList(new ArrayList<String>(users));
}
public int getGid() {
return (gid);
}
public String getName() {
return (name);
}
public String getPasswd() {
return (passwd);
}
public List<String> getUserList() {
return (userList);
}
@Override
public String toString() {
final StringBuilder sb;
sb = new StringBuilder();
sb.append(name);
sb.append(":");
sb.append(passwd);
sb.append(":");
sb.append(gid);
sb.append(":");
for (final String user : userList) {
sb.append(user);
sb.append(",");
}
sb.setLength(sb.length() - 1);
return (sb.toString());
}
}
``` | Here is the code John Ellinwood provided, but made safer (edit: added Johns changes, slightly differently, to keep then in sync with the comments. Good to see how two people implement the same sort of code).
I chose to throws exceptions in the case of an invalid line, you could simply return null as he originally did (I don't see the point in using a file that has wrong data...).
The only "must do" change it wrapping the userList as an UnmodifableList (or returning a new copy of the list) otherwise a malicious user of this method could add things to the userList (call getUserList and then proceed to add items to it or remove items from it).
Since the Group class is immutable (all instance variables are final) there is no fear of them being changed by a caller.
```
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Group
{
private final int gid;
private final String name;
private final String passwd;
private final List<String> userList;
public static Group parseGroup(final String groupLine)
throws InvalidGroupException
{
final String line;
final String[] parts;
if(groupLine == null)
{
throw new IllegalArgumentException("groupLine cannot be null");
}
line = groupLine.trim();
if(line.startsWith("#") || line.isEmpty())
{
return null;
}
parts = line.split(":");
if(parts.length < 3)
{
throw new InvalidGroupException(groupLine + "must be in the format of name:passwd:gid[:userlist]", line);
}
try
{
final Group group;
final String name;
final String passwd;
final int gid;
final List<String> userList;
name = parts[0];
passwd = parts[1];
gid = Integer.parseInt(parts[2]);
if(parts.length == 4)
{
userList = Arrays.asList(parts[3].split(","));
}
else
{
userList = Collections.emptyList();
}
group = new Group(name, passwd, gid, userList);
return group;
}
catch(final NumberFormatException ex)
{
throw new InvalidGroupException(groupLine + " gid must be a number", line);
}
}
public Group(final String nm, final String pw, final int id, final List<String> users)
{
name = nm;
passwd = pw;
gid = id;
userList = Collections.unmodifiableList(new ArrayList<String>(users));
}
public int getGid()
{
return (gid);
}
public String getName()
{
return (name);
}
public String getPasswd()
{
return (passwd);
}
public List<String> getUserList()
{
return (userList);
}
@Override
public String toString()
{
final StringBuilder sb;
sb = new StringBuilder();
sb.append(name);
sb.append(":");
sb.append(passwd);
sb.append(":");
sb.append(gid);
sb.append(":");
for(final String user : userList)
{
sb.append(user);
sb.append(",");
}
sb.setLength(sb.length() - 1);
return (sb.toString());
}
}
public class InvalidGroupException
extends Exception
{
private static final long serialVersionUID = 1L;
private final String line;
public InvalidGroupException(final String msg, final String ln)
{
super(msg);
line = ln;
}
public String getLine()
{
return (line);
}
}
``` | Is there a Java package to read the UNIX /etc/group file? | [
"",
"java",
"class",
"posix",
""
] |
I have a friendly argument going on with a co-worker about this, and my personal opinion is that a ASP.NET-MVC compiled web application would run more efficiently/faster than the same project that would be written in PHP. My friend disagrees.
Unfortunately I do not have any solid data that I can use to back up my argument. (neither does he)
To this, I tried to Google for answers to try and find evidence to prove him wrong but most of the time the debate turned into which platform it is better to develop on, cost, security features, etc... For the sake of this argument I really don't care about any of that.
I would like to know what stack overflow community thinks about the raw speed/efficency of websites in general that are developed in ASP.NET with MVC versus exactly the same website developed with PHP?
Does anyone have any practical examples in real-world scenarios comparing the performance of the two technologies?
*(I realize for some of you this may very well be an irrelevant and maybe stupid argument, but it is an argument, and I would still like to hear the answers of the fine people here at S.O.)* | It's a hard comparison to make because differences in the respective stacks mean you end up doing the same thing differently and if you do them the same for the purpose of comparison it's not a very realistic test.
PHP, which I like, is in its most basic form loaded with every request, interpreted and then discarded. It is very much like CGI in this respect (which is no surprise considering it is roughly 15 years old).
Now over the years various optimisations have been made to improve the performance, most notably opcode caching with APC, for example (so much so that APC will be a standard part of PHP 6 and not an optional module like it is now).
But still PHP scripts are basically transient. Session information is (normally) file based and mutually exclusive (session\_start() blocks other scripts accessing the same user session until session\_commit() or the script finishes) whereas that's not the case in ASP.NET. Aside from session data, it's fairly easy (and normal) to have objects that live within the application context in ASP.NET (or Java for that matter, which ASP.NET is much more similar to).
This is a key difference. For example, database access in PHP (using mysql, mysqli, PDO, etc) is transient (persistent connections notwithstanding) whereas .Net/Java will nearly always use persistent connection pools and build on top of this to create ORM frameworks and the like, the caches for which are beyond any particular request.
As a bytecode interpreted platform, ASP.NET is theoretically faster but the limits to what PHP can do are so high as to be irrelevant for most people. 4 of the top 20 visited sites on the internet are PHP for example. Speed of development, robustness, cost of running the environment, etc... tend to be far more important when you start to scale than any theoretical speed difference.
Bear in mind that .Net has primitive types, type safety and these sorts of things that will make code faster than PHP can run it. If you want to do a somewhat unfair test, sort an array of one million random 64 bit integers in both platforms. ASP.NET will kill it because they are primitive types and simple arrays will be more efficient than PHP's associative arrays (and all arrays in PHP are associative ultimately). Plus PHP on a 32 bit OS won't have a native 64 bit integer so will suffer hugely for that.
It should also be pointed out that ASP.NET is pre-compiled whereas PHP is interpreted on-the-fly (excluding opcode caching), which can make a difference but the flexibility of PHP in this regard is a good thing. Being able to deploy a script without bouncing your server is great. Just drop it in and it works. Brilliant. But it is less performant ultimately.
Ultimately though I think you're arguing what's really an irrelevant detail. | **ASP.NET runs faster. ASP.NET Development is faster.
Buy fast computer, and enjoy it if you do serious business web applications**
ASP.NET code executes a lot faster compared to PHP, when it's builded in Release mode, optimized, cached etc etc. But, for websites (except big players, like Facebook), it's less important - the most time of page rendering time is accessing and querying database.
In connecting database ASP.NET is a lot better - in asp.net we typically use LINQ which translates our object queries into stored procedures in SQL server database. Also connection to database is persistent, one for one website, there is no need for reconnecting.
PHP, in comparison, can't hold sql server connection between request, it connect, grab data from db and destroys, when reconnecting the database is often 20-30% of page rendering time.
Also whole web application config is reloaded in php on each request, where in asp.net it persist in memory. It can be easily seen in big, enterprise frameworks like symfony/symfony2, a lot of rendering time is symfony internal processess, where asp.net loads it's once and don't waste your server for useless work.
ASP.NET can holds object in cache in application memory - in php you have to write it to files, or use hack like memcache. using memcache is a lot of working with concurrency and hazard problems (storing cache in files also have it's own problems with concurrency - every request start new thread of apache server and many request can work on one time - you have to think about concurrency between those threads, it take a lot of development time and not always work because php don't have any mutex mechanisms in language, so you can't make critical section by any way).
now something about development speed:
ASP.NET have two main frameworks designed for it (Webforms and MVC), installed with environment, where in PHP you must get a open-source framework. There is no standard framework in php like in asp.NET.
ASP.NET language is so rich, standard library has solutions for very much common problems, where PHP standard library is ... naked... they can't keep one naming convention.
.NET has types, where PHP is dynamic, so it means no control about source code until you run it or write unit tests.
.NET has great IDE where PHP IDE's are average or average-good (PHPStorm is still a lot worse than VS+resharper or even without it)
PHP scaffolding in symfony is fired from command line when ASP.NET scaffolding is integrated into environment.
If you have slow computer like my (one core 2,2ghz), developing asp.net pages can be painfull because you have to recompile your project on any change of source code, where PHP code refresh immediately.
PHP language syntax is so unfinished, unsolid and naked compared to C# syntax.
Strong types in C# and many flexible language features can speed up your development and make your code less buggy. | Speed of code execution: ASP.NET-MVC versus PHP | [
"",
"php",
"asp.net-mvc",
"arguments",
""
] |
In spirit of the existing ["what's your most useful C/C++ snippet"](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) - thread:
Do you guys have short, monofunctional Python snippets that you use (often) and would like to share with the StackOverlow Community? Please keep the entries small (under 25
lines maybe?) and give only one example per post.
I'll start of with a short snippet i use from time to time to count sloc (source lines of code) in python projects:
```
# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc
import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])
loclist = []
for pydir, _, pyfiles in os.walk(cur_path):
for pyfile in pyfiles:
if pyfile.endswith(".py") and pyfile not in ignore_set:
totalpath = os.path.join(pydir, pyfile)
loclist.append( ( len(open(totalpath, "r").read().splitlines()),
totalpath.split(cur_path)[1]) )
for linenumbercount, filename in loclist:
print "%05d lines in %s" % (linenumbercount, filename)
print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)
``` | Initializing a 2D list
While this can be done safely to initialize a list:
```
lst = [0] * 3
```
The same trick won’t work for a 2D list (list of lists):
```
>>> lst_2d = [[0] * 3] * 3
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [5, 0, 0], [5, 0, 0]]
```
The operator \* duplicates its operands, and duplicated lists constructed with [] point to the same list. The correct way to do this is:
```
>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]
``` | I like using `any` and a generator:
```
if any(pred(x.item) for x in sequence):
...
```
instead of code written like this:
```
found = False
for x in sequence:
if pred(x.n):
found = True
if found:
...
```
I first learned of this technique from a Peter Norvig [article](http://norvig.com/sudoku.html). | Short (and useful) python snippets | [
"",
"python",
"code-snippets",
""
] |
Which is more practical to comment, the declaration (in the header file) or the definition (in the source file)? Maybe I should comment both, or comment neither and put it all in a separate file... | You should completely document the header file with highest priority.
Comments in the definition should be concentrated on implementation details, while header comments should be concentrated on the interface.
A third source of documentation, as you suggested, is useful as well. It should describe the overall concept.
A big plus of commenting header files is that you can create documentation automatically from them if you adhere to some simple syntax. Say hello to [doxygen](http://www.doxygen.nl)! | I want to add to ypnos's answer:
Where your comments go depends upon who your audience is. Thinking about your code as being closed-source helps in this regard: maintainers get to see the implementation, customers/users only get to see the interface. If the comment is necessary for users, it must go in the interface. If the comment is only relevant to the given implementation, it probably only needs to go into the implementation (but not necessarily, depending on your audience). | Should I comment the declaration or the definition in C++? | [
"",
"c++",
"comments",
""
] |
I need to pull data from an xls, I also need have the user be able to change the location of the file it will. So an OleDbConnection seemed like a good start, and it was until the first merged cell.
This works for all but the merged cells:
```
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=F:\test.xls;Extended Properties=Excel 8.0;");
cmd.CommandText = "SELECT * FROM [Sheet$]";
cmd.Connection.Open();
```
I found that this should allow access to the merged cells:
```
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\test.xls;Extended Properties=Excel 8.0;HDR=Yes;IMEX=1;");
```
But then I get a Could not find installable ISAM exception on cmd.conn.open();
I followed the advice here:
<http://support.microsoft.com/kb/209805>
And here:
[Error: "Could Not Find Installable ISAM"](https://stackoverflow.com/questions/512143/error-could-not-find-installable-isam)
No luck.
I’m open to other ways of pulling data from the xls. Or even if there was a command I could run on the xls to remove the mirged cells that might work. | I think it's just because you have to enclose the Extended Properties in quotes if you have more than one
```
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\test.xls;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';");
```
Or if single quotes don't work (you get the idea)
```
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\test.xls;
Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1;"";");
```
While your example doesn't show it, this error can also be caused by spaces in the file path. In which case you would need to wrap the file path in quotes as well.
```
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""F:\test.xls"";...
``` | Assuming your system requirements include an installation of Excel, you can use the Excel Object Library
```
Excel.Sheets sheets = m_Excel.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range range = worksheet.get_Range("A1", "E1".ToString());
```
etc.
See also [VSTO](http://msdn.microsoft.com/en-us/library/d2tx7z6d.aspx) | Open an Excel 2003 spreadsheet with C#. Could not find installable ISAM. Exception | [
"",
"c#",
"excel",
"xls",
"isam",
""
] |
I have the following structure in an aspx page:
```
<asp:Panel ID="pnlCust" runat="server">
<asp:GridView ID="gvMaster" runat="server"
OnRowCreated="gvMaster_RowCreated">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="pnlMaster" runat="server">
//...
</asp:Panel>
<asp:Panel ID="pnlDetails" runat="server">
<asp:GridView ID="gvDetails" runat="server">
<Columns>
//...
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
```
The panels are used for the CollapsiblePanelExtender from the Ajax Control Toolkit.
I am trying to use FindControl to find the gvDetails control in code-behind, but my latest attempt has not worked, which is in the gvMaster\_RowCreated event:
```
GridView gv =
e.Row.FindControl("pnlDetails").FindControl("gvDetails") as GridView;
```
where e is GridViewRowEventArgs
I am basically doing what was on this page, but I am not using a SqlDataSource, however, the person is basically finding the SqlDataSource via the FindControl from the e argument passed in from the RowCreated event. Here is the link:
<http://mosesofegypt.net/post/2008/02/Building-a-grouping-Grid-with-GridView-and-ASPNET-AJAX-toolkit-CollapsiblePanel.aspx> | Here is a code behind method which worked for me:
```
protected void gvMaster_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
GridView gv = (GridView)e.Row.FindControl("gvDetails");
}
}
```
Is your app throwing an exception? What is not working properly? | I don't believe that a GridView can have child controls like that. | How to find the nested Asp:GridView within the following code? | [
"",
"c#",
"asp.net",
"gridview",
""
] |
I know the following is not possible because the Enumeration's type has to be an int
```
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
```
From my database I get a field with incomprehensive codes (the `OEM` and `CMB`s). I would want to make this field into an `enum` or something else understandable. Because if the target is readability, the solution should be terse.
What other options do I have? | I like to use **properties in a class** instead of methods, since they look more enum-like.
Here's an example for a Logger:
```
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; private set; }
public static LogCategory Trace { get { return new LogCategory("Trace"); } }
public static LogCategory Debug { get { return new LogCategory("Debug"); } }
public static LogCategory Info { get { return new LogCategory("Info"); } }
public static LogCategory Warning { get { return new LogCategory("Warning"); } }
public static LogCategory Error { get { return new LogCategory("Error"); } }
public override string ToString()
{
return Value;
}
}
```
Pass in **type-safe string values** as a parameter:
```
public static void Write(string message, LogCategory logCategory)
{
var log = new LogEntry { Message = message };
Logger.Write(log, logCategory.Value);
}
```
Usage:
```
Logger.Write("This is almost like an enum.", LogCategory.Info);
``` | You could also use the extension model:
```
public enum MyEnum
{
[Description("String 1")]
V1= 1,
[Description("String 2")]
V2= 2
}
```
Your Extension Class
```
public static class MyEnumExtensions
{
public static string ToDescriptionString(this MyEnum val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
```
usage:
```
MyEnum myLocal = MyEnum.V1;
print(myLocal.ToDescriptionString());
``` | Associating enums with strings in C# | [
"",
"c#",
".net",
""
] |
I know about Arrays.deepEquals(Object[], Object[]) but this doesn't work for primitive types (due limitations of arrays and autoboxing, see [this related post](https://stackoverflow.com/questions/517751/java-generic-method-but-array-of-primitive-data-types-does-not-autobox)).
With that in mind, is this the most efficient approach?
```
boolean byteArrayEquals(byte[] a, byte[] b) {
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
if (a.length != b.length)
return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
``` | Change your first comparison to be:
```
if (a == b)
return true;
```
This not only catches the "both null" cases, but also "compare an array to itself" case.
However, for a simpler alternative - use [`Arrays.equals`](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#equals(byte[],%20byte[])) which has overloads for each primitive type. (The implementation is very similar to yours, except it hoists the array length out of the loop. On .NET that can be an anti-optimization, but I guess the JRE library implementors probably know better for the JVM :) | I think the most efficient should be to use the helper methods in the [Arrays](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html) class, because they might be implemented more cleverly. So in this case, use
```
Arrays.equals(a, b);
``` | Compare two arrays of primitives in Java? | [
"",
"java",
"arrays",
"compare",
"primitive-types",
""
] |
Why can't I use a temporary column in the where clause?
For example, this query:
```
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
1
GROUP BY
product_brand
```
This brings up two columns, one called `product_brand` and one called `brand_count`. `brand_count` is created on the fly and is always 1 or 0 depending on whether or not there are 50 or products with that brand.
All this makes sense to me, except that I can't select only if `brand_count = 1` as in this query below:
```
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
brand_count = 1
GROUP BY
product_brand
```
which gives me this error:
```
#1054 - Unknown column 'brand_count' in 'where clause'
``` | Use `HAVING` instead:
```
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM products
GROUP BY product_brand
HAVING brand_count = 1
```
`WHERE` is evaluated *before* the `GROUP BY`. `HAVING` is evaluated after. | Because in SQL the columns are first "selected" and then "projected". | How to use a temp column in the where clause | [
"",
"mysql",
"sql",
"mysql-error-1054",
""
] |
i've been playing around with Attributes over web services, and i've seen that The SoapHttpClientProtocol class need to define a WebServiceBinding Attribute.
Watching this [question](https://stackoverflow.com/questions/417275/-net-attributes-why-does-getcustomattributes-make-a-new-attribute-instance-eve) there seems one cannot modify the attributes on runtime, how can I achieve a dynamic web service invocation changing this attribute on runtime? is it possible?
[Edit]
I'm searching for an approach to do a dynamic invoke "generic style", rather to modify the WebServiceBinding attribute.
This is, in a nutshell, my class:
```
using System.Web.Services;
using System.Web.Services.Protocols;
namespace Whatever {
[WebServiceBinding(Name = "", Namespace = "")]
public class WebServiceInvoker : SoapHttpClientProtocol {
public WebServiceInvoker(string url, string ns, string bindingName) {
ChangeNamespace(ns);
ChangeBinding(bindingName);
Url = url;
// credentials, etc
}
public void ChangeNamespace(string ns) {
var att = GetType().GetCustomAttributes(typeof (WebServiceBindingAttribute), true);
if (att.Length > 0) {
// doesn't work
((WebServiceBindingAttribute)att[0]).Namespace = ns;
}
}
private void ChangeBinding(string bindingName) {
var att = GetType().GetCustomAttributes(typeof(WebServiceBindingAttribute), true);
if (att.Length > 0) {
// doesn't work
((WebServiceBindingAttribute)att[0]).Name = bindingName;
}
}
public object[] MakeInvoke(string method, object[] args) {
var res = Invoke(method, method);
return res;
}
public TRet InvokeFunction<TRet>(string method) {
//Funcion<T1, T2, T3, TRet>
var res = Invoke(method, null);
return MyUtils.ForceCast<TRet>(res);
}
public TRet InvokeFunction<T1, TRet>(string method, T1 par1) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] { par1 };
var res = Invoke(method, args);
return MyUtils.ForceCast<TRet>(res);
}
public TRet InvokeFunction<T1, T2, TRet>(string method, T1 par1, T2 par2) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] { par1, par2 };
var res = Invoke(method, args);
return MyUtils.ForceCast<TRet>(res);
}
public TRet InvokeFunction<T1, T2, T3, TRet>(string method, T1 par1, T2 par2, T3 par3) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] {par1, par2, par3};
var res = Invoke(method, args);
return MyUtils.ForceCast<TRet>(res);
}
public void InvokeAction(string metodo) {
//Funcion<T1, T2, T3, TRet>
Invoke(method, null);
}
public void InvokeAction<T1>(string method, T1 par1) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] { par1 };
Invoke(method, args);
}
public void InvokeAction<T1, T2>(string method, T1 par1, T2 par2) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] { par1, par2 };
Invoke(method, args);
}
public void InvokeAction<T1, T2, T3>(string method, T1 par1, T2 par2, T3 par3) {
//Funcion<T1, T2, T3, TRet>
var args = new object[] { par1, par2, par3 };
Invoke(method, args);
}
}
}
```
[Edit]
I would like to call my class like so:
```
var miProxy = new WebServiceInvoker("http://webServiceLocation", "ns", "Binding");
var res = miProxy.InvokeFunction<string, string, Entity>("MyWebMethod", stringPar1, stringPar2);
``` | I'm not exactly sure what you're trying to accomplish here... are you trying to create a web service which supports invocation of arbitrary methods by the caller? If so, here is an example of that in practice: [Creating a dynamic Web service to simplify code](http://www.techrepublic.com/article/applied-reflection-creating-a-dynamic-web-service-to-simplify-code/) | You cannot change attributes at runtime. They are just metadata in the IL code and if you query a attribute an instance of the specified attribute class is created and returned. So the actual attribute instances do not exist until you query them.
It might be possible to modify the assembly using reflection but I am not sure and this is probably not a thing you like to try. | Web Services Dynamic Invoker question | [
"",
"c#",
"web-services",
"binding",
"proxy",
""
] |
I could have sworn that there was an extension method already built for the Queryable class that I just can't find, but maybe I'm thinking of something different.
I'm looking for something along the lines of:
```
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ForEach(foo => foo.Status = "Complete");
```
en.Foreach() would essential perform:
```
foreach(Entity foo in en){
foo.Status = "Complete";
}
```
Is this already written? If not, is it possible to write said Extension Method, preferably allowing for any LINQ Table and any Field on that table. Where is a good place to start? | There is a foreach on a List<>. Roughly something along these lines:
```
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ToList().ForEach(foo => foo.status = "Complete");
``` | There's nothing in the base class library. Many, *many* developers have this in their own common library, however, and we have it in [MoreLINQ](http://code.google.com/p/morelinq/) too.
It sort of goes against the spirit of LINQ, in that it's all about side-effects - but it's really useful, so I think pragmatism trumps dogma here.
One thing to note - there's really no point in using a query expression in your example. (It's not *entirely* redundant, but if you're not exposing the value it doesn't matter.) The select isn't doing anything useful here. You can just do:
```
IDB.Entities.ForEach(foo => foo.status = "Complete");
```
Even if you want to do a single "where" or "select" I'd normally use dot notation:
```
IDB.Entities.Where(foo => foo.Name == "fred")
.ForEach(foo => foo.status = "Complete");
```
Only use query expressions where they actually make the code simpler :) | Extension Method to assign value to a field in every item? | [
"",
"c#",
"linq",
"extension-methods",
"iqueryable",
""
] |
If I have a database table containing a flag that can have multiple states, should I do this
```
if ($Object->isStateOne()) {
// do something
}
else if ($Object->isStateTwo()) {
// do something else
}
else if ($Object->isStateThree()) {
// do yet something else
}
```
or this
```
switch ($Object->getSomeFlag()) {
case ObjectMapper::STATE_ONE:
// do something
break;
case ObjectMapper::STATE_TWO:
// do something else
break;
case ObjectMapper::STATE_THREE:
// do yet something else
break;
}
```
? | Whichever makes sense, of course.
The switch looks much cleaner. But, what is this 'state' you are checking? If you're translating a string, use an array, for example.
The if has different behavior from switch. The method calls MAY have side effects. The if is better if multiple states may be active on the object at once, though. | From an OO perspective, both are discouraged. If you have different state, you may want to create a virtual methods, and override it in inherited class. Then based on polymorphism, you can avoid the if, and switch statement. | Should I use methods or constant flags? | [
"",
"php",
"switch-statement",
"if-statement",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.