Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it good to have all the setter functions return a reference to the object in c++? | It's a usable enough pattern if there's a lot of things that need to be set on an object.
```
class Foo
{
int x, y, z;
public:
Foo &SetX(int x_) { x = x_; return *this; }
Foo &SetY(int y_) { y = y_; return *this; }
Foo &SetZ(int z_) { z = z_; return *this; }
};
int main()
{
Foo foo;
foo.SetX(1).SetY(2).SetZ(3);
}
```
This pattern replaces a constructor that takes three ints:
```
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
```
It's useful if you have a number of values that don't always need to be set.
For reference, a more complete example of this sort of technique is refered to as the "[Named Parameter Idiom](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.18)" in the C++ FAQ Lite.
Of course, if you're using this for named parameters, you might want to take a look at [boost::parameter](http://www.boost.org/doc/libs/1_38_0/libs/parameter/doc/html/index.html). Or you might not... | You can return a reference to `this` if you want to chain setter function calls together like this:
```
obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35);
```
Personally I think that code is harder to read than the alternative:
```
obj.SetCount(10);
obj.SetName("Bob");
obj.SetColor(0x223344);
obj.SetWidth(35);
``` | Is it good to have all the setter functions return a reference to the object in c++? | [
"",
"c++",
"reference",
"return-type",
""
] |
PHP seems to use a rather annoying method for setting the evnironment timezone, using region names rather than the GMT offset. This makes having a timezone dropdown a huge pain, because it either has to be huge to accommodate all possible PHP timezone values, or I have to find a way to convert a GMT offset to a valid value to pass to PHP.
So, given a GMT offset, how might I set the timezone in PHP? For example, how might I convert the GMT offset value of "-8.0" to a value that I could pass to `date_timezone_set()`? | Using a region name is the *right* way to describe a time zone. Using a GMT offset on its own is hugely ambiguous.
This is reflected in your question - how should you convert a GMT offset of -8 into a time zone? Well, that depends on what "GMT -8" really means. Does it mean "UTC -8 at every point in time" or does it mean "UTC -8 during winter time, and UTC -7 in summer time"? If it's the latter, when does winter start and end?
I would *hope* that PHP accepted a well-known set of values for the "fixed" (no DST) time zones, e.g. "Etc/GMT+3" etc. But unless you really, really mean a fixed time zone, you're better off finding out which region you're actually talking about, because otherwise your calculations are almost guaranteed to be wrong at some point.
I've been wrestling with time zones for most of the last year. They're a pain - *particularly* when some zones change their rules for DST (like the US did a few years ago) or when some zones opt in and out of DST seemingly at will. Trying to reflect all of this in a single number is folly. If you're only interested in a single instant in time, it might be okay - but at that point you might as well just store the UTC value in the first place. Otherwise, a name is the best approach. (It's not necessarily plain sailing at that point, mind you. Even the names change over time...) | If you are using PHP >= 5.2, you can use the built-in DateTimeZone class method, listAbbreviations.
```
var_dump( DateTimeZone::listAbbreviations() );
``` | Timezone in PHP | [
"",
"php",
"date",
"timezone",
""
] |
I get the need to clean up resources during the teardown of an object, but I have always found the differences between ***Dispose***, ***Finalize***, and the destructor methods a bit confusing.
I found this great article that concisely describes the distinctions between them, that I am going to have to save for future reference:
["Difference between Destructor, Dispose and Finalize methods" - Sanjay Saini](http://sanjaysainitech.blogspot.com/2007/06/difference-between-destructor-dispose.html)
<http://sanjaysainitech.blogspot.com/2007/06/difference-between-destructor-dispose.html>
The fundamental question I am trying to ask here is this.
> If a language offers destructors (for example C# [refuted]) what
> value do ***Dispose*** and
> ***Finalize*** add to the equation?
Am I just a curmudgeon that is used to the old school way of doing everything in the destructor, or is there something I am missing that is only possible by breaking the tear-down of an object into three parts?
**UPDATE:**
As noted in some of the replies, C# does not actually have destructors. The question may be moot at this point in recognition of that. When I read in the above referenced article that C# actually had a separate deconstructor (an error apparently), it threw me for a loop and I started wondering what the point of Dispose and Finalize would be if you had a final destructor to wrap up everything. I suppose that in a GC langauge like C# the concept of a single destructor to provide the denemount for an object doesn't make much sense.
Sorry for the downvotes on some of you guys, but a couple people didn't read the question carefully and thought I was asking about the difference between Dispose and Finalize, which really wasn't the point. | The author of that blog post is a bit confused...
In C#, there is no such thing as a "destructor". Only Finalizers and IDisposable.
The ~ClassName() method is not called a "destructor". It is called a finalizer.
Dispose exists to release resources from code, where the finalizer exists to be called from the GC. Very often, the finalizer calls the Dispose() method, but the ["Dispose Pattern"](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) sets you up to only handle unmanaged resources from the finalizer.
You see, when the finalizer gets called, you are on a different thread, and any managed object you have is not necessarily valid. Because of this, if you call Dispose() from the finalizer, you should really be calling Dispose(false) which tells the "Dispose Pattern" to only dispose unmanaged resources.
Further, the ["Dispose Pattern"](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) suggests that when Dispose(true) is called, you should suppress the finalizer on that object. | Only managed objects can be finalized automatically. If you want to offer *implicit* disposal of unmanaged objects, the Finalizer can be used. If you want to offer *explicit* control of disposal to a caller of your object, you can allow them to call Dispose.
[I like this article](http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx). | What is the point of Finalize and Dispose methods in .NET? (see details before answering) | [
"",
"c#",
".net",
""
] |
Many languages, such as Java, C#, do not separate declaration from implementation. C# has a concept of partial class, but implementation and declaration still remain in the same file.
Why doesn't C++ have the same model? Is it more practical to have header files?
I am referring to current and upcoming versions of C++ standard. | I routinely flip between C# and C++, and the lack of header files in C# is one of my biggest pet peeves. I can look at a header file and learn all I need to know about a class - what it's member functions are called, their calling syntax, etc - without having to wade through pages of the code that implements the class.
And yes, I know about partial classes and #regions, but it's not the same. Partial classes actually make the problem worse, because a class definition is spread across several files. As far as #regions go, they never seem to be expanded in the manner I'd like for what I'm doing at the moment, so I have to spend time expanding those little plus's until I get the view right.
Perhaps if Visual Studio's intellisense worked better for C++, I wouldn't have a compelling reason to have to refer to .h files so often, but even in VS2008, C++'s intellisense can't touch C#'s | **Backwards Compatibility** - Header files are not eliminated because it would break Backwards Compatibility. | Should C++ eliminate header files? | [
"",
"c++",
"header-files",
""
] |
I am working on a shared addin for MS Word 2007. I would like to add a button which pops up when selected text is right clicked. The attached snapshot should make this clear.
Currently, the user has to select the text and then click a button on a custom control. It would be a lot easier if after selecting the text, s/he could right click it and press the relevant button in the popup.
 | Here is how this can be done...
```
Microsoft.Office.Core.CommandBar cellbar = diff.CommandBars["Text"];
Microsoft.Office.Core.CommandBarButton button = (Microsoft.Office.Core.CommandBarButton)cellbar.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 0, "MYRIGHTCLICKMENU", Missing.Value, Missing.Value);
if (button == null)
{
// add the button
button = (Microsoft.Office.Core.CommandBarButton)cellbar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Missing.Value, Missing.Value, cellbar.Controls.Count + 1, true);
button.Caption = "My Right Click Menu Item";
button.BeginGroup = true;
button.Tag = "MYRIGHTCLICKMENU";
button.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(MyButton_Click);
}
``` | You need to extend the correct contextmenu. The following link describes in words (no source code) how this can be achieved:
[Shared Addin using Word](http://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/c2e20f36-35cb-4c2d-b9a4-b464fc7c9989/)
Maybe this [Link](http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/62240ece-ab2d-4f28-b317-e6bd76f34000/) might help a little with the coding. I haven't tried it out myself, but it might point into the right direction.
Good luck! :)
**Edit:**
Does it have to be the ribbon style context menu or would a button within the normal context menu be enough?
In case the normal menu would be ok, you might use this way (C#):
```
Microsoft.Office.Core.CommandBar cb = this.Application.CommandBars["Text"];
Office.CommandBarControl newButton = cb.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, missing);
newButton.Caption = "Test";
newButton.Visible = true;
newButton.Enabled = true;
```
You can do this with VSTO, I'm not so sure if it works exactly the same way with the shared Add-In technology, but maybe it does help ;) | MS Word Plugin, Adding a button which pops up on right click on selected text | [
"",
"c#",
"word-2007",
"shared-addin",
""
] |
Is it ok to take it from Glassfish project ( glassfish-persistence-api) or may be there is a Hibernate jar? | If you are developing an OSGi system I would recommend you to download the "bundlefied" version from [Springsource Enterprise Bundle Repository](http://www.springsource.com/repository/app/).
Otherwise its ok to use a regular jar-file containing the **javax.persistence** package | If you are using maven, adding below dependency should work
```
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
``` | What jar should I include to use javax.persistence package in a hibernate based application? | [
"",
"java",
"hibernate",
"jar",
""
] |
All APIs in Hibernate are from 1.4 and are thus not using java generics.
So I wonder how "safe" the following is: (preconditions: name column is of datatype String, or atleast compatible to String)
```
@SuppressWarnings("unchecked")
public List<String> getAll() {
Query q = session.createQuery(
"select name from Customers");
return q.list();
}
```
From the Queryi API (org.hibernate.Query.list()) javadoc.
["Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[]. "](http://www.hibernate.org/hib_docs/v3/api/) | It'll be safe as long as you are sure that the query does not "contain multiple results per row". (I'm not familiar with queries, so I am unsure whether it can happen in this case.) If a row does contain multiple results, then when you try to access it, it will throw ClassCastException at runtime because that element will be an Object[] object instead of a String object. | Java generics use type erasure, so at runtime there's no difference between a `List`, a `List<String>`, and a `List<Integer>`. All are really just `List`s. At compilation, the compiler will enforce the template parameter type, but under the covers at runtime, you a have a `List`.
In fact, if you try to use reflection to find the template parameter type, you can't. | Hibernate Query API and Java 1.5/Generics | [
"",
"java",
"hibernate",
"generics",
""
] |
Since arguments sent to a method in Java point to the original data structures in the caller method, did its designers intend for them to used for returning multiple values, as is the norm in other languages like C ?
Or is this a hazardous misuse of Java's general property that variables are pointers ? | A long time ago I had a conversation with Ken Arnold (one time member of the Java team), this would have been at the first Java One conference probably, so 1996. He said that they were thinking of adding multiple return values so you could write something like:
```
x, y = foo();
```
The recommended way of doing it back then, and now, is to make a class that has multiple data members and return that instead.
Based on that, and other comments made by people who worked on Java, I would say the intent is/was that you return an instance of a class rather than modify the arguments that were passed in.
This is common practice (as is the desire by C programmers to modify the arguments... eventually they see the Java way of doing it usually. Just think of it as returning a struct. :-)
(Edit based on the following comment)
> I am reading a file and generating two
> arrays, of type String and int from
> it, picking one element for both from
> each line. I want to return both of
> them to any function which calls it
> which a file to split this way.
I think, if I am understanding you correctly, tht I would probably do soemthing like this:
```
// could go with the Pair idea from another post, but I personally don't like that way
class Line
{
// would use appropriate names
private final int intVal;
private final String stringVal;
public Line(final int iVal, final String sVal)
{
intVal = iVal;
stringVal = sVal;
}
public int getIntVal()
{
return (intVal);
}
public String getStringVal()
{
return (stringVal);
}
// equals/hashCode/etc... as appropriate
}
```
and then have your method like this:
```
public void foo(final File file, final List<Line> lines)
{
// add to the List.
}
```
and then call it like this:
```
{
final List<Line> lines;
lines = new ArrayList<Line>();
foo(file, lines);
}
``` | In my opinion, if we're talking about a public method, you should create a separate class representing a return value. When you have a separate class:
* it serves as an abstraction (i.e. a `Point` class instead of array of two longs)
* each field has a name
* can be made immutable
* makes evolution of API much easier (i.e. what about returning 3 instead of 2 values, changing type of some field etc.)
I would always opt for returning a new instance, instead of actually modifying a value passed in. It seems much clearer to me and favors immutability.
On the other hand, if it is an internal method, I guess any of the following might be used:
* an array (`new Object[] { "str", longValue }`)
* a list (`Arrays.asList(...)` returns immutable list)
* pair/tuple class, such as [this](http://javatuple.com/)
* static inner class, with public fields
Still, I would prefer the last option, equipped with a suitable constructor. That is especially true if you find yourself returning the same tuple from more than one place. | Should Java method arguments be used to return multiple values? | [
"",
"java",
"reference",
"arguments",
"return-value",
""
] |
I'm working on a PHP web interface that will receive huge traffic. Some insert/update requests will contain images that will have to be resized to some common sizes to speed up their further retrieval.
One way to do it is probably to set up some asynchronous queue on the server. Eg. set up a table in a db with a tasks queue that would be populated by PHP requests and let some other process on the server watch the table and process any waiting tasks. How would you do that? What would be the proper environment for that long running process? Java, or maybe something lighter would do? | If what you're doing is really high volume then what you're looking for is something like [beanstalkd](http://xph.us/software/beanstalkd/). It is a distributed work queue processor. You just put a job on the queue and then forget about it.
Of course then you need something at the other end reading the queue and processing the work. There are multiple ways of doing this.
The easiest is probably to have a cron job that runs sufficiently often to read the work queue and process the requests. Alternatively you can use some kind of persistent daemon process that is woken up by work becoming available.
The advantage of this kind of approach is you can tailor the number of workers to how much work needs to get done and beanstalkd handles distributed prorcessing (in the sense that the listners can be on different machines). | I use Perl for long running process in combination with beanstalkd. The nice thing is that the Beanstalkd client for Perl has a blocking reserve method. This way it uses almost no CPU time when there is nothing to do. But when it has to do its job, it will automatically start processing. Very efficient. | Best way to offload heavy processing (like image resizing) out of PHP request | [
"",
"php",
"architecture",
"scalability",
""
] |
When editing a C# source file, I type
```
new {
```
Visual Studio auto-corrects it to
```
new object{
```
Is there a way to stop this behavior? | You can configure which characters being typed commit the current intellisense selection. In Tools | Options | Text Editor | C# | IntelliSense.
Remove "{" and ensure committed by the space bar is not checked.
NB. This option is no longer present as of Visual Studio 2015. | I ran into this issue, and the answers above didn't work for me. In my case, it was caused by Resharper, and I addressed it by navigating to **Resharper -> Options -> Environment -> Intellisense -> Completing Characters** and adding the opening curly brace character "{" to the "Do not complete on" list for C#. | How do I stop Visual Studio from inserting "object" when I type "new {" | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"intellisense",
""
] |
We have a web page with this general structure:
```
<div id="container">
<div id="basicSearch">...</div>
<div id="advancedSearch" style="display: none">...</div>
<div>
```
With this CSS:
```
#container { MARGIN: 0px auto; WIDTH: 970px }
#basicSearch { width:100% }
#advancedSearch{ width:100%;}
```
We have a link on the page that lets the user toggle between using the "basic" search and the "advanced" search. The toggle link calls this Javascript:
```
var basic = document.getElementById('basicSearch');
var advanced = document.getElementById('advancedSearch');
if (showAdvanced) {
advanced.style.display = '';
basic.style.display = 'none';
} else {
basic.style.display = '';
advanced.style.display = 'none';
}
```
This all works great in IE.
It works in Firefox too - except - when we toggle (ie: show/hide) from one div to the other, the page "moves" in Firefox. All the text in the "container" moves about 5px to the left/right when you toggle back and forth. Anyone know why? | What I ended up doing was this: `HTML { OVERFLOW-Y:SCROLL; OVERFLOW-X:HIDDEN; }`
Here's a good related [SO](https://stackoverflow.com/questions/311504/long-pages-in-firefox-offset-when-scrollbar-appears) post. | Is it causing a scrollbar to appear / disappear? | Firefox page "moves" when hiding/showing divs | [
"",
"javascript",
"firefox",
"html",
"show-hide",
""
] |
I just switched to Moq and have run into a problem. I'm testing a method that creates a new instance of a business object, sets the properties of the object from user input values and calls a method (SaveCustomerContact ) to save the new object. The business object is passed as a ref argument because it goes through a remoting layer. I need to test that the object being passed to SaveCustomerContact has all of its properties set as expected, but because it is instantiated as new in the controller method I can't seem to do so.
```
public void AddContact() {
var contact = new CustomerContact() { CustomerId = m_model.CustomerId };
contact.Name = m_model.CustomerContactName;
contact.PhoneNumber = m_model.PhoneNumber;
contact.FaxNumber = m_model.FaxNumber;
contact.Email = m_model.Email;
contact.ReceiveInvoiceFlag = m_model.ReceiveInvoiceFlag;
contact.ReceiveStatementFlag = m_model.ReceiveStatementFlag;
contact.ReceiveContractFlag = m_model.ReceiveContractFlag;
contact.EmailFlag = m_model.EmailFlag;
contact.FaxFlag = m_model.FaxFlag;
contact.PostalMailFlag = m_model.PostalMailFlag;
contact.CustomerLocationId = m_model.CustomerLocationId;
RemotingHandler.SaveCustomerContact( ref contact );
}
```
Here's the test:
```
[TestMethod()]
public void AddContactTest() {
int customerId = 0;
string name = "a";
var actual = new CustomerContact();
var expected = new CustomerContact() {
CustomerId = customerId,
Name = name
};
model.Setup( m => m.CustomerId ).Returns( customerId );
model.SetupProperty( m => model.CustomerContactName, name );
model.SetupProperty( m => m.PhoneNumber, string.Empty );
model.SetupProperty( m => m.FaxNumber, string.Empty );
model.SetupProperty( m => m.Email, string.Empty );
model.SetupProperty( m => m.ReceiveInvoiceFlag, false );
model.SetupProperty( m => m.ReceiveStatementFlag, false );
model.SetupProperty( m => m.ReceiveContractFlag, false );
model.SetupProperty( m => m.EmailFlag, false );
model.SetupProperty( m => m.FaxFlag, false );
model.SetupProperty( m => m.PostalMailFlag, false );
model.SetupProperty( m => m.CustomerLocationId, 0 );
remote
.Setup( r => r.SaveCustomerContact( ref actual ) )
.Callback( () => Assert.AreEqual( actual, expected ) );
target.AddContact();
}
```
This is just the most recent of many attempts to get ahold of that parameter. For reference, the value of actual does not change from its initial (constructed) state.
Moving the Assert.AreEqual(expected, actual) after the target call fails. If I add .Verifiable() to the setup instead of the .CallBack and then call remote.Verify after the target (or, I assume, set the mock to strict) it always fails because the parameter I provide in the test is not the same instance as the one that is created in the controller method.
I'm using Moq 3.0.308.2. Any ideas on how to test this would be appreciated. Thanks! | I can't offer you an exact solution, but an alternative would be to hide the pass-by-ref semantics behind an adapter, which takes the parameter by value and forwards it to the RemotingHandler. This would be easier to mock, and would remove the "ref" wart from the interface (I am always suspicious of ref parameters :-) )
EDIT:
Or you could use a stub instead of a mock, for example:
```
public class StubRemotingHandler : IRemotingHandler
{
public CustomerContact savedContact;
public void SaveCustomerContact(ref CustomerContact contact)
{
savedContact = contact;
}
}
```
You can now examine the saved object in your test:
```
IRemotingHandler remote = new StubRemotingHandler();
...
//pass the stub to your object-under-test
...
target.AddContact();
Assert.AreEqual(expected, remote.savedContact);
```
You also say in your comment:
> I'd hate to start a precedent of wrapping random bits of the backend so I can write tests more easily
I think that's *exactly* the precedent you need to set! If your code isn't testable, you're going to keep struggling to test it. Make it easier to test, and increase your coverage. | The latest version of Moq supports this scenario.
Taken from the quickstart at <http://code.google.com/p/moq/wiki/QuickStart>:
```
// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
``` | Verify value of reference parameter with Moq | [
"",
"c#",
"mocking",
"tdd",
"moq-3",
""
] |
This is just a curiosity question I was wondering if anyone had a good answer to:
In the .NET Framework Class Library we have for example these two methods:
```
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate
)
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
```
Why do they use `Func<TSource, bool>` instead of `Predicate<TSource>`? Seems like the `Predicate<TSource>` is only used by `List<T>` and `Array<T>`, while `Func<TSource, bool>` is used by pretty much all `Queryable` and `Enumerable` methods and extension methods... what's up with that? | While `Predicate` has been introduced at the same time that `List<T>` and `Array<T>`, in .net 2.0, the different `Func` and `Action` variants come from .net 3.5.
So those `Func` predicates are used mainly for consistency in the LINQ operators. As of .net 3.5, about using `Func<T>` and `Action<T>` the [guideline states](https://learn.microsoft.com/en-us/archive/blogs/mirceat/linq-framework-design-guidelines#2-extension-methods-func-action-and-expression):
> Do use the new LINQ types `Func<>` and
> `Expression<>` instead of custom
> delegates and predicates | I've wondered this before. I like the `Predicate<T>` delegate - it's nice and descriptive. However, you need to consider the overloads of `Where`:
```
Where<T>(IEnumerable<T>, Func<T, bool>)
Where<T>(IEnumerable<T>, Func<T, int, bool>)
```
That allows you to filter based on the index of the entry as well. That's nice and consistent, whereas:
```
Where<T>(IEnumerable<T>, Predicate<T>)
Where<T>(IEnumerable<T>, Func<T, int, bool>)
```
wouldn't be. | Why Func<T,bool> instead of Predicate<T>? | [
"",
"c#",
".net",
"predicate",
"func",
""
] |
I have an MFC app built using Visual Studio 2008 and it needs to run on W2K, XP, 2003 and Vista. The application writes to HKLM in the registry and will only work on Vista if you run it as Administrator.
My question is: can I force the app to run as Adminstrator automatically? Does it involve creating a manifest file? At the moment I have the following in stdafx.h which I guess creates a manifest file on the fly:
```
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
```
Can I modify this line to force the elevation or do I need to do something with the VC project manifest settings?
Thanks in advance. | I found out how to do this using some advanced C++ linker options:
1. Open the project's Property Pages dialog box.
2. Expand the Configuration Properties node.
3. Expand the Linker node.
4. Select the Manifest File property page.
5. Modify the Enable User Account Control (UAC), UAC Execution Level, and UAC Bypass UI Protection properties. | You can do this using the manifest.
Possibly something like this but I can't recall exactly:
```
<requestedExecutionLevel level="requireAdministrator"/>
``` | Forcing my MFC app to run as Administrator on Vista | [
"",
"c++",
"mfc",
"windows-vista",
""
] |
I have the following `GridView`:
```
<ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" />
<GridViewColumn Header="Album" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Name}"/>
<GridViewColumn Header="Length" Width="100" HeaderTemplate="{StaticResource BlueHeader}"/>
</GridView>
</ListView.View>
</ListView>
```
Now I would like to display a context menu on a right click on a bounded item that will allow me to retrieve the item selected when I handle the event in the code behind.
In what possible way can I accomplish this?
---
**[Update]**
Following [Dennis Roche](https://stackoverflow.com/questions/747872/wpf-displaying-a-context-menu-for-a-gridviews-items/749671#749671)'s code, I now have this:
```
<ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnListViewItem_PreviewMouseLeftButtonDown" />
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Add to Playlist"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" />
<GridViewColumn Header="Album" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Name}"/>
<GridViewColumn Header="Length" Width="100" HeaderTemplate="{StaticResource BlueHeader}"/>
</GridView>
</ListView.View>
</ListView>
```
But upon running, I am receiving this exception:
> Cannot add content of type
> 'System.Windows.Controls.ContextMenu'
> to an object of type 'System.Object'.
> Error at object
> 'System.Windows.Controls.ContextMenu'
> in markup file
> 'MusicRepo\_Importer;component/controls/trackgridcontrol.xaml'.
What is the problem? | Yes, add a ListView.ItemContainerStyle with the Context Menu.
```
<ListView>
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
...
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnListViewItem_PreviewMouseLeftButtonDown" />
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
```
NOTE: You need to reference the ContextMenu as a resource and cannot define it locally.
This will enable the context menu for the entire row. :)
Also see that I handle the `PreviewMouseLeftButtonDown` event so I can ensure the item is focused (and is the currently selected item when you query the ListView). I found that I had to this when changing focus between applications, this may not be true in your case.
**Updated**
In the code behind file you need to walk-up the visual tree to find the list container item as the original source of the event can be an element of the item template (e.g. a stackpanel).
```
void OnListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.Handled)
return;
ListViewItem item = MyVisualTreeHelper.FindParent<ListViewItem>((DependencyObject)e.OriginalSource);
if (item == null)
return;
if (item.Focusable && !item.IsFocused)
item.Focus();
}
```
The `MyVisualTreeHelper` that is use a wrapper that I've written to quickly walk the visual tree. A subset is posted below.
```
public static class MyVisualTreeHelper
{
static bool AlwaysTrue<T>(T obj) { return true; }
/// <summary>
/// Finds a parent of a given item on the visual tree. If the element is a ContentElement or FrameworkElement
/// it will use the logical tree to jump the gap.
/// If not matching item can be found, a null reference is returned.
/// </summary>
/// <typeparam name="T">The type of the element to be found</typeparam>
/// <param name="child">A direct or indirect child of the wanted item.</param>
/// <returns>The first parent item that matches the submitted type parameter. If not matching item can be found, a null reference is returned.</returns>
public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
return FindParent<T>(child, AlwaysTrue<T>);
}
public static T FindParent<T>(DependencyObject child, Predicate<T> predicate) where T : DependencyObject
{
DependencyObject parent = GetParent(child);
if (parent == null)
return null;
// check if the parent matches the type and predicate we're looking for
if ((parent is T) && (predicate((T)parent)))
return parent as T;
else
return FindParent<T>(parent);
}
static DependencyObject GetParent(DependencyObject child)
{
DependencyObject parent = null;
if (child is Visual || child is Visual3D)
parent = VisualTreeHelper.GetParent(child);
// if fails to find a parent via the visual tree, try to logical tree.
return parent ?? LogicalTreeHelper.GetParent(child);
}
}
```
I hope this additional information helps.
Dennis | Dennis,
Love the example, however I did not find any need for your Visual Tree Helper...
```
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem x:Name="menuItem_CopyUsername"
Click="menuItem_CopyUsername_Click"
Header="Copy Username">
<MenuItem.Icon>
<Image Source="/mypgm;component/Images/Copy.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem x:Name="menuItem_CopyPassword"
Click="menuItem_CopyPassword_Click"
Header="Copy Password">
<MenuItem.Icon>
<Image Source="/mypgm;component/Images/addclip.png" />
</MenuItem.Icon>
</MenuItem>
<Separator />
<MenuItem x:Name="menuItem_DeleteCreds"
Click="menuItem_DeleteCreds_Click"
Header="Delete">
<MenuItem.Icon>
<Image Source="/mypgm;component/Images/Delete.png" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
</Style>
</ListView.ItemContainerStyle>
```
Then inside the MenuItem\_Click events I added code that looks like this:
```
private void menuItem_CopyUsername_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(mySelectedItem.Username);
}
```
mySelectedItem is used on the ListView.SelectedItem:
```
<ListView x:Name="ListViewCreds" SelectedItem="{Binding mySelectedItem, UpdateSourceTrigger=PropertyChanged}" ....
```
Please tick me if it helps... | WPF: Displaying a Context Menu for a GridView's Items | [
"",
"c#",
"wpf",
"xaml",
"contextmenu",
""
] |
I have 2 objects. Foo and Bar in two different threads. Now I want to raise an event in Foo but in the thread of Bar.
and how can I use SynchronizationContext.Current for that? | Neither "Foo" nor "Bar" really have threads... you would need an external message-pump mechanism to push messages between threads, such as is provided in winforms (Control.Invoke) and WPF (Dispatcher). Alternatively, something like a (synchronized) producer/consumer queue would suffice *if* you don't mind one of the threads being devoted to waiting (passively) for messages.
Unless you have written your own sync-context, it is impossible for us to say what `SynchronizationContext.Current` will be; in many cases it is `null`.
Can you add more context to the problem? | Synchronization context is used more for Silverlight apps, isn't it? If you need different operations to run in the same thread, launch each operation with SynchronizationContext.Send().
(hopefully that when you say you want to run it in the thread of Bar, that you're referring the the UI thread that the synchronization context will run any Send()d callbacks in. If thats the case, only the event from Foo needs to be Send()d). | C# Synchronize two objects through events | [
"",
"c#",
"multithreading",
"synchronization",
""
] |
I have a number of projects running on a Hudson slave. I'd like one of them to run Ant under Java6, rather than the default (which is Java5 in my environment).
In the project configuration view, I was hoping to find either:
* An explicit option allowing me to set a custom JDK location to use for this project.
* A way to set custom environment variables for this project, which would allow me to set
JAVA\_HOME to the JDK6 location. The would make Ant pick up and run on Java6 as desired.
Is there a way to do either of the above? If one of those facilities is available, I can't see how to access it. I'm running on Hudson 1.285.
I would rather avoid using an "execute shell" operation instead of the "invoke Ant" operation if possible: my slave is on z/OS and Hudson doesn't seem to create the temporary shell scripts properly on this platform (probably an encoding issue). | It turns out that if you make the build parametrised, any string parameters you add become environment variables. With this approach, it is possible to set any environment variable for the build, including JAVA\_HOME, which is picked up by Ant.
So the best solution for me was:
1. In the job configuration page Tick "This build is parameterized"
2. Add an new String parameter called JAVA\_HOME and with the default value set to the JDK location
It's not obvious that build string parameters become environment variables, but once you know that they do, it's easy to set the JDK this way.
The developers on the Hudson mailing list [recommended another approach](http://jenkins.361315.n4.nabble.com/Using-a-specific-JDK-when-running-Ant-on-a-Slave-td379560.html) using the master JDK configurations and overrides in the node configurations... but just setting the JAVA\_HOME env var seems way easier to me. | We have both Java 5 and Java 6 configured for use in our Hudson instance.
Under Manage Hudson -> Configuration System you can add a number of JDKs and specify the path for JAVA\_HOME. In the configuration for each job you then selected which JDK you would like that job to run on. | How can I configure a Hudson job to use a specific JDK? | [
"",
"hudson",
"java",
""
] |
I'm looping through an array of class names in PHP, fetched via get\_declared\_classes().
How can I check each class name to detect whether or not that particular class is an abstract class or not? | Use reflection. [`ReflectionClass`](http://php.net/ReflectionClass)`->isAbstract()`
Use it like this:
```
$class = new ReflectionClass('NameOfTheClass');
$abstract = $class->isAbstract();
``` | You can use [Reflection](https://www.php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionclass) on the class. | In PHP 5.x, how can I detect if a class is abstract or not at run time? | [
"",
"php",
"oop",
"reflection",
""
] |
How to parse in easy way a **.h** file written in **C** for **comments** and entity names using **Python**?
We're suppose for a further writing the content into the word file already developed.
Source comments are formatted using a simple tag-style rules.
Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments.
A comment could be in multi-line form. An each comment have stay straight upon the entity definition:
```
//ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
// could be multi-line. Bla bla bla bla bla bla bla bla bla.
enum my_enum
{
//EITEM My enum item 1.
// Just could be multi-line too.
MY_ENUM_ITEM_1,
//EITEM My enum item 2
MY_ENUM_ITEM_2,
};
//STRUCT My struct
struct my_struct {
//MEMBER struct member 1
int m_1_;
};
//FUNC my function 1 description.
// Could be multi-line also.
//INPUT arg1 - first argument
//RETURN pointer to an allocated my_struct instance.
my_struct* func_1(int arg1);
```
A code-and-comments tree should come out as a result of this parsing.
How does one make it quickly and **without using third-party libraries**? | Here's a quick and dirty solution. It won't handle comments in strings, but since this is just for header files that shouldn't be an issue.
```
S_CODE,S_INLINE,S_MULTLINE = range (3)
f = open (sys.argv[1])
state = S_CODE
comments = ''
i = iter (lambda: f.read (1), '')
while True:
try:
c = i.next ()
except StopIteration:
break
if state == S_CODE:
if c == '/':
c = i.next ()
if c == '*':
state = S_MULTLINE
elif c == '/':
state = S_INLINE
elif state == S_INLINE:
comments += c
if c == '\n':
state == S_CODE
elif state == S_MULTLINE:
if c == '*':
c = i.next ()
if c == '/':
comments += '\n'
state = S_CODE
else:
comments += '*%s' % c
else:
comments += c
print comments
``` | This has already been done. Several times over.
Here is a parser for the C language written in Python. Start with this.
<http://wiki.python.org/moin/SeeGramWrap>
Other parsers.
<http://wiki.python.org/moin/LanguageParsing>
<http://nedbatchelder.com/text/python-parsers.html>
You could probably download any ANSI C Yacc grammar and rework it into PLY format without too much trouble and use that as a jumping-off point. | Easy way to parse .h file for comments using Python? | [
"",
"python",
"parsing",
"lexer",
""
] |
I've a input string:
"risk management, portfolio management, investment planning"
How do I convert this string into:
"risk management" + "portfolio management" + "investment planning"
Thanks. | ## Split and Trim
```
// include linq library like this:
// using System.Linq;
// then
"test1, test2".Split(',').Select(o => o.Trim());
```
or
```
"test1, test2".Split(',').Select(o => o.Trim()).ToArray(); // returns array
```
and
```
"test1, test2".Split(',').Select(o => "\"" + o.Trim() + "\"")
.Aggregate((s1, s2) => s1 + " + " + s2);
// returns a string: "test1" + "test2"
``` | Use the `Split()` method:
```
string[] phrases = s.Split(',');
```
Now you have a string array of each comma separated value.
To remove the spaces, use the `Trim()` method on each string (thanks John Feminella) | String concatenation using C# | [
"",
"c#",
"string",
""
] |
I faced with problem that geomap by google fails with JQuery together in Internet explorer.
Otherwise in Firefox it looks like this:
[](https://i.stack.imgur.com/Tnat6.jpg)
(source: [clip2net.com](http://clip2net.com/clip/m0/1239617014-clip-11kb.jpg))
Here comes js references
```
<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=ABCDEFG">
</script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/js/ui.core.js" type="text/javascript"></script>
<script src="/js/ui.accordion.js" type="text/javascript"></script>
```
[](https://i.stack.imgur.com/K7zBA.jpg)
(source: [clip2net.com](http://clip2net.com/clip/m0/1239620705-clip-21kb.png))
Please anybody help with this...
Thanks in advise. | Fixed by removing JQuery.UI.Dialog from page. | It's hard to debug javascript in IE, but it's even harder to debug without the actual url, or when using minified javascript. You might want to switch to the full non-minified version of jquery temporarily, so that you can find the line where the error occurs and see what's going on.
Also, in firefox you can try using firebug to see if it throws any errors. Even though the map is working in firefox, it may be silently recovering from an error that IE can't recover from. | Google geomap with jquery fails in IE | [
"",
"javascript",
"jquery",
"internet-explorer",
"jquery-ui",
"google-maps",
""
] |
I have an iframe that contains a page that is constantly updating (basically a logger type thing). Is there a way (either via JS/jQuery or otherwise) to force the iframe to stick to the bottom of that inner page even as it expands?
I basically want to mimic the way may log viewers stick to the tail of a log file as it is updated. I found a similar question already here, but the solution doesn't seem to work within an iframe context ([similar question](https://stackoverflow.com/questions/13362/scrolling-overflowed-divs-with-javascript)).
**Update:** Just to clarify, I don't want the iframe at the bottom of the page. I want the contents *inside* the iframe to stay scrolled to the bottom. The iframe has a fixed height, and after the page loads, additional lines are added to that inner page and I want to force the iframe to always show the bottom of that inner page. | does the iframe keep refreshing, and adding content.. or does it keep the connection open? if it isn't keeping the connection open... document.scrollTo() is the javascript method you are looking for.. if you are using ajax to append the information.. do a scrollTo where the number is *VERY* large 0xFFFFFF should work. | Can be achieved using just CSS
```
iframe{
position: absolute;
left: 0;
bottom: 0;
}
```
This will position the iframe relative to the body and it will always appear on the bottom. | Stick Iframe to Bottom | [
"",
"javascript",
"jquery",
"iframe",
""
] |
I'm writing an "envirorment" where each variable is composed by a value and a description:
```
class my_var:
def __init__(self, value, description):
self.value = value
self.description = description
```
Variables are created and put inside a dictionary:
```
my_dict["foo"] = my_var(0.5, "A foo var")
```
This is cool but 99% of operations with variable are with the "value" member. So I have to write like this:
```
print my_dict["foo"].value + 15 # Prints 15.5
```
or
```
my_dict["foo"].value = 17
```
I'd like that all operation on the object my\_dict["foo"] could default to the "value" member. In other words I'd like to write:
```
print my_dict["foo"] + 15 # Prints 5.5
```
and stuff like that.
The only way I found is to reimplement **all** underscore-members (eq, add, str, etc) but I feel like this is the wrong way somehow. Is there a magic method I could use?
A workaround would be to have more dictionaries, like this:
```
my_dict_value["foo"] = 0.5
my_dict_description["foo"] = "A foo var"
```
but I don't like this solution. Do you have any suggestions? | I would personally just use two dictionaries, one for values and one for descriptions. Your desire for magic behavior is not very Pythonic.
With that being said, you could implement your own dict class:
```
class DescDict(dict):
def __init__(self, *args, **kwargs):
self.descs = {}
dict.__init__(self)
def __getitem__(self, name):
return dict.__getitem__(self, name)
def __setitem__(self, name, tup):
value, description = tup
self.descs[name] = description
dict.__setitem__(self, name, value)
def get_desc(self, name):
return self.descs[name]
```
You'd use this class as follows:
```
my_dict = DescDict()
my_dict["foo"] = (0.5, "A foo var") # just use a tuple if you only have 2 vals
print my_dict["foo"] + 15 # prints 15.5
print my_dict.get_desc("foo") # prints 'A foo var'
```
If you decide to go the magic behavior route, then this should be a good starting point. | Two general notes.
1. Please use Upper Case for Class Names.
2. Please (unless using Python 3.0) subclass object. `class My_Var(object):`, for example.
Now to your question.
Let's say you do
```
x= My_Var(0.5, "A foo var")
```
How does python distinguish between `x`, the composite object and x's value (`x.value`)?
Do you want the following behavior?
* Sometimes `x` means the whole composite object.
* Sometimes `x` means `x.value`.
How do you distinguish between the two? How will you tell Python which you mean? | Returning default members when accessing to objects in python | [
"",
"python",
"dynamic-data",
""
] |
I am using VS2005 and NUnit.
I would like to know if there is a way to test popups using just NUnit.
```
button1.click();<-Find/Assert if the popup window has been opened->
``` | If you are testing whether the popup window has opened or not, then I suppose you are working for the Browser and not your project :)
This kind of functionality is tested using [NMock](http://www.nmock.org) or [Rhino.Mocks](http://ayende.com/projects/rhino-mocks.aspx), In which a mock object is created which is in tern equivalent of your UI object, and its "mocked" to have functionality of your UI component, which is used to test the functionality you would expect the UI component/object to pass. | IMHO, it's generally a bad idea to unit test the UI. The very nature of UIs make them problematic for automated testing. They're fluid, and are changed frequently, much more frequently than other code, in ways that will break any tests. Many automated tests are solvable only by taking image snapshots, which is obviously very brittle. Timing concerns become extremely problematic. And finally, such automation relies on taking control of the entire UI, including I/O devices such as the keyboard and mouse. This means that no other activity can be done on the system while the tests are run for fear of breaking the running tests. It's much better to move as much of the functionality out of the UI as humanly possible (patterns such as [Presentation Model](http://martinfowler.com/eaaDev/PresentationModel.html) help with this) and test that functionality instead.
That said, if you must and/or insist on creating automated tests for the UI, you're best served to use an automation library designed just for this. For WinForms and WPF, [White](http://www.codeplex.com/white) is a good example of such a library. | Testing Popups using NUnit | [
"",
"c#",
"unit-testing",
"nunit",
""
] |
I'm planning to package [OpenTibia Server](http://opentibia.svn.sf.net/svnroot/opentibia/otserv/trunk/) for Debian. One of the things I want to do is add startup via `/etc/init.d` and daemonization of the `otserv` process.
Thing is, we should probably redirect output to syslog. This is usually done via the `syslog()` function. Currently, the code is swarmed with:
```
std::cout << "Stuff to printout" << std::endl;
```
Is there a proper, easy to add, way to redirect standard output and standard error output into syslog without replacing every single "call" to std::cout and friends? | Not sure whether a straight "C" answer suffices; but in "C" you can use underlying stdio features to plug the (FILE\*) directly into syslog calls, without an intervening "logger" process. Check out
<http://mischasan.wordpress.com/2011/05/25/redirecting-stderr-to-syslog/> | You can pipe your `stdout` to `syslog` with the `logger` command:
> **NAME**
>
> ```
> logger - a shell command interface to the syslog(3) system log module
> ```
>
> **SYNOPSIS**
>
> ```
> logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]
> ```
>
> **DESCRIPTION**
>
> ```
> Logger makes entries in the system log. It provides a shell command
> interface to the syslog(3) system log module.
> ```
If you don't supply a message on the command line it reads `stdin` | Redirecting standard output to syslog | [
"",
"c++",
"unix",
"redirect",
"daemon",
"syslog",
""
] |
Basically I have,
```
typedef map<std::string, set<double> > MAP_STRING_TO_SET;
```
What is the best way to update (add or remove value) the set with a new value without causing the set to be copied?
The only viable solution I see is to use `map<std::string, set<double>* >` -- something I don't want to do.
Thanks | The set is only copied in initialization.
You are allowed to do something like
```
myMap[myString].insert(myDouble);
```
since map::operator[] returns a reference. | You can also do this:
```
map<std::string, set<double> >::iterator iter = myMap.find(myString);
if(iter != myMap.end())
{
iter->second.insert(myDouble);
}
``` | Using map containing set as a value | [
"",
"c++",
"stl",
""
] |
I have a C++ program that benchmarks various algorithms on input arrays of different length. It looks more or less like this:
```
# (1)
for k in range(4..20):
# (2)
input = generate 2**k random points
for variant in variants:
benchmark the following call
run variant on input array
# (3)
```
Is it possible to reset the whole heap management at (2) to the state it had at (1)? All memory allocated on the heap that was allocated during the program is guaranteed to be freed at (3).
I am using g++ 4.3 on Linux.
Edit: I understand that there is no real garbage collection in C/C++. I want to force the memory allocation to join adjacent empty chunks of memory it has in its free list at (2). | If you want the test runs to start in the same heap states, you can run them in their own processes created by fork(). | I think there's a simple solution to your problem - you could move the outside loop outside of your application and into a shell script or another application and pass the (k) (and any other) parameters through the command line to the benchmarked app - this way you'll be sure all executions had similar starting conditions. | Force garbage collection/compaction with malloc() | [
"",
"c++",
"memory",
"memory-management",
"malloc",
"heap-memory",
""
] |
I'm using a background worker in order to get data from a database. My problem is that I'm struggling to report any errors in the database activity.
I've tried straight up spawning a Dialog (Windows Form that I've created) from the DatabaseUpdater class. However, this hangs and I'm left with a white box instead of the error message. I've tried spawning the Dialog in a separate thread - this results in the Dialog appearing and disappearing almost instantly. Obviously I wasn't entirely surprised by this, but attempts at maintaining the Dialog resulted in the same white box effect.
I guess my question is really what is the best practice for displaying errors coming from threaded activity? | Assuming the BackgroundWorker task in invoked from the UI thread, you should check for and display any errors in the handler for the RunWorkerCompleted event - do not try to handle them in the DoWork handler method... | This is a good resource for multithreading and WinForms: [Synchronizing calls to the UI in a multi-threaded application](http://www.lostechies.com/blogs/gabrielschenker/archive/2009/01/23/synchronizing-calls-to-the-ui-in-a-multi-threaded-application.aspx) | GUI Error Reporting | [
"",
"c#",
".net",
"user-interface",
"error-handling",
""
] |
I don't hear much about GWT any more.
When it first came out, it seemed to be all the rave in certain RIA circles.
But lately my impression is that GWT has suffered a dip in popularity because solutions like Jquery/MooTools/Prototype offer a much easier way of solving the same problem.
Is this accurate or does GWT solve a different type of problem? | GWT and javascript libraries serve two different purposes. GWT generates web applications from java code and javascript libraries can be used as a component within web applications. Because javascript libraries can be used in many different types of web application projects (ASP.NET, Ruby on Rails etc.) they may have more of an audience than GWT but the functionality of GWT isn't something javascript libraries completely replace on their own. Depending on needs, both can be very useful for their respective audiences. | Well, sort of.
The end-product of GWT ends up being something similar to what the other JS frameworks provide - a JavaScript solution that, for the most part, abstracts-away all the browser and DOM inconsistencies so you can focus on Real Work™.
However, there is a significant difference between GWT and the JS frameworks - programmers who author code with GWT are writing Java, which is then compiled into JavaScript.
So what it really comes down to is this: because great JS frameworks now exist, how many web developers are left that know Java, but don't know JavaScript? Ergo, don't know jQuery or MooTools or whatever?
To me, the answer to that question is: not many. | Has Jquery/MooTools/Prototype eliminated the need for GWT? | [
"",
"javascript",
"jquery",
"ajax",
"gwt",
"rich-internet-application",
""
] |
I am building a client-server based solution; client being a desktop application and the server being a web application.
Basically, I need to monitor the performance and resource utilization of the client, which is a .NET 2.0 based Windows Desktop application.
The **most important thing I need to monitor is the network resources the client uses**, i.e. what is the size of the data that flows out from the client to the server and what is the size of the data that the client downloads from the server.
Apart from this, general performance monitoring would help too.
Please guide.
***Edit: A few people have suggested using perfmon, but aren't the values shown in perfmon system-wide? I need these network based stats for a single application only...bytes being sent and received by a single desktop application.*** | You need to split your monitoring in two parts:
* How the system interacts with the server (number of calls performed)
* Amount of network traffic (size of exchanged data for any call)
The first part is (in my experience) often negleted while it has a lot of importance, because acquiring a new connection is often much more expensive that data traffic in itself.
You do not tell us anything about the king of connection you're using (low level tcpip calls, web services, WCF or what else) but my suggestion is:
* Find a way to determine how many time your application calls the server
* Find how much any single call is costing in term of data exchanged
How to monitor these values depends a lot from the technology involved, for some is very simple (if, for example, you're using a web service, setting up [Fiddler](http://www.fiddler2.com/fiddler2/) to monitor the calls and examining an monitoring results is very simple), for other you need to work using a low level traffic analyzer like [Wireshark](http://www.wireshark.org/) or [MS Network Monitor](http://www.microsoft.com/Downloads/details.aspx?FamilyID=f4db40af-1e08-4a21-a26b-ec2f4dc4190d&displaylang=en) and learn how to filter traffic according to IP address of the server, ports used and other parameters.
If you clarify your application architecture I can try to be more specific.
Regards
Massimo | The standard tool for network monitoring is [Wireshark](http://www.wireshark.org).
It allows you to filter the network traffic very flexiblely.
This could be quite an overkill for your application though.
If you are using pure .NET, I would suggest that you add performance logging into your networking classes on the server side- if you are using .Net library classes, then inheritate from them your own classes which add statistics when sending and receiving data. | Monitoring (network) resource utlization and performance of a windows application | [
"",
"c#",
".net",
"performance",
"networking",
"resources",
""
] |
I am facing strange problem,
Whenever I commented second **if** condition, it works in Production, but fail in development.
And when I dont comments second if condtion of code, it works for development and fail for production.
```
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblDocument.Text = "Document :" + this.Request.QueryString["A_No"].ToString();
//if (!frmViewer.Action.Contains("?"))
//{
// frmViewer.Action = String.Format("{0}?A_No={1}&A_Format={2}",
// frmViewer.Action,
//this.Request.QueryString["A_No"].ToString(),
// //this.Request.QueryString["A_Format"].ToString());
// }
}
}
```
Here is Error message:
**CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'** | Well **Barbaros Alp** give me following hint to solve this problem...
**Right Click on the solution > Click Clean Solution then Build Solution –** | Did you verify that your ASPX file was migrated up to production with the latest changes?
It looks to me that the Action control was added in development, and the DLL file migrated up to production, but not the corresponding ASPX file. | ASP.Net Problem in Prod/Dev | [
"",
"c#",
"asp.net",
""
] |
I want to make an archive\_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this
```
2009 - Jan, Feb, Mar
2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
2007 - Sep, Oct, Nov, Dec
``` | This will give you a list of unique posting dates:
```
Posts.objects.filter(draft=False).dates('post_date','month',order='DESC')
```
Of course you might not need the draft filter, and change 'post\_date' to your field name, etc. | I found the answer to my own question.
[It's on this page](http://docs.djangoproject.com/en/dev/ref/models/querysets/) in the documentation.
There's a function called dates that will give you distinct dates. So I can do
Entry.objects.dates('pub\_date','month') to get a list of datetime objects, one for each year/month. | Select Distinct Years and Months for Django Archive Page | [
"",
"python",
"django",
"datetime",
"django-views",
"django-queryset",
""
] |
Is it jQuery? Is there a way to integrate support for the excellent ExtJS or YUI libraries?
Any news on whether Visual Studio 2010 will support another JS framework? | If you have either documented or debug versions of the framework you want to use, [VS 2008 will give you IntelliSense](http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx) of the referenced JS libraries.
If you've installed the [additional IntelliSense hotfix](http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx) [KB958502](http://code.msdn.microsoft.com/KB958502/Release/ProjectReleases.aspx?ReleaseId=1736), you can take advantage of VS automatically finding copies of documented JS files named .vsdoc.js or .debug.js next to your referenced minified versions.
Going forward, VS 2010 will have even more support for JavaScript, working out parameter types from usage, etc.
Microsoft have started offering **support** for jQuery - which is different to VS supporting a JavaScript framework - this means that you can phone MS up and say your site isn't working with jQuery, and they will help you fix it (as a standard support incident, like they would if you found an issue in VS itself, or IIS, or even Word). | I have only seen that Microsoft will support JQuery. But that has less to do with Visual Studio and IIS, and more to do with Microsoft Support practices. JQuery will be shipped with Visual Studio 2010, the Microsoft AJAX Framework, and the ASP.Net MVC Framework (happening now).
But you can use any JavaScript library you want, and if you have the correct service packs you should also get a bit of intelesence with Visual Studio 2008.
The one "extra" JQuery gives you that I have not seen (yet) from other JavaScript libraries is a version of their library with Visual Studio comments in them, giving better intelesense directives. | Which JavaScript framework does Visual Studio natively support? | [
"",
"asp.net",
"javascript",
""
] |
I;m trying yo implement a javacript function which will not allow to the user to input anything else than float numbers (digits)
This is my approach but I don't know how to improve it in order to allow submition of negatives numbers also (allow '-' key) and work on IE also.
```
function digits_only(evt, form) {
var evt = evt || window.event,
targ = evt.target || evt.srcElement,
charCode = evt.which || evt.keyCode,
keyChar = String.fromCharCode(charCode),
isValid = true;
if (charCode > 13) {
isValid = /[0-9.]/.test(keyChar);
//if a dolt is already in input
if (keyChar === '.' && /\./.test(targ.value)) {
isValid = false;
}
}
return isValid;
}
``` | I think you are looking for so called "input masks". They are a lot more powerful then just allowing numbers. But you can surly use them for that. Google "javascript input mask" or check out [this jQuery Plugin](http://digitalbush.com/projects/masked-input-plugin/).
EDIT:
Seems like the linked plugin only supports fixed length masks, but the term may be a good starting point... | Is this on an ASP.NET web application? You could use the AjaxControlToolkits MaskEditExtender. | allow digits only for inputs | [
"",
"javascript",
"parsing",
""
] |
I am trying to implement WMD onto my website and was wondering how would I go about running showdown.js server side to convert markdown to HTML? (in order to store both in the DB)
I am using PHP...any tips would be helpful (never ran any sort of js from php before)
Thanks,
Andrew | You could use [PHP Markdown](http://michelf.com/projects/php-markdown/), which is a port of the [Markdown](http://daringfireball.net/projects/markdown/) program written by John Gruber.
Here is a example of how to use PHP Markdown with your code.
```
include_once "markdown.php";
$my_html = Markdown($my_text);
``` | If you're going to run a markdown converter, why run the javascript port? Isn't that a bit backwards?
Markdown was originally designed to run server-side, showdown is a port that allows the conversion to happen in javascript.
[Here is where you start](http://daringfireball.net/projects/markdown/). | running showdown.js serverside to conver Markdown to HTML (in PHP) | [
"",
"php",
"html",
"markdown",
"wmd",
""
] |
I am currently working with using Bezier curves and surfaces to draw the famous Utah teapot. Using Bezier patches of 16 control points, I have been able to draw the teapot and display it using a 'world to camera' function which gives the ability to rotate the resulting teapot, and am currently using an orthographic projection.
The result is that I have a 'flat' teapot, which is expected as the purpose of an orthographic projection is to preserve parallel lines.
However, I would like to use a perspective projection to give the teapot depth. My question is, how does one take the 3D xyz vertex returned from the 'world to camera' function, and convert this into a 2D coordinate. I am wanting to use the projection plane at z=0, and allow the user to determine the focal length and image size using the arrow keys on the keyboard.
I am programming this in java and have all of the input event handler set up, and have also written a matrix class which handles basic matrix multiplication. I've been reading through wikipedia and other resources for a while, but I can't quite get a handle on how one performs this transformation. | The standard way to represent 2D/3D transformations nowadays is by using **homogeneous coordinates**. *[x,y,w]* for 2D, and *[x,y,z,w]* for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:
1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be *isotropic*; scaling and shearing makes the normals malformed.
2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the *perspective divide*.
3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. **Sutherland-Hodgeman clipping** is the most widespread clipping algorithm in use.
4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.
This stage is the actual projection, because z isn't used as a component in the position any more.
## The algorithms:
### Calculation of field-of-view
This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but *angle* must match. Notice that the result reaches infinity as *angle* nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep *angle* less or equal to 179 degrees.
```
fov = 1.0 / tan(angle/2.0)
```
Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.
### Calculation of the clip matrix
This is the layout of the clip matrix. *aspectRatio* is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.
```
[fov * aspectRatio][ 0 ][ 0 ][ 0 ]
[ 0 ][ fov ][ 0 ][ 0 ]
[ 0 ][ 0 ][(far+near)/(far-near) ][ 1 ]
[ 0 ][ 0 ][(2*near*far)/(near-far)][ 0 ]
```
### Screen Projection
After clipping, this is the final transformation to get our screen coordinates.
```
new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;
```
## Trivial example implementation in C++
```
#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>
struct Vector
{
Vector() : x(0),y(0),z(0),w(1){}
Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}
/* Assume proper operator overloads here, with vectors and scalars */
float Length() const
{
return std::sqrt(x*x + y*y + z*z);
}
Vector Unit() const
{
const float epsilon = 1e-6;
float mag = Length();
if(mag < epsilon){
std::out_of_range e("");
throw e;
}
return *this / mag;
}
};
inline float Dot(const Vector& v1, const Vector& v2)
{
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
class Matrix
{
public:
Matrix() : data(16)
{
Identity();
}
void Identity()
{
std::fill(data.begin(), data.end(), float(0));
data[0] = data[5] = data[10] = data[15] = 1.0f;
}
float& operator[](size_t index)
{
if(index >= 16){
std::out_of_range e("");
throw e;
}
return data[index];
}
Matrix operator*(const Matrix& m) const
{
Matrix dst;
int col;
for(int y=0; y<4; ++y){
col = y*4;
for(int x=0; x<4; ++x){
for(int i=0; i<4; ++i){
dst[x+col] += m[i+col]*data[x+i*4];
}
}
}
return dst;
}
Matrix& operator*=(const Matrix& m)
{
*this = (*this) * m;
return *this;
}
/* The interesting stuff */
void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
{
Identity();
float f = 1.0f / std::tan(fov * 0.5f);
data[0] = f*aspectRatio;
data[5] = f;
data[10] = (far+near) / (far-near);
data[11] = 1.0f; /* this 'plugs' the old z into w */
data[14] = (2.0f*near*far) / (near-far);
data[15] = 0.0f;
}
std::vector<float> data;
};
inline Vector operator*(const Vector& v, const Matrix& m)
{
Vector dst;
dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
return dst;
}
typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
float halfWidth = (float)width * 0.5f;
float halfHeight = (float)height * 0.5f;
float aspect = (float)width / (float)height;
Vector v;
Matrix clipMatrix;
VecArr dst;
clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
/* Here, after the perspective divide, you perform Sutherland-Hodgeman clipping
by checking if the x, y and z components are inside the range of [-w, w].
One checks each vector component seperately against each plane. Per-vertex
data like colours, normals and texture coordinates need to be linearly
interpolated for clipped edges to reflect the change. If the edge (v0,v1)
is tested against the positive x plane, and v1 is outside, the interpolant
becomes: (v1.x - w) / (v1.x - v0.x)
I skip this stage all together to be brief.
*/
for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
v = (*i) * clipMatrix;
v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
dst.push_back(v);
}
/* TODO: Clipping here */
for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
}
return dst;
}
```
If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved.
The DevMaster forums at <http://www.devmaster.net/> have a lot of nice articles related to software rasterizers as well. | *I think [this](https://stackoverflow.com/questions/701504/perspective-projection-help-a-noob/701978#701978) will probably answer your question. Here's what I wrote there*
---
Say the camera's at (**Xc**, **Yc**, **Zc**) and the point you want to project is **P** = (**X**, **Y**, **Z**). The distance from the camera to the 2D plane onto which you are projecting is **F** (so the equation of the plane is **Z**-**Zc**=**F**). The 2D coordinates of **P** projected onto the plane are (**X'**, **Y'**).
Then, very simply:
```
X' = ((X - Xc) * (F/Z)) + Xc
Y' = ((Y - Yc) * (F/Z)) + Yc
```
If your camera is the origin, then this simplifies to:
```
X' = X * (F/Z)
Y' = Y * (F/Z)
``` | How to convert a 3D point into 2D perspective projection? | [
"",
"java",
"graphics",
"3d",
"bezier",
""
] |
I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
```
The actual line of code was
```
s=unicodestring.replace('\xa0','')
```
Anyway-I decided that I needed to preface it with an r so I ran this line of code:
```
s=unicodestring.replace(r'\xa0','')
```
It runs without error but I when I look at a slice of s I see that the \xaO is still there | may be you should be doing
```
s=unicodestring.replace(u'\xa0',u'')
``` | ```
s=unicodestring.replace('\xa0','')
```
..is trying to create the unicode character `\xa0`, which is not valid in an ASCII sctring (the default string type in Python until version 3.x)
The reason `r'\xa0'` did not error is because in a raw string, escape sequences have no effect. Rather than trying to encode `\xa0` into the unicode character, it saw the string as a "literal backslash", "literal x" and so on..
The following are the same:
```
>>> r'\xa0'
'\\xa0'
>>> '\\xa0'
'\\xa0'
```
This is something resolved in Python v3, as the default string type is unicode, so you can just do..
```
>>> '\xa0'
'\xa0'
```
> I am trying to clean all of the HTML out of a string so the final output is a text file
I would strongly recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for this. Writing an HTML cleaning tool is difficult (given how horrible most HTML is), and BeautifulSoup does a great job at both parsing HTML, and dealing with Unicode..
```
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<html><body><h1>Hi</h1></body></html>")
>>> print soup.prettify()
<html>
<body>
<h1>
Hi
</h1>
</body>
</html>
``` | How to work with unicode in Python | [
"",
"python",
"string",
"unicode",
"replace",
"unicode-string",
""
] |
How do I handle simultaneous key presses in Java?
I'm trying to write a game and need to handle multiple keys presses at once.
When I'm holding a key (let's say to move forward) and then I hold another key (for example, to turn left), the new key is detected but the old pressed key isn't being detected anymore. | One way would be to keep track yourself of what keys are currently down.
When you get a keyPressed event, add the new key to the list; when you get a keyReleased event, remove the key from the list.
Then in your game loop, you can do actions based on what's in the list of keys. | Here is a code sample illustrating how to perform an action when CTRL+Z is pressed:
```
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class p4 extends Frame implements KeyListener
{
int i=17;
int j=90;
boolean s1=false;
boolean s2=false;
public p4()
{
Frame f=new Frame("Pad");
f.setSize(400,400);
f.setLayout(null);
Label l=new Label();
l.setBounds(34,34,88,88);
f.add(l);
f.setVisible(true);
f.addKeyListener(this);
}
public static void main(String arg[]){
new p4();
}
public void keyReleased(KeyEvent e) {
//System.out.println("re"+e.getKeyChar());
if(i==e.getKeyCode())
{
s1=false;
}
if(j==e.getKeyCode())
{
s2=false;
}
}
public void keyTyped(KeyEvent e) {
//System.out.println("Ty");
}
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
System.out.println("pre"+e.getKeyCode());
if(i==e.getKeyCode())
{
s1=true;
}
if(j==e.getKeyCode())
{
s2=true;
}
if(s1==true && s2==true)
{
System.out.println("EXIT NOW");
System.exit(0);
}
}
/** Handle the key released event from the text field. */
}
``` | How do I handle simultaneous key presses in Java? | [
"",
"java",
"events",
"keyboard",
""
] |
I have a database that is part of a Merge Replication scheme that has a GUID as it's PK. Specifically the Data Type is *uniqueidentifier*, Default Value *(newsequentialid())*, RowGUID is set to *Yes*. When I do a InsertOnSubmit(CaseNote) I thought I would be able to leave CaseNoteID alone and the database would input the next Sequential GUID like it does if you manually enter a new row in MSSMS. Instead it sends *00000000-0000-0000-0000-000000000000*. If I add `CaseNoteID = Guid.NewGuid(),` the I get a GUID but not a Sequential one (I'm pretty sure).
Is there a way to let SQL create the next sequential id on a LINQ InsertOnSubmit()?
For reference below is the code I am using to insert a new record into the database.
```
CaseNote caseNote = new CaseNote
{
CaseNoteID = Guid.NewGuid(),
TimeSpentUnits = Convert.ToDecimal(tbxTimeSpentUnits.Text),
IsCaseLog = chkIsCaseLog.Checked,
ContactDate = Convert.ToDateTime(datContactDate.Text),
ContactDetails = memContactDetails.Text
};
caseNotesDB.CaseNotes.InsertOnSubmit(caseNote);
caseNotesDB.SubmitChanges();
```
---
Based on one of the suggestions below I enabled the Autogenerated in LINQ for that column and now I get the following error --> *The target table of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.*
Ideas? | In the Linq to Sql designer, set the Auto Generated Value property to true for that column.
This is equivalent to the [IsDbGenerated property](http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.isdbgenerated.aspx) for a column. The only limitation is that you can't update the value using Linq. | From the top of the "Related" box on the right:
[Sequential GUID in Linq-to-Sql?](https://stackoverflow.com/questions/665417/sequential-guid-in-linq-to-sql)
If you really want the "next" value, use an int64 instead of GUID. COMB guid will ensure that the GUIDs are ordered. | LINQ to SQL Insert Sequential GUID | [
"",
"c#",
"linq",
"guid",
""
] |
Is it possible to pass a method as a parameter to a method?
```
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
``` | Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the `self` parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
```
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
```
Note: I believe a `__call__()` method does exist, i.e. you *could* technically do `methodToRun.__call__()`, but you probably should never do so explicitly. `__call__()` is meant to be implemented, not to be invoked from your own code.
If you wanted `method1` to be called with arguments, then things get a little bit more complicated. `method2` has to be written with a bit of information about how to pass arguments to `method1`, and it needs to get values for those arguments from somewhere. For instance, if `method1` is supposed to take one argument:
```
def method1(self, spam):
return 'hello ' + str(spam)
```
then you could write `method2` to call it with one argument that gets passed in:
```
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
```
or with an argument that it computes itself:
```
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
```
You can expand this to other combinations of values passed in and values computed, like
```
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
```
or even with keyword arguments
```
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
```
If you don't know, when writing `method2`, what arguments `methodToRun` is going to take, you can also use argument unpacking to call it in a generic way:
```
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
```
In this case `positional_arguments` needs to be a list or tuple or similar, and `keyword_arguments` is a dict or similar. In `method2` you can modify `positional_arguments` and `keyword_arguments` (e.g. to add or remove certain arguments or change the values) before you call `method1`. | Yes it is possible. Just call it:
```
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
``` | How do I pass a method as a parameter in Python | [
"",
"python",
"parameter-passing",
""
] |
Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
`String.trim()` throws a NPE when invoked on a null String. So I have to do:
```
if(str!=null)
setValue(str.trim());
else
setValue("");
```
What if I create a utility method that checks for the null?
```
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
```
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach? | I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at [StringUtils.trimToEmpty()](http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#trimToEmpty(java.lang.String)). Good luck. | > *some developers on the team might not like/not know this utility*
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your **team** | Homegrown utility methods | [
"",
"java",
"utilities",
""
] |
```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever.example">some text</a>'`, it will only print 'some text', `'<b>hello</b>'` prints 'hello', etc. How would one go about doing this? | I always used this function to strip HTML tags, as it requires only the Python stdlib:
For Python 3:
```
from io import StringIO
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
```
For Python 2:
```
from HTMLParser import HTMLParser
from StringIO import StringIO
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
``` | If you need to strip HTML tags to do text processing, a simple regular expression will do. **Do not use this if you are looking to sanitize user-generated HTML to prevent XSS attacks. It is not a secure way to remove all `<script>` tags or tracking `<img>`s.** The following regular expression will fairly reliably strip most HTML tags:
```
import re
re.sub('<[^<]+?>', '', text)
```
For those that don't understand regex, this searches for a string `<...>`, where the inner content is made of one or more (`+`) characters that isn't a `<`. The `?` means that it will match the smallest string it can find. For example given `<p>Hello</p>`, it will match `<'p>` and `</p>` separately with the `?`. Without it, it will match the entire string `<..Hello..>`.
If non-tag `<` appears in html (eg. `2 < 3`), it should be written as an escape sequence `&...` anyway so the `^<` may be unnecessary. | Strip HTML from strings in Python | [
"",
"python",
"html",
""
] |
Say I have a table 'orders' created as:
```
CREATE TABLE orders (id SERIAL,
customerID INTEGER,
timestamp BIGINT,
PRIMARY KEY(id));
```
Timestamp being the UNIX timestamp. Now i want to select the ids of the LATEST orders for every customer. As a view would be nice.
however the following statement
```
CREATE VIEW lastOrders AS SELECT id,
customerID,
MAX(timestamp)
FROM orders
GROUP BY customerID;
```
Causes a postgre error:
> ERROR: column "orders.id" must appear in the GROUP BY
> clause or be used in an aggregate function
What am I doing wrong? | For these kind of things you can use 2 approaches. One has been already shown by Jens.
Other, is to use "DISTINCT ON" clause:
```
CREATE VIEW lastOrders AS
SELECT
DISTINCT ON (customerID)
id,
customerID,
timestamp
FROM orders
ORDER BY customerID, timestamp desc;
``` | The following query should return only the very last order for each customer.
```
CREATE VIEW last_orders AS
SELECT id, customer_id, timestamp
FROM orders AS o
WHERE timestamp = (
SELECT MAX(timestamp)
FROM orders AS oi
WHERE o.customer_id = oi.customer_id
);
```
(Assuming that you can't have two orders for a customer with the exact same timestamp value.)
Edit: Postgres's `DISTINCT ON` is a much niftier way of doing this. I'm glad I learned about it. But, the above works for other RDBMSs. | group-by question in postgresql | [
"",
"sql",
"postgresql",
"group-by",
""
] |
I have 2 networked apps that should send serialized protobuf-net messages to each other. I can serialize the objects and send them, however, **I cannot figure out how to deserialize the received bytes**.
I tried to deserialize with this and it failed with a NullReferenceException.
```
// Where "ms" is a memorystream containing the serialized
// byte array from the network.
Messages.BaseMessage message =
ProtoBuf.Serializer.Deserialize<Messages.BaseMessage>(ms);
```
I am passing a header before the serialized bytes that contains message type ID, which I can use in a giant switch statement to return the expected sublcass Type. With the block below, I receive the error: System.Reflection.TargetInvocationException ---> System.NullReferenceException.
```
//Where "ms" is a memorystream and "messageType" is a
//Uint16.
Type t = Messages.Helper.GetMessageType(messageType);
System.Reflection.MethodInfo method =
typeof(ProtoBuf.Serializer).GetMethod("Deserialize").MakeGenericMethod(t);
message = method.Invoke(null, new object[] { ms }) as Messages.BaseMessage;
```
Here's the function I use to send a message over the network:
```
internal void Send(Messages.BaseMessage message){
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()){
ProtoBuf.Serializer.Serialize(ms, message);
byte[] messageTypeAndLength = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(message.messageType), 0, messageTypeAndLength, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes((UInt16)ms.Length), 0, messageTypeAndLength, 2, 2);
this.networkStream.Write(messageTypeAndLength);
this.networkStream.Write(ms.ToArray());
}
}
```
This the class, with base class, I'm serializing:
```
[Serializable,
ProtoContract,
ProtoInclude(50, typeof(BeginRequest))]
abstract internal class BaseMessage
{
[ProtoMember(1)]
abstract public UInt16 messageType { get; }
}
[Serializable,
ProtoContract]
internal class BeginRequest : BaseMessage
{
[ProtoMember(1)]
public override UInt16 messageType
{
get { return 1; }
}
}
```
---
**Fixed** using Marc Gravell's suggestion. I removed the ProtoMember attribute from the readonly properties. Also switched to using SerializeWithLengthPrefix. Here's what I have now:
```
[Serializable,
ProtoContract,
ProtoInclude(50, typeof(BeginRequest))]
abstract internal class BaseMessage
{
abstract public UInt16 messageType { get; }
}
[Serializable,
ProtoContract]
internal class BeginRequest : BaseMessage
{
public override UInt16 messageType
{
get { return 1; }
}
}
```
To receive an object:
```
//where "this.Ssl" is an SslStream.
BaseMessage message =
ProtoBuf.Serializer.DeserializeWithLengthPrefix<BaseMessage>(
this.Ssl, ProtoBuf.PrefixStyle.Base128);
```
To send an object:
```
//where "this.Ssl" is an SslStream and "message" can be anything that
// inherits from BaseMessage.
ProtoBuf.Serializer.SerializeWithLengthPrefix<BaseMessage>(
this.Ssl, message, ProtoBuf.PrefixStyle.Base128);
``` | First; for network usage, there is `SerializeWithLengthPrefix` and `DeserializeWithLengthPrefix` which handle length for you (optionally with a tag). The `MakeGenericMethod` looks OK at first glance; and this actually ties in very closely to the pending commit of the work I've been doing to implement an RPC stack: the pending code `has an override of DeserializeWithLengthPrefix` that takes (essentially) a `Func<int,Type>`, to resolve a tag to a type to make it easier to deserialize unexpected data on the fly.
If the message type actually relates to the inheritance between `BaseMessage` and `BeginRequest`, then you don't need this; it always goes to the top-most contract type in the hierarchy and works its way down (due to some wire details).
Also - I haven't had chance to test it, but the following might be upsetting it:
```
[ProtoMember(1)]
public override UInt16 messageType
{
get { return 1; }
}
```
It is marked for serialization, but has no mechanism for setting the value. Maybe this is the issue? Try removing the `[ProtoMember]` here, since I don't this is useful - it is (as far as serialization is concerned), largely a duplicate of the `[ProtoInclude(...)]` marker. | ```
Serializer.NonGeneric.Deserialize(Type, Stream); //Thanks, Marc.
```
or
```
RuntimeTypeModel.Default.Deserialize(Stream, null, Type);
``` | Deserialize unknown type with protobuf-net | [
"",
"c#",
"serialization",
"protocol-buffers",
"protobuf-net",
""
] |
Is it possible using jQuery (or any other JavaScript function) to detect when an onmouseover event is fired?
I have a page where existing javaScript calls a onmouseover/out events to re-write the contents of the div. I'm actually only interested in getting at what the div contains while the mouse is hovered over it. The onmouseover event is generated server-side by a program I don't have the ability to change :(.
Any suggestions on how to accomplish this? | Here's an even more specific example:
```
$("#idOfYourControl").hover(
function() { $('#divToShowText').text($(this).text()) },
function() { $('#divToShowText').text("") }
);
``` | ```
$("#idOfYourControl").hover(function() { /*mouseover event*/ }, function() { /*mouseout event*/ });
``` | jquery detect change in dom outsite jquery | [
"",
"javascript",
"jquery",
"dom",
""
] |
***Read EDIT 2 first***
I am trying to set up some way to visually distinguish the nodes in a winform app. For example, alternating colors.
Can some one start me down that path? Also, has anyone else had to do that before and how did you do it?
Thanks
## EDIT
I had seen the backcolor setting as well(Thank You) but I am having trouble getting it to work. I do not see a Paint() event for treeviews. I tried putting the below code in my Form Load() but it isn't working. Possibly because the treeview is loaded yet??
```
private void frmCaseNotes_Load(object sender, System.EventArgs e)
{
foreach (TreeNode treeNode in treeView1.Nodes[0].Nodes)
{
treeNode.BackColor = Color.DeepSkyBlue;
}
}
```
## EDIT 2
Okay, I have the initial problem out of the way using the below on Form\_Load()
```
foreach (TreeNode treeNode in treeView1.Nodes)
{
if (treeNode.Index % 2 == 0)
{
treeNode.ForeColor = Color.DodgerBlue;
}
else
{
treeNode.ForeColor = Color.Goldenrod;
}
```
Now what I need to figure out, with someone's help, is how to Loop through **ALL** layers of nodes and apply my alternating coloring. If I do something along the below lines I can *achieve* this.
```
foreach (TreeNode treeNode in treeView1.Nodes[1].Nodes[0].Nodes)
{
if (treeNode.Index % 2 == 0)
{
treeNode.ForeColor = Color.DodgerBlue;
}
else
{
treeNode.ForeColor = Color.Goldenrod;
}
```
How do I iterate through ALL layers programatically? | Recursion?
**Edit: added code for eliminating color repetition**
```
protected void ColorNodes(TreeNode root, Color firstColor, Color secondColor)
{
Color nextColor;
foreach (TreeNode childNode in root.Nodes)
{
nextColor = childNode.ForeColor = childNode.Index % 2 == 0 ? firstColor : secondColor;
if (childNode.Nodes.Count > 0)
{
// alternate colors for the next node
if (nextColor == firstColor)
ColorNodes(childNode, secondColor, firstColor);
else
ColorNodes(childNode, firstColor, secondColor);
}
}
}
private void frmCaseNotes_Load(object sender, System.EventArgs e)
{
foreach (TreeNode rootNode in treeView1.Nodes)
{
ColorNodes(rootNode, Color.Goldenrod, Color.DodgerBlue);
}
}
``` | Dude, this one was serious trouble. The Broadth Search was easy, but you were right. Depth Search was a pain. I hope it helps you. Shame that such nice trick will probably fall into oblivion due to the sheer ammount of questions on this site. The depth algorithm is kind of crude and assume a head node without siblings.
```
//depth search on TreeView
TreeNode node = trv.Nodes[0];
Stack<TreeNode> list = new Stack<TreeNode>();
list.Push(node);
while (list.Count > 0)
{
while (node.Nodes.Count > 0)
{
list.Push(node.Nodes[0]);
node = node.Nodes[0];
}
//Will always have a leaf here as the current node. The leaf is not pushed.
//If it has a sibling, I will try to go deeper on it.
if (node.NextNode != null)
{
node = node.NextNode;
continue;
}
//If it does NOT have a sibling, I will pop as many parents I need until someone
//has a sibling, and go on from there.
while (list.Count > 0 && node.NextNode == null)
{
node = list.Pop();
}
if (node.NextNode != null) node = node.NextNode;
}
//broadth search on TreeView
Queue<TreeNode> list = new Queue<TreeNode>();
foreach(TreeNode node in trv.Nodes)
{
list.Enqueue(node);
}
foreach(TreeNode node in list)
{
foreach(TreeNode childNode in node.Nodes)
{
list.Enqueue(childNode);
}
}
``` | How do I loop through all layers of Treeview nodes? | [
"",
"c#",
"winforms",
".net-3.5",
"loops",
""
] |
Is there an easy way to read settings from a (asp.net) web.config file using javascript within a html page?
BTW I have found examples of passing config settings into javascript blocks within aspx pages e.g.
```
<script type="text/javascript">
function ReadConfigSettings(){
var wibble = '<%=ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString %>' }
</script>
```
but this is NOT what I'm trying to do. I need to read the settings from within a stand-alone html page. | If the HTML/Javascript is running from a Virtual Directory in IIS then there's no direct way to access the .config file in Javascript as the asp.net handlers prevent ".config" files from being served. So, no loading the file into an IFrame/Ajax request.
One option is an .aspx file on the server which returns the applicable value from the .config file, so:
<http://myhost/mydirectiory/GetConfigurationValue.aspx?key=MyConnString>
called from Javascript would return XML of "connectionStringGoesHere" which can then be used.? | You can't. The config file is server side and not accessible (deliberately and quite rightly) from the client side. | Read .net config files with Javascript (not javascript in an aspx page) | [
"",
".net",
"javascript",
"web-config",
""
] |
The point is to notify the user using the memo when a packet is received/sent in a TCP Client.
The old code was extra dumb,I used a Timer that used to add text in the memo since the Timer has access to the form members,lol.
The old code:
```
//Memo.Text += txt + "\n";
```
I played with it today,this is what I've done
In Form1's class
```
public string TextValue
{
get
{
return Memo.Text;
}
set
{
this.Memo.Text += value + "\n";
}
}
```
I call the code like that:
```
Form1 myForm = new Form1();
myForm.TextValue = "test asdasd";
```
The memo modifiers are **private**,but that's not the problem.
The problem is that no text is displayed on the memo when i call the code. | By typing this:
```
Form1 myForm = new Form1();
```
you create a new instance of your form (Form1), but instead I guess you should use existing instance which most likely has been initialized already.
One of the ways to do it:
```
var form = Form.ActiveForm as Form1;
if (form != null)
{
form.TextValue = "test asdasd";
}
```
Though this is not very good design. Try to use custom [`events`](http://msdn.microsoft.com/en-us/library/aa645739.aspx) instead. | Maybe you should consider publishing an event in your tcpclient. Then your form will be able to listen to this event and display proper information. | Accessing form members from another class | [
"",
"c#",
"winforms",
"memo",
""
] |
I have a application/controller/login.php file containing the following
```
class Login extends Controller {
function Login()
{
parent::Controller();
}
function index()
{
$this->mysmarty->assign('title', 'Login');
$this->mysmarty->assign('site_media', $this->config->item('site_media'));
$this->mysmarty->display('smarty.tpl');
}
}
```
My routes definition looks like the following:
```
$route['default_controller'] = "welcome";
$route['login'] = 'login';
$route['scaffolding_trigger'] = "";
```
The problem is that I keep getting a 404 when I try to access <http://localhost/myapp/login>. What did I do wrong? I've checked CI routes docs and cannot spot anything. | There shouldn't be anything wrong with this - does it work without the route?
Also, have you set the .htaccess properly (i.e. does <http://localhost/myapp/index.php/login> work instead) | Another point to keep in mind, if you have have "enable\_query\_strings" set to true and aren't using the .htaccess mod\_rewrite rules:
In config/config.php:
```
$config['enable_query_strings'] = TRUE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
```
The URL to route your request properly would look like this:
```
http://localhost/myapp/index.php?c=login
``` | CodeIgniter routes: I keep getting a 404 | [
"",
"php",
"codeigniter",
""
] |
I am already using this [example of how to read large data files in PHP line by line](https://stackoverflow.com/questions/162176/reading-very-large-files-in-php/162263#162263)
Now, what it'd like to do, is obtain the total number of rows in the file so that I may display a percentage complete or at least what the total number of rows are so I can provide some idea of how much processing is left to be done.
Is there a way to get the total number of rows without reading in the entire file twice? (once to count the rows and once to do the processing) | Poor mans answer:
No, but you can estimate. Calc a simple average reading (use the first 250 lines) and go with that.
```
estNumOfLines = sizeOfFile / avgLineSize
```
You could store off the number of lines in the file when you are creating the file...
***Alternatively, you could display the number of KB processed, and that would be perfectly accurate.*** | You can determine the size of the file, then guage your progress through it by adding up the size of your reads:
```
$fname = 'foofile.txt';
$fsize = filesize($fname);
$count = 0;
$handle = fopen($fname, "r") or die("Couldn't get handle");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
// Process buffer here..
$count++;
echo ($count * 4096)/$fsize . " percent read.";
}
fclose($handle);
}
```
Note: code adapted from [referenced answer](https://stackoverflow.com/questions/162176/reading-very-large-files-in-php/162263#162263) | How to get the total number of rows before reading in a large file in PHP | [
"",
"php",
"file-io",
""
] |
In general, what is the maximum number of parameters a class constructor should accept? I'm developing a class that requires a lot of initialization data (currently 10 parameters). However, a constructor with 10 parameters doesn't feel right. That leads me to believe I should create a getter/setter for each piece of data. Unfortunately, the getter/setter pattern doesn't force the user to enter the data and without it characterization of the object is incomplete and therefore useless. Thoughts? | With that many parameters, it's time to consider the [Builder pattern](http://en.wikipedia.org/wiki/Builder_pattern). Create a builder class which contains all of those getters and setters, with a build() method that returns an object of the class that you're really trying to construct.
### Example:
```
public class ReallyComplicatedClass {
private int int1;
private int int2;
private String str1;
private String str2;
// ... and so on
// Note that the constructor is private
private ReallyComplicatedClass(Builder builder) {
// set all those variables from the builder
}
public static class Builder {
private int int1;
private int int2;
private String str1;
private String str2;
// and so on
public Builder(/* required parameters here */) {
// set required parameters
}
public Builder int1(int newInt) {
int1 = newInt;
return this;
}
// ... setters for all optional parameters, all returning 'this'
public ReallyComplicatedClass build() {
return new ReallyComplicatedClass(this);
}
}
}
```
And in your client code:
```
ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()
.int1(myInt1)
.str2(myStr2)
.build();
```
See pages 7-9 of [Effective Java Reloaded](http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-2689.pdf) [pdf], Josh Bloch's presentation at JavaOne 2007. (This is also item 2 in [Effective Java 2nd Edition](http://java.sun.com/docs/books/effective/), but I don't have it handy so I can't quote from it.) | You can decide when enough is enough and use [Introduce Parameter Object](http://www.refactoring.com/catalog/introduceParameterObject.html) for your constructor (or any other method for that matter). | Constructor Parameters - Rule of Thumb | [
"",
"java",
"design-patterns",
"refactoring",
""
] |
I want to hide my mouse cursor after an idle time and it will be showed up when I move the mouse. I tried to use a timer but it didn't work well. Can anybody help me? Please! | Here is a contrived example of how to do it. You probably had some missing logic that was overriding the cursor's visibility:
```
public partial class Form1 : Form
{
public TimeSpan TimeoutToHide { get; private set; }
public DateTime LastMouseMove { get; private set; }
public bool IsHidden { get; private set; }
public Form1()
{
InitializeComponent();
TimeoutToHide = TimeSpan.FromSeconds(5);
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
}
void Form1_MouseMove(object sender, MouseEventArgs e)
{
LastMouseMove = DateTime.Now;
if (IsHidden)
{
Cursor.Show();
IsHidden = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan elaped = DateTime.Now - LastMouseMove;
if (elaped >= TimeoutToHide && !IsHidden)
{
Cursor.Hide();
IsHidden = true;
}
}
}
``` | If you are using WinForms and will only deploy on Windows machines then it's quite easy to use [`user32 GetLastInputInfo`](http://msdn.microsoft.com/en-us/library/ms646302.aspx) to handle both mouse and keyboard idling.
```
public static class User32Interop
{
public static TimeSpan GetLastInput()
{
var plii = new LASTINPUTINFO();
plii.cbSize = (uint)Marshal.SizeOf(plii);
if (GetLastInputInfo(ref plii))
return TimeSpan.FromMilliseconds(Environment.TickCount - plii.dwTime);
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
}
```
And then in your `Form`
```
public partial class MyForm : Form
{
Timer activityTimer = new Timer();
TimeSpan activityThreshold = TimeSpan.FromMinutes(2);
bool cursorHidden = false;
public Form1()
{
InitializeComponent();
activityTimer.Tick += activityWorker_Tick;
activityTimer.Interval = 100;
activityTimer.Enabled = true;
}
void activityWorker_Tick(object sender, EventArgs e)
{
bool shouldHide = User32Interop.GetLastInput() > activityThreshold;
if (cursorHidden != shouldHide)
{
if (shouldHide)
Cursor.Hide();
else
Cursor.Show();
cursorHidden = shouldHide;
}
}
}
``` | Hide mouse cursor after an idle time | [
"",
"c#",
""
] |
I don't really understand how [cURL](http://en.wikipedia.org/wiki/CURL) works. Can it read the unparsed [PHP](http://en.wikipedia.org/wiki/PHP) code from a PHP file? If so, what is to stop some hacker from reading the script that connects to my database and stealing the login information? | No—PHP code is always parsed by the server whenever any kind of request is made. So if you use cURL to download a PHP file from the web, you will get its parsed HTML output. | No, it cannot. All cURL does is access an URL just like you would access it using a browser. If you can read the PHP source with a browser, so can cURL, if not, then not. | Can cURL be used to read PHP code from PHP files? | [
"",
"php",
"security",
"curl",
""
] |
I'm adding some code into a `using` block in a C# program. I'm sort of stuffing my app, which previously was a standalone into an existing body of code, so I need to do a bit of messing around to get it to fit properly. What it's ending up looking like is the following:
```
public class WrapperForMyOldApp
{
public static ItemThatINeed item1;
public static ItemThatINeed item2;
public WrapperForMyOldApp ()
{
item1 = new ItemThatINeed();
item2 = new ItemThatINeed();
}
public static go()
{
// some stuff that i need to do with items 1 and 2
}
}
public class MainProgram
{
.
.
.
public void MethodThatNeedsToMakeUseOfMyApp ()
{
....
using (WrapperForMyOldApp oldAPp = new WrapperForMyOldApp())
{
WrapperForMyOldApp.go();
}
}
}
```
Alright, so the question here is: Have I now crippled the effects of the using block and/or created any peculiar side effects that might adversely effect the class MainProgram? I believe that the Wrapper object and it's contents will be Disposed and execution will continue as expected but is there anything I need to be aware of that I'm overlooking?
thanks! | In order for this to work, you'll need to have WrapperForMyOldApp implement IDisposable.
The Dispose() call in WrapperForMyOldApp would then do your cleanup.
However, static objects are typically used for objects that have a lifetime beyond the single object. In general, for this type of usage, you'd make the ItemThatINeed instances non-static, generate them in your WrapperForMyOldApp constructor, then clean them up in WrapperForMyOldApp.Dispose().
With static objects, you're potentially creating a nightmare - you're constructing the object, and then saying you want to perform the cleanup (at the end of the using block), so you Dispose() method would be cleaning up the static objects. However, if they get used again, what should happen? What is the correct behavior if you create two WrapperForMyOldApp instances in 2 threads? I would consider these issues if you want deterministic cleanup. | Does your wrapper class implement IDisposable and you're just not showing it? If it's not disposable, then you don't need the using statement at all. | C# Using block usage with static objects | [
"",
"c#",
"using",
""
] |
### Exact Duplicate:
[combine paths in java](https://stackoverflow.com/questions/412380/)
I would like to know if there is such a method in Java. Take this snippet as example :
```
// this will output a/b
System.out.println(path_join("a","b"));
// a/b
System.out.println(path_join("a","/b");
``` | This concerns Java versions 7 and earlier.
To quote a [good answer to the same question](https://stackoverflow.com/questions/412380/combine-paths-in-java/412495#412495):
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
```
public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
``` | Try:
```
String path1 = "path1";
String path2 = "path2";
String joinedPath = new File(path1, path2).toString();
``` | Does Java have a path joining method? | [
"",
"java",
"file",
"file-io",
"path",
""
] |
c#: How do I accept any kind of number into a function as an argument?
Currently my AddDataInt32() asks specifically for Int32, but how I can accept any number, byte, ints signed or unsigned, so I can pass it on to BitConverter.GetBytes()? It's seems silly to write same funct's for each type :(
```
public void AddDataInt32(Int32 i)
{
Data = ConcatTwoByteArrays(Data, BitConverter.GetBytes(i));
}
``` | You can just overload the method...
```
public void AddData (Int32 i)
{...}
public void AddData (Int16 i)
{...}
```
etc. One for each number type. When you make the call to the procedure, it will take any form of number that you've coded, with the same procedure name. | Well, you could automate it with reflection and generics, but IMO overloads are the better choice - very much like your existing code.
Reflection / generics example - although I don't really recommend this route:
```
static void Main()
{
byte[] bytes = GetBytes(123);
}
static byte[] GetBytes<T>(T value) {
return Cache<T>.func(value);
}
static class Cache<T> {
public static readonly Func<T, byte[]> func;
static Cache() {
MethodInfo method = typeof(BitConverter)
.GetMethod("GetBytes", new Type[] { typeof(T) });
if (method == null) {
func = delegate { throw new ArgumentException(
"No GetBytes implementation for " + typeof(T).Name); };
} else {
func = (Func<T, byte[]>)Delegate.CreateDelegate(
typeof(Func<T, byte[]>), method);
}
}
}
```
You would then mix that with an `AddData<T>` generic method that calls `GetBytes<T>` etc. | How to accept any kind of number into a function as an argument in C#? | [
"",
"c#",
".net",
""
] |
Before I explain what I want to do, if you look at the following code, would you understand what it's supposed to do? *(updated - see below)*
```
Console.WriteLine(
Coalesce.UntilNull(getSomeFoo(), f => f.Value) ?? "default value");
```
C# already has a null-coalescing operator that works quite well on simple objects but doesn't help if you need to access a member of that object.
E.g.
```
Console.WriteLine(getSomeString()??"default");
```
works very well but it won't help you here:
```
public class Foo
{
public Foo(string value) { Value=value; }
public string Value { get; private set; }
}
// this will obviously fail if null was returned
Console.WriteLine(getSomeFoo().Value??"default");
// this was the intention
Foo foo=getSomeFoo();
Console.WriteLine(foo!=null?foo.Value:"default");
```
Since this is something that I come across quite often I thought about using an extension method *(old version)*:
```
public static class Extension
{
public static TResult Coalesce<T, TResult>(this T obj, Func<T, TResult> func, TResult defaultValue)
{
if (obj!=null) return func(obj);
else return defaultValue;
}
public static TResult Coalesce<T, TResult>(this T obj, Func<T, TResult> func, Func<TResult> defaultFunc)
{
if (obj!=null) return func(obj);
else return defaultFunc();
}
}
```
Which allows me to write:
```
Console.WriteLine(getSomeFoo().Coalesce(f => f.Value, "default value"));
```
So would you consider this code to be readable? Is Coalesce a good name?
Edit 1: removed the brackets as suggested by Marc
## Update
I really liked lassevk's suggestions and Groo's feedback. So I added overloads and didn't implement it as an extension method. I also decided that defaultValue was redundant because you could just use the existing ?? operator for that.
This is the revised class:
```
public static class Coalesce
{
public static TResult UntilNull<T, TResult>(T obj, Func<T, TResult> func) where TResult : class
{
if (obj!=null) return func(obj);
else return null;
}
public static TResult UntilNull<T1, T2, TResult>(T1 obj, Func<T1, T2> func1, Func<T2, TResult> func2) where TResult : class
{
if (obj!=null) return UntilNull(func1(obj), func2);
else return null;
}
public static TResult UntilNull<T1, T2, T3, TResult>(T1 obj, Func<T1, T2> func1, Func<T2, T3> func2, Func<T3, TResult> func3) where TResult : class
{
if (obj!=null) return UntilNull(func1(obj), func2, func3);
else return null;
}
public static TResult UntilNull<T1, T2, T3, T4, TResult>(T1 obj, Func<T1, T2> func1, Func<T2, T3> func2, Func<T3, T4> func3, Func<T4, TResult> func4) where TResult : class
{
if (obj!=null) return UntilNull(func1(obj), func2, func3, func4);
else return null;
}
}
```
Sample usage:
```
Console.WriteLine(
Coalesce.UntilNull(getSomeFoo(), f => f.Value) ?? "default value");
```
Another sample:
```
public class Bar
{
public Bar Child { get; set; }
public Foo Foo { get; set; }
}
Bar bar=new Bar { Child=new Bar { Foo=new Foo("value") } };
// prints "value":
Console.WriteLine(
Coalesce.UntilNull(bar, b => b.Child, b => b.Foo, f => f.Value) ?? "null");
// prints "null":
Console.WriteLine(
Coalesce.UntilNull(bar, b => b.Foo, f => f.Value) ?? "null");
``` | Six years later and [**Null-conditional operators**](https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#null-conditional-operators) are here:
> Sometimes code tends to drown a bit in null-checking. The
> null-conditional operator lets you access members and elements only
> when the receiver is not-null, providing a null result otherwise:
>
> ```
> int? length = customers?.Length; // null if customers is null Customer
> first = customers?[0]; // null if customers is null
> ```
>
> The null-conditional operator is conveniently used together with the
> null coalescing operator ??:
>
> ```
> int length = customers?.Length ?? 0; // 0 if customers is null
> ```
>
> The null-conditional operator exhibits short-circuiting behavior,
> where an immediately following chain of member accesses, element
> accesses and invocations will only be executed if the original
> receiver was not null:
>
> ```
> int? first = customers?[0].Orders.Count();
> ```
>
> This example is essentially equivalent to:
>
> ```
> int? first = (customers != null) ? customers[0].Orders.Count() : null;
> ```
>
> Except that customers is only evaluated once. None of the member
> accesses, element accesses and invocations immediately following the ?
> are executed unless customers has a non-null value.
>
> Of course null-conditional operators can themselves be chained, in
> case there is a need to check for null more than once in a chain:
>
> ```
> int? first = customers?[0].Orders?.Count();
> ```
>
> Note that an invocation (a parenthesized argument list) cannot
> immediately follow the ? operator – that would lead to too many
> syntactic ambiguities. Thus, the straightforward way of calling a
> delegate only if it’s there does not work. However, you can do it via
> the Invoke method on the delegate:
>
> ```
> if (predicate?.Invoke(e) ?? false) { … }
> ```
>
> We expect that a very common use of this pattern will be for
> triggering events:
>
> ```
> PropertyChanged?.Invoke(this, args);
> ```
>
> This is an easy and thread-safe way to check for null before you
> trigger an event. The reason it’s thread-safe is that the feature
> evaluates the left-hand side only once, and keeps it in a temporary
> variable. | Yes, I would understand it. Yes, coalesce is a good name. Yes, it would be better if C# had a null-safe dereferencing operator like Groovy and some other languages :)
**Update**
C# 6 has such an operator - the null conditional operator, `?.` For example:
```
var street = customer?.PrimaryAddress?.Street;
```
Use it in conjunction with the original null-coalescing operator if you still want a default. For example:
```
var street = customer?.PrimaryAddress?.Street ?? "(no address given)";
```
Or, based on the original code in the question:
```
Console.WriteLine(getSomeFoo()?.Value ?? "default");
```
Noting, of course, that providing a default this way works only if it's okay to use that default value even when the final property value is available but set to null for some reason.
The result of an expression `x?.y` is `null` if `x` evaluates to null; otherwise it's the result of `x.y`. Oh, and you can use it for conditional method invocation, too:
```
possiblyNull?.SomeMethod();
``` | Extending the C# Coalesce Operator | [
"",
"c#",
"extension-methods",
""
] |
How do I get the color of a pixel at X,Y using c#?
As for the result, I can convert the results to the color format I
need. I am sure there is an API call for this.
For any given X,Y on the monitor, I want to get the color of that
pixel. | To get a pixel color from the **Screen** here's code from [Pinvoke.net](http://www.pinvoke.net/default.aspx/gdi32/GetPixel.html):
```
using System;
using System.Drawing;
using System.Runtime.InteropServices;
sealed class Win32
{
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
static public System.Drawing.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromArgb((int)(pixel & 0x000000FF),
(int)(pixel & 0x0000FF00) >> 8,
(int)(pixel & 0x00FF0000) >> 16);
return color;
}
}
``` | There's [`Bitmap.GetPixel`](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx) for an image... is that what you're after? If not, could you say which x, y value you mean? On a control?
Note that if you *do* mean for an image, and you want to get *lots* of pixels, and you don't mind working with unsafe code, then [`Bitmap.LockBits`](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits.aspx) will be a lot faster than lots of calls to `GetPixel`. | How to get the colour of a pixel at X,Y using c#? | [
"",
"c#",
"api",
""
] |
I'm trying to start the session in a header page in my webiste. But it seems there might be some sort of bug because it fails with the following error:
```
Warning: session_start() [function.session-start]: open(\xampp\tmp\sess_a7430aab4dd08d5fc0d511f781f41fe5, O_RDWR) failed: No such file or directory (2) in D:\Development\PHP\tt\Include\header.php on line 3
```
I'm using the default settings for xampp, everything is straight out of the box. For some reason its failing to open the file. however when i go to the directory with the session files in it, the files are there, they are just empty. Is this a bug? or am I doing something wrong?
php version 5.2.8 | This means that you don't have the correct permissions to either read or write the files in the temp directory.
If you on linux then do this
```
sudo chmod -R 755 \xampp\tmp //or should it be 775
```
On windows do this as an administrator
```
attrib -r -a C:\xampp\tmp /S
``` | First stop the Xampp Server.
session.save\_path = "\xampp\tmp"
and change it to look like this
session.save\_path = "C:\xampp\tmp"
Restart the Xampp Server.
That’s it now your session should work as expected. | PHP session_start fails | [
"",
"php",
"session",
"xampp",
""
] |
In the database, I have a table called Contact. The first name and other such string fields are designed to use a Char datatype (not my database design). My object Contact maps to a string type in the properties. If I wanted to do a simple test retrieving a Contact object by id, I would do something like this:
```
Contact contact = db.Contacts.Single(c => c.Id == myId);
Contact test = new Contact();
test.FirstName = "Martin";
Assert.AreEqual(test.FirstName, contact.FirstName);
```
The contact.FirstName value is "Martin " because of the char type. Where can I intercept the FirstName property when it is being loaded? OnFirstNameChanging(string value) does not get called on the initial load (contact), but does on the test object. | Maybe you could put it in the OnLoaded() partial method? Note: I've never used this, but I assume it would look like this:
```
public partial class Contact
{
partial void OnLoaded()
{
FirstName = FirstName.Trim();
}
}
``` | If you can't change the schema, you might want to make the designer generated accessor private/protected and create a public accessor to front-end the property in a partial class implementation. You can then Trim the value in the get accessor.
```
public partial class Contact
{
public string RealFirstName
{
get { return this.FirstName.Trim(); }
set { this.FirstName = value; }
}
...
}
``` | How to trim values using Linq to Sql? | [
"",
"c#",
"linq-to-sql",
""
] |
I am using the getResponseBody() method of the org.apache.commons.httpclient.methods.PostMethod class. However, I am always getting a message written to the console at runtime:
*WARNING: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.*
In the code I have to write the response to a byte array anyway, so it is the getResponseBody() method that I ought to use. But is there an easy way that I can suppress the warning message so I don't have to look at it at every run?
If it was a compiler error, I'd use the *@SuppressWarnings* annotation, but this isn't a compile-time issue; it happens at runtime. Also, I could use getResponseBodyAsStream to write to a ByteArrayOutputStream, but this seems like a hacky way to get around the warning (extra lines of code to do what getResponseBody() is already doing for me).
My guess is that the answer involves System.out or System.err manipulation, but is there a good way to do this? | I would recommend that you do as the warning suggests and use a stream rather than a byte array. If the response you're trying to push is particularly large (suppose it's a large file), you will load it all into memory, and that'd be a very bad thing.
You're really better off using streams.
That said, you might hack around it by replacing System.err or System.out temporarily. They're just `PrintStream` objects, and they're settable with the setOut and setErr methods.
```
PrintStream oldErr = System.err;
PrintStream newErr = new PrintStream(new ByteArrayOutputStream());
System.setErr(newErr);
// do your work
System.setErr(oldErr);
```
**Edit:**
> *I agree that it would be preferable to
> use streams, but as it is now, the
> target API where I need to put the
> response is a byte array. If
> necessary, we can do a refactor to the
> API that will allow it to take a
> stream; that would be better. The
> warning is definitely there for a
> reason.*
If you can modify the API, do so. Stream processing is the best way to go in this case. If you can't due to internal pressures or whatever, go [@John M](https://stackoverflow.com/questions/745022/whats-the-best-way-to-suppress-a-runtime-console-warning-in-java/745054#745054)'s route and pump up the `BUFFER_WARN_TRIGGER_LIMIT` -- but make sure you have a known contentLength, or even that route will fail. | If you want to cleanly stop this log entry, there's a tunable max that triggers the warning. I saw this [looking at the code](http://google.com/codesearch/p?hl=en#uZxE5gtdHtc/java/src/org/apache/commons/httpclient/HttpMethodBase.java&q=getResponseBodyAsStream%20instead%20is%20recommended).
```
int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024);
if ((contentLength == -1) || (contentLength > limit)) {
LOG.warn("Going to buffer response body of large or unknown size. "
+"Using getResponseBodyAsStream instead is recommended.");
}
```
HttpMethodBase.setParams() looks like the place to set HttpMethodParams.BUFFER\_WARN\_TRIGGER\_LIMIT to the desired value. | What's the best way to suppress a runtime console warning in Java? | [
"",
"java",
"console",
"runtime",
"warnings",
"suppress-warnings",
""
] |
I'm debating whether to use Seam, Wicket, JSF or GWT as the foundation for my presentation layer in a Java project.
I narrowed my selection of Java web frameworks down to this subset based on job market considerations, newness of the technology and recommendations from other S.O. users.
What factors should I take into consideration in deciding among these? | The only one of those I've used is JSF, so I won't be able to give you feedback on the others, but here's my take on JSF. In my experience, the minute we converted from JSF in JSP to JSF in facelets, life got MUCH easier, so I'll focus around facelets. Also, It looks like Seam and JSF are not mutually exclusive.
Pros:
* Creating facelets xhtml components is simple, which promotes re-use.
* Decent templating abilities using built in tags like ui:insert, ui:include, and ui:decorate
* Simple access to Spring beans through faces-config
* XHTML based so web developers unfamiliar with java can still be effective
* Good widget library available in tomahawk/trinidad
Cons:
* Post requests only. This can make bookmarking difficult.
* Not as built-in ajax-y as GWT, but this may be fixed if used with Seam
I'm by no means an expert in JSF/Facelets, so I'm sure there are others I've missed. Hopefully someone else will also elaborate.
**Update for JSF 2.0:**
* Has even better re-use capabilities with composite components
* Widget libraries for 2.0 include primefaces and mojarra scales
* Allows get requests and bookmarking
* Has built in Ajax support
* See <http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/> for more on JSF 2 | I've used GWT since version 1.4 and JSF since the 2.0 spec came out.
GWT is a client-side framework, it generates JavaScript from Java. Your architecture would be a pure client-server, which means:
* Best to use coarse-grained services
* All objects that travel to the client side should be fully serializable (it means there's no lazy load, or OpenSessionInView pattern)
* Since GWT 2.0 you can design your gui using xhtml, which is much easier in regards to styling & structuring HTML
* GWT tends to favour good architecture, if you mess it up it will be *bad* to refactor
* *Perfect* History (browser back button, bookmarkable urls) support is **hard**, you probably have to roll your own, although it's easy to hack something right up front
JSF is a component-based framework, with a view-first design (code-behind if you like):
* It's easier to do some type of webapps (stateful, like shopping cart)
* JSF+Seam have suport for conversations (think wizard-like pages that maintain state across several pages)
* You *can* implement OpenSessionInView, depending on your stack. It's probably not recommended if you use EJB for service/business layer
* JSF2 has **superb** support for AJAX, and with a component suite like RichFaces you can build nice webapps
+ But if you want exquisite javascript behaviour, you'll have to write some javascript
* JSF tracks the current UI state in client or server-side. This is a tradeoff between network traffic or server memory.
Resume:
* **GWT** is more adequate for web **applications** (think gmail) that require the best client-side performance. It's easy to write custom components (you write Java) and since your server-side is just a service layer you can be fully stateless on the server side.
* **JSF** is more adequate for mostly CRUD applications that are better suited for component-oriented stuff: think a hotel/flight reservation system, an online store with a shopping cart, etc | Which framework should I choose - Seam, Wicket, JSF or GWT? | [
"",
"java",
"jsf",
"seam",
"wicket",
"web-frameworks",
""
] |
I'm looking for the best (possible on most PHP 5.2 installs and still actively developed) way to detect a files MIME type in PHP.
I'm aware of the `mime_content_type()` method and the Fileinfo extension, however `mime_content_type()` is unreliable and deprecated, and Fileinfo doesn't come in a "standard" PHP (5.2) install.
Do I have any other options? | Have you looked into this PEAR package?
<http://pear.php.net/package/MIME_Type> | (lol sorry I realized this was asked months ago as I was finishing up. oh well. might as well add this...)
If it's a \*nix server you could use *file* command.
```
file -bi <filepath>
```
You'd have to use "exec" in PHP to do that I guess? I'm new to PHP so don't quote me on this but...
```
$content_type = exec("file -bi " . escapeshellarg($filepath));
```
I didn't test it so you might need to escape the path string and format the output.
Dunno if this will be more reliable than the other methods. | Detecting MIME type in PHP | [
"",
"php",
"mime-types",
"mime",
""
] |
I am using offset() with the jquery slider and I am so close to achieving my goal, but it is off slighty. I have it animating using animate to the top CSS coordinates but if you check out: <http://www.ryancoughlin.com/demos/interactive-slider/index.html> - you will see what it is doing. My goal is to have it fadeIn() and display the value to the right of the handle. i know I can offset the text from the handle using a simple margin:0 0 0 20px.
The part is aligning #current\_value to the right of the handle. Thoughts?
var slide\_int = null;
```
$(function(){
$("h4.code").click(function () {
$("div#info").toggle("slow");
});
$('#slider').slider({
animate: true,
step: 1,
min: 1,
orientation: 'vertical',
max: 10,
start: function(event, ui){
$('#current_value').empty();
slide_int = setInterval(update_slider, 10);
},
slide: function(event, ui){
setTimeout(update_slider, 10);
},
stop: function(event, ui){
clearInterval(slide_int);
slide_int = null;
}
});
});
function update_slider(){
var offset = $('.ui-slider-handle').offset();
var value = $('#slider').slider('option', 'value');
$('#current_value').text('Value is '+value).css({top:offset.top });
$('#current_value').fadeIn();
}
```
I know I could use margin to offset it to match, but is there a better way? | There are two problems. The first, like Prestaul said, the slider event fires at the "beginning" of the move, not the end, so the offset is wrong. You could fix this by setting a timeout:
```
$(function(){
slide: function(event, ui){
setTimeout(update_slider, 10);
},
...
});
function update_slider()
{
var offset = $('.ui-slider-handle').offset();
var value = $('#slider').slider('option', 'value');
$('#current_value').text('Value is '+value).animate({top:offset.top }, 1000 )
$('#current_value').fadeIn();
}
```
The second problem is that the move is instantaneous, while the animation is not, meaning that the label will lag behind the slider. The best I've come up with is this:
```
var slide_int = null;
$(function(){
...
start: function(event, ui){
$('#current_value').empty();
// update the slider every 10ms
slide_int = setInterval(update_slider, 10);
},
stop: function(event, ui){
// remove the interval
clearInterval(slide_int);
slide_int = null;
},
...
});
function update_slider()
{
var offset = $('.ui-slider-handle').offset();
var value = $('#slider').slider('option', 'value');
$('#current_value').text('Value is '+value).css({top:offset.top });
$('#current_value').fadeIn();
}
```
By using `css` instead of `animate`, you keep it always next to the slider, in exchange for smooth transitions. Hope this helps! | I had the same problem: the visible value in Jquery Ui slider lags behind from internal value. Fixed the problem by changing the slider event from "slide" to "change". | Using offset and jQuery slider | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I'd like to learn LAMP development for my own personal edification.
I tried setting up Ubuntu 8.10 "Hardy Heron" in Microsoft VPC, but I can't get the video to work above 800x600. Played with xorg.conf a million times but no joy. Can anyone recommend a good distro to work with that plays well with VPC? Any guidance on getting started with Apache and Perl/PHP would also be welcome. | I installed ubuntu 8.10 in a virtual machine on my Vista 64-bit laptop. I attempted the install with Virtual PC, VM Ware and Virtual Box from SUN. Virtual Box was the only vm software that I was successful with from the start. In the setup you choose that you are installing linux as your guest OS and everything works without spending your evening sifting through blogs trying to get install to work. | Firstly, if your goal is to learn LAMP development, I'd start by just downloading the WAMP stack for windows from <http://www.wampserver.com/en/> or one of it's competitors. The "Linux" part of LAMP programming isn't likely to be a major part of your learning experience. Avoiding running a VM will be much less resource intense on your development workstation and avoid having issues with suspend/resume and disk IO contention.
Secondly, any linux should work, under virtualbox or msvpc. All the modern desktop virtualization systems emulate a full system, so it's just a matter of configuration and getting the right drivers. Like others said, virtualbox is more open source friendly so give that a shot.
Finally, I don't usually run X on my development VM's, since it just eats unnecessary resources. Just use putty on the host and ssh in to a VM running in console mode.
Not entirely the answer to your question, but I think it attacks your goal more directly. | Which Linux distro is best for running in a virtual machine, for programming research? | [
"",
"php",
"linux",
"apache",
"virtualization",
""
] |
## Observations:
Java has a logical AND operator.
Java has a logical OR operator.
Java has a logical NOT operator.
## Problem:
Java has no logical XOR operator, [according to sun](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html). I would like to define one.
## Method Definition:
As a method it is simply defined as follows:
```
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
```
## Method Call:
This method is called in the following way:
```
boolean myVal = logicalXOR(x, y);
```
## Operator Usage:
I would much rather have an operator, used as follows:
```
boolean myVal = x ^^ y;
```
## Question:
I can't find anything on how to go about defining a new operator in Java. Where should I start? | Java **does have a logical XOR operator**, it is [^](https://stackoverflow.com/questions/460542/-operator-in-java) (as in `a ^ b`).
Apart from that, you can't define new operators in Java.
**Edit:** Here's an example:
```
public static void main(String[] args) {
boolean[] all = { false, true };
for (boolean a : all) {
for (boolean b: all) {
boolean c = a ^ b;
System.out.println(a + " ^ " + b + " = " + c);
}
}
}
```
Output:
```
false ^ false = false
false ^ true = true
true ^ false = true
true ^ true = false
``` | Isn't it x != y ? | Creating a "logical exclusive or" operator in Java | [
"",
"java",
"operators",
"xor",
""
] |
I'm looking at using a singleton in a multithreaded Win service for doing logging, and wanted to know what are some of the problems I might encounter. I have already set up the get instance to handle syncing with
```
private static volatile Logging _instance;
private static object _syncRoot = new object();
private Logging(){}
public static Logging Instance
{
get
{
if (_instance==null)
{
lock(_syncRoot)
{
if (_instance == null)
{
_instance = new Logging();
}
}
}
return _instance;
}
}
```
Is there anything else I might need to worry about? | That looks pretty good to me.
See [Implementing the Singleton Pattern in C#](http://csharpindepth.com/Articles/General/Singleton.aspx) for more info.
Edit: Should probably put the return inside the lock, though. | This is more informational than anything else.
What you've posted is the *double-checked locking algorithm* - and what you've posted *will* work, as far as I'm aware. (As of Java 1.5 it works there, too.) However, it's very fragile - if you get any bit of it wrong, you could introduce very subtle race conditions.
I usually prefer to initialize the singleton in the static initializer:
```
public class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance
{
get { return instance; }
}
private Singleton()
{
// Do stuff
}
}
```
(Add a static constructor if you want a bit of extra laziness.)
That pattern's easier to get right, and in most cases it does just as well.
There's more detail on my [C# singleton implementation page](http://csharpindepth.com/Articles/General/Singleton.aspx) (also linked by Michael).
As for the dangers - I'd say the biggest problem is that you lose testability. Probably not *too* bad for logging. | What are the Dangers of using a Singleton in a multithreaded application | [
"",
"c#",
".net",
"multithreading",
"singleton",
""
] |
Is it possible to load a picture from memory (`byte[]` or `stream` or `Bitmap`) without saving it to disk?
This is the code I use to turn the `byte[]` array into a `Bitmap`:
```
unsafe
{
fixed (byte* ptr = Misc.ConvertFromUInt32Array(image))
{
Bitmap bmp = new Bitmap(200, 64, 800, PixelFormat.Format32bppRgb, new IntPtr(ptr));
bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
bmp.MakeTransparent(Color.Black);
bmp.Save("test.bmp");
}
}
```
Instead of using `Bmp.save()`, can I put the `Bitmap` in the picture box on my form? | Have you tried this?
```
pictureBox.Image = bmp;
``` | I had some code resembling the accepted answer that caused a memory leak. Problem is that when you set the picture box image to the bitmap, you're still referring to the bitmap, rather than creating a copy. If you need to set the image multiple times you need to make sure you're disposing all the old bitmaps.
This is for anyone who's looking to *clone* a bitmap to an image box. Try this:
```
if (pictureBox.Image != null) pictureBox.Image.Dispose();
pictureBox.Image = myBitmap.Clone(
new Rectangle(0, 0, myBitmap.Width, myBitmap.Height),
System.Drawing.Imaging.PixelFormat.DontCare);
``` | How to put image in a picture box from Bitmap | [
"",
"c#",
"bitmap",
"image",
""
] |
I've written this function before but I can't seem to remember it and it didn't get into version control. Now, more to do with sleep deprivation than anything else, I can't remember how to rebuild it.
Here's the idea. I have two tables, "regPrice" and "custPrice", with shared key "itemID." They both have a "price" column and custPrice also has another key "acct" such that if a price exists in custPrice, it should return that one. If there isn't a custPrice entry, it should return the regPrice.
pseudoCode:
```
if(select custPrice where acct = passedAcct and itemID = passedItemID) {
return custPrice;
else
return regPrice;
```
Any help would be appreciated. | ```
SELECT COALESCE(c.price, r.price) AS price
FROM regPrice r LEFT OUTER JOIN custPrice c
ON (r.itemID = c.itemID AND c.acct = ?)
WHERE r.itemID = ?;
``` | ```
select r.itemID, r.Acct,
case when c.price is null then r.price else c.price end as price
from regPrice r
left outer join custPrice c
on r.itemID = c.itemID
and r.Acct = @passedAcct
where r.itemID = @passedItemID
``` | SQL Outer Join Function | [
"",
"sql",
"mysql",
"stored-procedures",
"join",
""
] |
Is there any way to set a foreign key in django to a *field* of another model?
For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)
Is there a way to store this field-level mapping in django? | I haven't tried this, but it seems that since Django 1.0 you can do something like:
```
class Foo(models.Model):
foo = models.ForeignKey(Bar, to_field='bar')
```
Documentation for this is [here](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field). | Yes and no. The FK relationship is described at the class level, and mirrors the FK association in the database, so you can't add extra information directly in the FK parameter.
Instead, I'd recommend having a string that holds the field name on the other table:
```
class ValidationRule(models.Model):
other = models.ForeignKey(OtherModel)
other_field = models.CharField(max_length=256)
```
This way, you can obtain the field with:
```
v = ValidationRule.objects.get(id=1)
field = getattr(v, v.other_field)
```
Note that if you're using Many-to-Many fields (rather than a One-to-Many), there's built-in support for creating custom intermediary tables to hold meta data with the [through](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through) option. | Django Model set foreign key to a field of another Model | [
"",
"python",
"python-3.x",
"django",
"django-models",
"foreign-keys",
""
] |
Is there a way to associate a string from a text file with an enum value?
The problem is: I have a few enum values stored as string in a text file which I read on the fly on meeting some condition... Now I want to assign the read value to an enum.
What is the most effective way to do so? It doesn't need to be the simplest approach. | You can set up a map that you can use over and over:
```
template <typename T>
class EnumParser
{
map <string, T> enumMap;
public:
EnumParser(){};
T ParseSomeEnum(const string &value)
{
map <string, T>::const_iterator iValue = enumMap.find(value);
if (iValue == enumMap.end())
throw runtime_error("");
return iValue->second;
}
};
enum SomeEnum
{
Value1,
Value2
};
EnumParser<SomeEnum>::EnumParser()
{
enumMap["Value1"] = Value1;
enumMap["Value2"] = Value2;
}
enum OtherEnum
{
Value3,
Value4
};
EnumParser<OtherEnum>::EnumParser()
{
enumMap["Value3"] = Value3;
enumMap["Value4"] = Value4;
}
int main()
{
EnumParser<SomeEnum> parser;
cout << parser.ParseSomeEnum("Value2");
}
``` | ```
std::map< string, enumType> enumResolver;
``` | String to enum in C++ | [
"",
"c++",
"string",
"enums",
""
] |
I'm still confused... When we write some thing like this:
```
Object o = new Object();
var resource = new Dictionary<int , SomeclassReference>();
```
...and have two blocks of code that lock `o` while accessing `resource`...
```
//Code one
lock(o)
{
// read from resource
}
//Code two
lock(o)
{
// write to resource
}
```
Now, if i have two threads, with one thread executing code which reads from `resource` and another writing to it, i would want to lock `resource` such that when it is being read, the writer would have to wait (and vice versa - if it is being written to, readers would have to wait). Will the lock construct help me? ...or should i use something else?
(I'm using `Dictionary` for the purposes of this example, but could be anything)
There are two cases I'm specifically concerned about:
1. two threads trying to execute same line of code
2. two threads trying to work on the same resource
Will `lock` help in both conditions? | Most of the other answers address your code example, so I'll try to answer you question in the title.
A lock is really just a token. Whoever has the token may take the stage so to speak. Thus the object you're locking on doesn't have an explicit connection to the resource you're trying to synchronize around. As long as all readers/writers agree on the same token it can be anything.
When trying to lock on an object (i.e. by calling `Monitor.Enter` on an object) the runtime checks if the lock is already held by a thread. If this is the case the thread trying to lock is suspended, otherwise it acquires the lock and proceeds to execute.
When a thread holding a lock exits the lock scope (i.e. calls `Monitor.Exit`), the lock is released and any waiting threads may now acquire the lock.
Finally a couple of things to keep in mind regarding locks:
* Lock as long as you need to, but no longer.
* If you use `Monitor.Enter/Exit` instead of the `lock` keyword, be sure to place the call to `Exit` in a `finally` block so the lock is released even in the case of an exception.
* Exposing the object to lock on makes it harder to get an overview of who is locking and when. Ideally synchronized operations should be encapsulated. | Yes, using a lock is the right way to go. You can lock on any object, but as mentioned in other answers, locking on your resource itself is probably the easiest and safest.
However, you may want use a read/write lock pair instead of just a single lock, to decrease concurrency overhead.
The rationale for that is that if you have only one thread writing, but several threads reading, you do not want a read operation to block an other read operation, but only a read block a write or vice-versa.
Now, I am more a java guy, so you will have to change the syntax and dig up some doc to apply that in C#, but [rw-locks](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html) are part of the standard concurrency package in Java, so you could write something like:
```
public class ThreadSafeResource<T> implements Resource<T> {
private final Lock rlock;
private final Lock wlock;
private final Resource res;
public ThreadSafeResource(Resource<T> res) {
this.res = res;
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
this.rlock = rwl.readLock();
this.wlock = rwl.writeLock();
}
public T read() {
rlock.lock();
try { return res.read(); }
finally { rlock.unlock(); }
}
public T write(T t) {
wlock.lock();
try { return res.write(t); }
finally { wlock.unlock(); }
}
}
```
If someone can come up with a C# code sample... | Does lock(){} lock a resource, or does it lock a piece of code? | [
"",
"c#",
"multithreading",
"concurrency",
""
] |
I'm trying to find a simple Java API for creating graph relationships. It should have some functionality like `addEdge()`, `addNode()`, `isConnected(node1, node2)`, `findPaths(node1, node2)`, etc. I need no UI, just logic.
I found a bunch of academic projects, but none seems to be "*The Definitive Graph API*".
Does anyone know about such an API? | [JGraphT](http://jgrapht.org) sounds like what you're after.
> JGraphT is a free Java graph library that provides mathematical graph-theory objects and algorithms. JGraphT supports various types of graphs.
Their API can create graphs from various input and also supports creating graphs using `addVertex`, `addEdge`. They support finding shortest paths using various well know algorithms such as Bellman-Ford and Dijkstra They also have a complete [javadoc available online](http://www.jgrapht.org/javadoc/). | [JDLS](http://www.jdsl.org/) is a great library for Graphs and Datastructures in general. You could also use the [Grappa](http://www.research.att.com/~john/Grappa/) library. Its advantage is that it can use the [graphViz](http://www.graphviz.org/) libraries for graph layouting. | Looking for a simple Java API for creating graphs (edges + nodes) | [
"",
"java",
"api",
"graph-theory",
""
] |
I know I can start a new worker thread from with .NET. But how do I start a new UI thread (like in MFC)?
I don't mind if the solution is restricted to Windows boxes only; I also would like the solution to be purely .NET - no p/invokes to CreateThread, etc.
Any input appreciated. | Use [`Application.Run`](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx) - it starts a message loop in the current thread. There are overloads to take a form to start with, or an application context, or neither. (If you want to do this for a *new* thread, you need to create the thread and start it in the normal way, and make it call `Application.Run`.) | If you are interested in using WPF, check out MSDN's article [WPF's Threading Model](http://msdn.microsoft.com/en-us/library/ms741870.aspx), in particular the "Multiple Windows, Multiple Threads" section. It details what you need to do to create a new Dispatcher and show a window on a new thread. | How to start a UI thread in C# | [
"",
"c#",
".net",
"multithreading",
"user-interface",
""
] |
I'm wondering if there is a tried/true method for reporting the progress of a DB call from a .Net application to its user. I'm wondering if it's even possible to actually indicate a percentage of completion, or is the best/only approach to simply display a "loading" animation to indicate that something is happening?
Also, does SQL2008 address this to anyone's knowledge? | You have to load things deterministically. For example if you *know* that you'll be fetching a lot of data, for example, you might do something like:
-get a count of all of the records
-get 500 of them
-report status as 500/total %
-get 500 more
-report status as 1000/total %
-... continue until you've gotten them all of the user has canceled
This would be incredibly wasteful on something that takes no time at all, since the mere fact of going to the database is a large part of the overhead. | As far as I know there is no way to do this. My suggestion is use one of the circular progress bars that just spins forever. Microsoft uses these in database operations in SQL and Project.
Here is an article on CodeProject that has a variety of these:
<http://www.codeproject.com/KB/vb/sql2005circularprogress.aspx?fid=324397&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2205952>
Adam Berent | Progress Bar for calls to SQL from .Net | [
"",
"asp.net",
"sql",
"progress-bar",
""
] |
I recently started maintaining a .Net 1.1 project and would like to
convert it to .Net 3.5.
Any tips to share on reducing code by making use of new features?
As a first attempt, I would like to convert a bunch of static helper functions.
**Update**: The main reason why I am converting is to learn new features like static classes, LINQ etc. Just for my own use at least for now. | You can use [static classes](http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx) (C# 2.0 feature) to rewrite old helper functions. | I would suggest starting by migrating to .NET 2.0 features, first.
My first step would be to slowly refactor to move all the collections to generic collections. This will help tremendously, and ease the migration into the .NET 3.5 features, especially with LINQ. It should also have a nice impact on your performance, since any collections of value types will perform better.
Be wary in this of converting HashTables to Dictionary<T,U>, since the behavior is different in some cases, but otherwise, ArrayList->List<T>, etc are easy, useful conversions.
After that, moving helpers to static classes, and potentially extension methods, would be a good next step to consider. This can make the code more readable. | Conversion to .Net 3.5 | [
"",
"c#",
".net",
""
] |
I'm trying to create a view in an Oracle database, but keep getting an ORA-00907 error (missing right parenthesis). My SQL is as below:
```
CREATE VIEW my_view AS
(
SELECT metadata.ID,metadata.Field1,metadata.Field2,metadata.Field3,metadata.Field4,attribute1.StrValue AS Attr1, attribute2.StrValue AS Attr2
FROM metadata,data AS attribute1,data AS attribute2
WHERE
(
metadata.Type = 'TYPE1'
)
AND
(
metadata.ID = attribute1.ID AND attribute1.name = 'attr1'
)
AND
(
metadata.ID = attribute2.ID AND attribute2.name = 'attr2'
)
)
```
Where the table metadata defines entities, and data defines attributes for those entities.
This works fine in MS SQL and MySQL, but I keep getting the above error from Oracle.
Not been working with Oracle too long, so I don't know a whole lot about its quirks. | You need to remove the AS in the FROM clause. Oracle allows the optional AS for aliasing column names but not for providing aliases
```
SQL> ed
Wrote file afiedt.buf
1 CREATE VIEW my_view AS
2 (
3 SELECT metadata.ID,metadata.Field1,metadata.Field2,metadata.Field3,metadata
.Field4,attribute1.StrValue AS Attr1, attribute2.StrValue AS Attr2
4 FROM metadata,data attribute1,data attribute2
5 WHERE
6 (
7 metadata.Type = 'TYPE1'
8 )
9 AND
10 (
11 metadata.ID = attribute1.ID AND attribute1.name = 'attr1'
12 )
13 AND
14 (
15 metadata.ID = attribute2.ID AND attribute2.name = 'attr2'
16 )
17* )
SQL> /
View created.
```
Depending on the tool you're using, it may be useful to know that SQL\*Plus will show you exactly where a syntax error is occurring-- the snippet below shows it objecting to the AS keyword.
```
SQL> ed
Wrote file afiedt.buf
1 CREATE VIEW my_view AS
2 (
3 SELECT metadata.ID,metadata.Field1,metadata.Field2,metadata.Field3,metadata
.Field4,attribute1.StrValue AS Attr1, attribute2.StrValue AS Attr2
4 FROM metadata,data AS attribute1,data AS attribute2
5 WHERE
6 (
7 metadata.Type = 'TYPE1'
8 )
9 AND
10 (
11 metadata.ID = attribute1.ID AND attribute1.name = 'attr1'
12 )
13 AND
14 (
15 metadata.ID = attribute2.ID AND attribute2.name = 'attr2'
16 )
17* )
SQL> /
FROM metadata,data AS attribute1,data AS attribute2
*
ERROR at line 4:
ORA-00907: missing right parenthesis
``` | ```
CREATE VIEW my_view AS
(
SELECT metadata.ID,metadata.Field1,metadata.Field2,
metadata.Field3,metadata.Field4,
attribute1.StrValue AS Attr1, attribute2.StrValue AS Attr2
FROM metadata, data /* No AS here */ attribute1,
data /* No AS here */ attribute2
WHERE
(
metadata.Type = 'TYPE1'
)
AND
(
metadata.ID = attribute1.ID AND attribute1.name = 'attr1'
)
AND
(
metadata.ID = attribute2.ID AND attribute2.name = 'attr2'
)
)
```
I removed `AS` between `data` and `attribute1` | Oracle Throwing SQL Error when creating a View | [
"",
"sql",
"oracle",
"ora-00907",
""
] |
I have a set of RTF's stored in strings in C# is their a way to merge these into one document for printing as the user wants to print them as one document with the print settings appearing once. I can use office interop if necessary, obviously avoiding this is better.
Edit: A page break would be necessary between each document I think I can just insert \page for this though | [Here](http://anhl3.blogspot.com/2011/02/trick-of-processing-rtf-files.html) you go (C# code's included in) | You would have to remove the trailing } from the first document.
You would have to remove the {\rtf1... and {fonttbl.. and {colortbl... sections from the second document. Might need to look at any header, margins etc. that you might have.
Separate them by a \page as you say.
This assumes the font and color tables are the same.
Probably better to get the print settings from the user then silently print each document separately, if that's an option.
Document 1:
```
{\rtf1\ansi\ansicpg1252\deff0\deflang5129
{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}}
{\colortbl;\red0\green0\blue0;}
\margl1134\margr1134\margt1134\margb1134\sectd
\pard
Document One Content
\line
}
```
Document 2:
```
{\rtf1\ansi\ansicpg1252\deff0\deflang5129
{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}}
{\colortbl;\red0\green0\blue0;}
\margl1134\margr1134\margt1134\margb1134\sectd
\pard
Document Two Content
\line
}
```
Merged Documents:
```
{\rtf1\ansi\ansicpg1252\deff0\deflang5129
{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}}
{\colortbl;\red0\green0\blue0;}
\margl1134\margr1134\margt1134\margb1134\sectd
\pard
Document One Content
\page
\pard
Document Two Content
\line
}
``` | Merge RTF files | [
"",
"c#",
"rtf",
""
] |
Say I have the string "User Name:firstname.surname" contained in a larger string how can I use a regular expression to just get the firstname.surname part?
Every method i have tried returns the string "User Name:firstname.surname" then I have to do a string replace on "User Name:" to an empty string.
Could back references be of use here?
Edit:
The longer string could contain "Account Name: firstname.surname" hence why I want to match the "User Name:" part of the string aswell to just get that value. | I like to use named groups:
```
Match m = Regex.Match("User Name:first.sur", @"User Name:(?<name>\w+\.\w+)");
if(m.Success)
{
string name = m.Groups["name"].Value;
}
```
Putting the `?<something>` at the beginning of a group in parentheses (e.g. `(?<something>...)`) allows you to get the value from the match using `something` as a key (e.g. from `m.Groups["something"].Value`)
If you didn't want to go to the trouble of naming your groups, you could say
```
Match m = Regex.Match("User Name:first.sur", @"User Name:(\w+\.\w+)");
if(m.Success)
{
string name = m.Groups[1].Value;
}
```
and just get the first thing that matches. (Note that the first parenthesized group is at index `1`; the whole expression that matches is at index `0`) | You could also try the concept of "lookaround". This is a kind of zero-width assertion, meaning it will match characters but it won't capture them in the result.
In your case, we could take a positive lookbehind: we want what's behind the target string "firstname.surname" to be equal to "User Name:".
Positive lookbehind operator: (?<=StringBehind)StringWeWant
This can be achieved like this, for instance (a little Java example, using string replace):
```
String test = "Account Name: firstname.surname; User Name:firstname.surname";
String regex = "(?<=User Name:)firstname.surname";
String replacement = "James.Bond";
System.out.println(test.replaceAll(regex, replacement));
```
This replaces only the "firstname.surname" strings that are preceeded by "User Name:" without replacing the "User Name:" itself - which is not returned by the regex, only matched.
OUTPUT: Account Name: firstname.surname; User Name:James.Bond
***That is, if the language you're using supports this kind of operations*** | Returning only part of match from Regular Expression | [
"",
"c#",
"regex",
""
] |
I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?
Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/> | Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They have a Python wrapper but it looks pretty crappy and unsupported. Still open to other suggestions. | I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).
Instead, please use [imageio](http://imageio.github.io), which was developed to solve this problem and more, and is intended to stay.
Quick and dirty solution:
```
import imageio
images = []
for filename in filenames:
images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)
```
For longer movies, use the streaming approach:
```
import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
``` | Programmatically generate video or animated GIF in Python? | [
"",
"python",
"video",
"wxpython",
"animated-gif",
""
] |
I need a min-heap implemented as a binary tree. Really fast access to the minimum node and insertion sort.
Is there a good implementation in stl or boost that anyone can point me too? | I think [std::priority\_queue](http://en.cppreference.com/w/cpp/container/priority_queue) is what you are looking for. | See the Standard C++ algorithm [make\_heap](http://www.sgi.com/tech/stl/make_heap.html)(). | C++ Implementation of a Binary Heap | [
"",
"c++",
"data-structures",
"heap",
"binary-tree",
""
] |
I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.
I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.
Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?
Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.
Any help is very appreciated.
Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.
Add: This is what I've put together so far. <http://animania1.ca/ShowFriends/dev/dirmove.rar> would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?) | Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:
```
import pygame
quit = False
pygame.init()
display = pygame.display.set_mode((640,480))
sprite_sheet = pygame.image.load('sprite.bmp').convert()
# by default, display the first sprite
image_number = 0
while quit == False:
event = pygame.event.poll()
no_more_events = True if event == pygame.NOEVENT else False
# handle events (update game state)
while no_more_events == False:
if event.type == pygame.QUIT:
quit = True
break
elif event.type == pygame.NOEVENT:
no_more_events = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
image_number = 0
elif event.key == pygame.K_RIGHT:
image_number = 1
event = pygame.event.poll()
if quit == False:
# redraw the screen
display.fill(pygame.Color('white'))
area = pygame.Rect(image_number * 100, 0, 100, 150)
display.blit(sprite_sheet, (0,0), area)
pygame.display.flip()
```
I've never really used Pygame before so maybe this code shoudln't really be taken as an example. I hope it shows the basics though.
To be more complete I should wait some time before updating, e.g. control that I update only 60 times per second.
It would also be handy to write a sprite class which would simplify your work. You would pass the size of a sprite frame in the constructor, and you'd have methodes like `update()` and `draw()` which would automatically do the work of selecting the next frame, blitting the sprite and so on.
Pygame seems to provide a base class for that purpose: [link text](http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite). | dude the only thing you have to do is offcourse
import pygame and all the other stuff needed
type code and stuff..........then
when it comes to you making a spri
```
class .your class nam here. (pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.init(self)
self.image=pygame.image.load(your image and path)
self.rect=self.image.get_rect()
x=0
y=0
# any thing else is what you want like posistion and other variables
def update(self):
self.rect.move_ip((x,y))
```
and thats it!!!! but thats not the end. if you do this you will ony have made the sprite
to move it you need | Pygame: Sprite changing due to direction of movement | [
"",
"python",
"2d",
"pygame",
"sprite",
""
] |
I have a web application deployed in production which references an external web service.
Looking at the source code in Visual Studio, I see that the web referebce was statically linked. In the proxy reference.cs, it is hardcode to the url.
this.Url = "<http://server/WebService/Service.asmx>";
I can change the url. But, I would like the proxy to pick up the url from web.config file. How do I enhance proxy code without using Visual Studio to set url behavior to dynamic? would love to get some code samples in C#. | You can use the same code generated by Visual Studio when you change the behavior to dynamic:
```
public Service1() {
string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["WebApplication1.localhost.Service1"];
if ((urlSetting != null)) {
this.Url = string.Concat(urlSetting, "");
}
else {
this.Url = "http://localhost/WebService1/Service1.asmx";
}
}
``` | In your properties folder of the project with `Settings.settings` add a web service URL setting to one of the properties.
Then modify `this.Url = Properties.Settings.YourWebServiceUrlName`.
This will create a configuration in your web.config that you can change on a per server basis. I usually set the property settings to my production server settings and then modify the web.config for my local dev environment. | Need help on setting web service proxy dynamically without build? | [
"",
"c#",
"visual-studio",
"web-services",
""
] |
Should the following code give a warning?
```
class Foo { public void Do() { /*...*/ } /*...*/ }
class Bar : Foo { public static void Do() { /*...*/ } /*...*/ }
```
It gives:
> "Warning CS0108: 'Bar.Do()' hides inherited member 'Foo.Do()'. Use the new keyword if hiding was intended."
If I make a change to the code:
```
class Foo { public static void Do() { /*...*/ } /*...*/ }
class Bar : Foo { public void Do() { /*...*/ } /*...*/ }
```
I get the same warning.
If I make the following change, however, the warning goes away.
```
class Foo { public void Do() { /*...*/ } /*...*/ }
class Bar : Foo { new public static void Do() { /*...*/ } /*...*/ }
```
Let me make a further change:
```
class Foo { public void Do() { /*...*/ } /*...*/ }
class Bar : Foo {
new public static void Do()
{ new Bar().Do();/*...*/ } /*...*/
}
```
This does not compile:
> "Error CS0176: Member 'Bar.Do()' cannot be accessed with an instance reference; qualify it with a type name instead."
So, I lose access to my inherited method via an instance reference from a static method!
What would be the logic behind it? Or did I make a typo somewhere?
I came across this when I was trying to define a static method 'Show' for my form derived from 'Form'. | Where do you think the bug is? The fact that there is a warning is absolutely right. From the C# 3.0 spec, section 10.3.4:
> A class-member-declaration is
> permitted to declare a member with the
> same name or signature as an inherited
> member. When this occurs, the derived
> class member is said to hide the base
> class member. Hiding an inherited
> member is not considered an error, but
> it does cause the compiler to issue a
> warning. To suppress the warning, the
> declaration of the derived class
> member can include a new modifier to
> indicate that the derived member is
> intended to hide the base member.
The fact that your method invocation fails is subtler, but it's basically because the member lookup algorithm picks the static method, and then this part of section 7.5.5.1 is used:
> Final validation of the chosen best
> method is performed:
>
> The method is
> validated in the context of the method
> group: If the best method is a static
> method, the method group must have
> resulted from a simple-name or a
> member-access through a type. If the
> best method is an instance method, the
> method group must have resulted from a
> simple-name, a member-access through a
> variable or value, or a base-access.
> If neither of these requirements is
> true, a compile-time error occurs. | No, that makes perfect sense. This works as expected:
```
using System;
using System.Collections.Generic;
class Foo { public void Do() { /*...*/ } /*...*/ }
class Bar : Foo {
new public static void Do()
{ ((Foo)new Bar()).Do();/*...*/ } /*...*/
}
```
That's because the compiler assumes that you have a Bar type, and then finds the static member. By casting it to Foo (which comes for free btw.) you make it look in the metdadata for Foo() and all is fine. | Why does my Static method hide my instance method? | [
"",
"c#",
".net",
""
] |
I want to write a lambda expression to verify that a list is ordered correctly. I have a List where a person has a Name property eg:
```
IList<Person> people = new List<Person>();
people.Add(new Person(){ Name = "Alan"});
people.Add(new Person(){ Name = "Bob"});
people.Add(new Person(){ Name = "Chris"});
```
I'm trying to test that the list is ordered ASC by the Name property.So I'm after something like
```
Assert.That(people.All(....), "list of person not ordered correctly");
```
How can I write a lambda to check that each Person in the list has a name less that the next person in the list? | Here's an alternative to Jared's solution - it's pretty much the same, but using a foreach loop and a Boolean variable to check whether or not this is the first iteration. I usually find that easier than iterating manually:
```
public static bool IsOrdered<T>(this IEnumerable<T> source)
{
var comparer = Comparer<T>.Default;
T previous = default(T);
bool first = true;
foreach (T element in source)
{
if (!first && comparer.Compare(previous, element) > 0)
{
return false;
}
first = false;
previous = element;
}
return true;
}
``` | I don't believe there is any LINQ operator which currently covers this case. However you could write an IsOrdered method which does the work. For example.
```
public static bool IsOrdered<T>(this IEnumerable<T> enumerable) {
var comparer = Comparer<T>.Default;
using ( var e = enumerable.GetEnumerator() ) {
if ( !e.MoveNext() ) {
return true;
}
var previous = e.Current;
while (e.MoveNext()) {
if ( comparer.Compare(previous, e.Current) > 0) {
return false;
}
previous = e.Current;
}
return true;
}
}
```
Then you could use the following to verify your list:
```
var isOrdered = people.Select(x => x.Name).IsOrdered();
``` | lambda expression to verify list is correctly ordered | [
"",
"c#",
"linq",
"lambda",
""
] |
So lets say I have an object that it stored in a Database:
```
com.test.dummy.Cat
```
The cat has an integer id.
Outside of my "world" the reference to the object is a String of the form:
Cat-433
Where 433 is the Cats assigned Database ID.
When I get the String passed to me, I need to be able to find it in the Database.
So I do this:
```
String[] splitString = str.split("-");
String objectType = splitString[0];
Integer id = Integer.valueOf(splitString[1]);
```
My question is: What would be the best way to get from **Cat** to **com.test.dummy.Cat** so I can do a Class.forName() on the String and find that object in the DB?
I was thinking some sort of XML mapping, or hardcoded pure java mapping. What are my options? | If you already know that you're going to be reading a Cat from the database, why isn't your DAO for the Cat table coded to create a new Cat() before populating it with the values you read?
You would have a Factory that would return a "DatabaseObject" for the method getDatabaseObject(String reference) that would do the splitting of the "Cat-433" name, use the first part to decide which DAO to call, and the second part to pass in as the UID in the DAO's `DatabaseObject get(int uid);` method. | A map, like HashMap. It can be set up in code, or the pair can be read from a file using any of several classes for this purpose (e.g., in Spring).
But in the larger picture, your plan is fragile. You have to parse a string, you have to assume you'll never use a class in another paxckage with the same name, etc.
You probably need to rethink what you're doing, or maybe post your *goal*, not your implementation, as a question.
Comment from OP:
> But since I would control the mapping from the SimpleName to the ClassName, would that really be a problem? – cloutierm (2 mins ago)
In a very simple toy app, this *might* work. In a real app, you'll find that you're using library classes that have the same simple name.
Or to put it another way, by doing this you're saying, "I'll never use Spring clasess, or Apache Commons classes or even java.lang classes without having to grep through my code looking for name clashes." It's to avoid such inevitable classes that packages were designed. | Best way to convert from "Simple Class Name" to "Full Class Name" to Object in Java | [
"",
"java",
"string",
"reflection",
"class",
"jpa",
""
] |
Given a generic class definition like
```
public class ConstrainedNumber<T> :
IEquatable<ConstrainedNumber<T>>,
IEquatable<T>,
IComparable<ConstrainedNumber<T>>,
IComparable<T>,
IComparable where T:struct, IComparable, IComparable<T>, IEquatable<T>
```
How can I define arithmetic operators for it?
The following does not compile, because the '+' operator cannot be applied to types 'T' and 'T':
```
public static T operator +( ConstrainedNumber<T> x, ConstrainedNumber<T> y)
{
return x._value + y._value;
}
```
The generic type 'T' is constrained with the 'where' keyword as you can see, but I need a constraint for number types that have arithmetic operators (IArithmetic?).
'T' will be a primitive number type such as int, float, etc. Is there a 'where' constraint for such types? | I think the best you'd be able to do is use `IConvertible` as a constraint and do something like:
```
public static operator T +(T x, T y)
where T: IConvertible
{
var type = typeof(T);
if (type == typeof(String) ||
type == typeof(DateTime)) throw new ArgumentException(String.Format("The type {0} is not supported", type.FullName), "T");
try { return (T)(Object)(x.ToDouble(NumberFormatInfo.CurrentInfo) + y.ToDouble(NumberFormatInfo.CurrentInfo)); }
catch(Exception ex) { throw new ApplicationException("The operation failed.", ex); }
}
```
That won't stop someone from passing in a String or DateTime though, so you might want to do some manual checking - but IConvertible should get you close enough, and allow you to do the operation. | Unfortunately there is no way to constrain a generic parameter to be an integral type (**Edit:** I guess "arithmetical type" might be a better word as this does not pertain to just integers).
It would be nice to be able to do something like this:
```
where T : integral // or "arithmetical" depending on how pedantic you are
```
or
```
where T : IArithmetic
```
I would suggest that you read [Generic Operators](http://jonskeet.uk/csharp/genericoperators.html) by our very own Marc Gravell and Jon Skeet. It explains why this is such a difficult problem and what can be done to work around it.
> .NET 2.0 introduced generics into the
> .NET world, which opened the door for
> many elegant solutions to existing
> problems. Generic constraints can be
> used to restrict the type-arguments to
> known interfaces etc, to ensure access
> to functionality - or for simple
> equality/inequality tests the
> Comparer.Default and
> EqualityComparer.Default
> singletons implement IComparer and
> IEqualityComparer respectively
> (allowing us to sort elements for
> instance, without having to know
> anything about the "T" in question).
>
> With all this, though, there is still
> a big gap when it comes to operators.
> Because operators are declared as
> static methods, there is no IMath
> or similar equivalent interface that
> all the numeric types implement; and
> indeed, the flexibility of operators
> would make this very hard to do in a
> meaningful way. Worse: **many of the
> operators on primitive types don't
> even exist as operators; instead there
> are direct IL methods.** [emphasis mine] To make the
> situation even more complex,
> Nullable<> demands the concept of
> "lifted operators", where the inner
> "T" describes the operators applicable
> to the nullable type - but this is
> implemented as a language feature, and
> is not provided by the runtime (making
> reflection even more fun). | Arithmetic operator overloading for a generic class in C# | [
"",
"c#",
"generics",
"operator-overloading",
"math",
"primitive-types",
""
] |
What is the best way to implement a strategy for the constructor of a template/abstract class in C#?
I have several classes which are all based on parsing a string inside the constructor.
The parsing is done in a static method which creates list of key value pairs and is common for all classes, but some fields are also common for all classes - thus I use a abstract template class.
The problem is that I do not see a way to inherite the implementation of the constructor of the abstract base class. Otherwise I would implement the constructor strategy in the base class and would force the handling of the lists inside some abstract methods.
Edit:
Added Not working code for the template class
```
public abstract class XXXMessageTemplate
{
public XXXMessageTemplate(string x) // implementation for the constructor
{
Parse(x);//general parse function
CommonFields();//filling common properties
HandlePrivateProperties();//fill individual properties
HandlePrivateStructures();//fill individual structures
}
abstract void HandlePrivateProperties();
abstract void HandlePrivateStructures();
}
The actual messages should not implement any constructor and only implement the HandlePrivateProperties and HandlePrivateStructures functions.
``` | If you want the logic of the base class constructor to run in the derived class, you'd normally just call up to it:
```
public Derived(...) : base(...)
{
// ...
}
```
The base class *can* call abstract/virtual methods during the constructor, but it's generally frowned upon as the derived class's constructor body will not have been executed yet. (You'd want to document this really emphatically.)
Does this answer your question? I'm not entirely sure I understand the issue - some pseudo-code would help.
EDIT: The derived classes *have* to implement constructors. Constructors aren't inherited. If you don't specify any constructor, the compiler will provide a parameterless constructor which calls a base parameterless constructor. However, you can easily write a constructor with the same signature and just call the base class constructor:
```
public Derived(string x) : base(x)
{
// Base constructor will do all the work
}
``` | Provide a constructor for the base class and use it in the derived classes:
```
abstract class Base {
// ...
protected Base(string commonField) {
CommonField = commonField;
}
}
class Derived1 : Base {
public Derived1(string commonField, string specificField) : base(commonField) {
SpecificField = specificField;
}
}
``` | Implementing a strategy for the constructor | [
"",
"c#",
"constructor",
"strategy-pattern",
""
] |
I just came across an interesting scenario. I have a class in C#:
```
public class Test
{
public int A;
public int a;
}
```
As C# is case sensitive, this will treat the two variables `A` and `a` as distinct. I want to inherit the above class in my VB code, which is not case sensitive. How will the VB code access the two distinct variables `A` and `a`?
Any help is appreciated. | The common language specification (CLS) which ensures cross language compatibility tells you not to declare two public members that are only different in case. Such a code won't be CLS compliant.
If you can't change the code of the library, you can use reflection API to manually select the field you want:
```
obj.GetType().GetField("a").GetValue(obj)
obj.GetType().GetField("A").GetValue(obj)
``` | Like Mehrdad said it is not CLS compliant to declare two public members that are only different in case
And if you want visual studio to help you write CLS complaint code that can be used from any other .NET languages , just write
```
[assembly: System.CLSCompliant(true)]
```
in your **AssemblyInfo.cs** file, if you did something wrong after writing this line, visual studio will not be happy :)
EDIT: or **AssemblyInfo.vb** if you are using VB.NET, thanks [Lucas](https://stackoverflow.com/users/24231/lucas) | Accessing members with case-sensitive names across languages in .NET | [
"",
"c#",
".net",
"vb.net",
""
] |
I just started to learn jquery and JavaScript so i can implement it with my current asp.net project. However i have a hard time to grasp the idea how to make a dialog that will show up when user attempt to push delete button and then if user chose button "Yes" it will go for the delete function in code behind of asp.net or if user chose "No" then it will be terminated and no action will be taken.
**NOTE:** I don't look for somebody to teach me, I just would like some explanation, code examples and links to information where i can read and understand and try on my own.
Thanks in advance. | In javascript you can use 'confirm' to prevent a form submission e.g.
```
<form onsubmit="return confirm('do you really want to delete this?');" method="post">
<input type="submit" value="click me">
</form>
```
The 'return' will return 'true' if you clicked [ok] in the confirm box and then the form will be submitted, or 'false' if you clicked [cancel] and then the form won't be submitted.
**[EDIT]** Some links that might be helpfull:
* [ASP.NET Popup Dialog](http://davidhayden.com/blog/dave/archive/2004/03/16/178.aspx)
* [Adding Client-Side Message Boxes in your ASP.NET Web Pages](https://web.archive.org/web/20210304115245/https://www.4guysfromrolla.com/articles/021104-1.aspx) | A simple example (which does not require jQuery) would be:
```
function deleteConfirm ()
{
if ( confirm('Are you sure you want to delete this?') )
{
// do ajax call (jquery would be handy for this)
// or redirect to delete script
}
return false;
}
```
This method uses the built-in javascript confirm() function. If you are planning on making an ajax call to access your asp.net code, then I suggest using jQuery's ajax function:
[jQuery.ajax](http://docs.jquery.com/Ajax/jQuery.ajax), [jQuery.post](http://docs.jquery.com/Ajax/jQuery.post), [jQuery.get](http://docs.jquery.com/Ajax/jQuery.get) | Need some simple explanation about dialog in jquery? | [
"",
"javascript",
"jquery",
""
] |
I'm sure there has to be an easy way to do this, maybe I'm making more work for myself than I need to. I'm trying to set up cross system communications in a way that I can have bi-directional communication between objects, I imagine it would be something like this.
```
public interface ISharedResource
public class SharedResourceHost : ISharedResource //<- slave process
SharedResourceHost resource = new SharedResourceHost("http://192.168.1.102/HostedResources/Process1");
resource.Invoke("SomeMethod");
```
is there anything like this? I don't wanna have to pull teeth setting up web services etc but if I have to I will. | You should check WCF. It is far too big to explain here but this article should give you some pointers.
<http://msdn.microsoft.com/pt-br/library/bb907581.aspx>
WCF allows you to set up interfaces in which two objects can communicate using a protocol of your choice. | You're definitely re-inventing the wheel here. Look at the [`System.Runtime.Remoting`](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.aspx) namespace. I'd link in a tutorial, but I'd just have to check [Google](http://www.google.com/search?q=c%23+remoting) and you can evaluate what will make more sense for you better than I. | Simple remote process object interaction in C# | [
"",
"c#",
".net",
"networking",
""
] |
I have two vectors of floats and i want them to become one vector of Complex numbers. I'm stuck. I don't mind using iterators, but i am sure it'd be rediscovering the wheel i'm not informed about. Is my code leading me in the right direction?
```
typedef std::vector<float> CVFloat;
CVFloat vA, vB;
//fil vectors
typedef std::complex<CVFloat> myComplexVector;
myComplexVector* vA_Complex = new myComplexVector(vA, vB);
```
The code above is going through the compiler correctly, but when i want to get single numbers from myComplexVector using iterator i get error "Undefined symbol 'const\_iterator'" (Borland C++)
```
myComplexVector::const_iterator it = vA_Complex->begin();
``` | Here you are creating a "complex" object whose real and imaginary parts are vectors of floats.
Maybe what you actually want to do is creating a vector of complex objects whose real and imaginary parts are floats?
EDIT: myComplexVector is *not* a vector, is a complex. That's why a `const_iterator` for it is not defined. | Whay not do it much much easier?
```
vector< complex<float> > result;
for( int i = 0; i < vA.size(); i++ ) {
result.push_back( complex<float>( vA[i], vB[i] ) );
}
``` | How to get Vector of Complex numbers from two vectors (real & imag) | [
"",
"c++",
"stl",
"vector",
"complex-numbers",
""
] |
The reason is long and boring, but I need to run an Ant script to compile Java 1.5 code from a Java 1.4 app. I keep getting this error, though:
```
BUILD FAILED
build.xml:16: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\j2sdk1.4.2_16\jre"
```
In my code, I have:
```
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.setProperty("java.home", "C:\Program Files\Java\jdk1.6.0_04");
p.fireBuildStarted();
p.init();
// so on and so forth
```
but it ignores it. I've also tried p.setUserProperty(String, String), but that doesn't do the trick, either. Is there a way to do it without launching a separate process? | Does the javac task in your buildfile have `fork="yes"`? If not, then it doesn't matter what the `java.home` property is set to; ant will attempt to call the javac `Main` method in the same java process, which from your error is a JRE, not a JDK.
**EDIT** Try setting the `executable` property of your javac task to the full path to the `javac` binary and add `compiler="extJavac"` to the task. | Have you set environment variables JAVA\_HOME and ANT\_HOME properly? If you are setting via code it should work though.
Also check if your %JAVA\_HOME%\bin directory %ANT\_HOME%\bin should be in the environment variable 'path'.
Your problem seems to be with the %JAVA\_HOME%\bin not being present in the envt. variable path though. | Setting JAVA_HOME when running Ant from Java | [
"",
"java",
"ant",
"javac",
""
] |
I am working on medium sized web application 4-5 tabs, user login for about 100k users. We are completing redesigning the application from scratch and using spring and hibernate, connected to MySQL.
Did you experience major issues and what where did Spring benefit your application. | No major issues. Spring was particularly of benefit for:
* Making all the configuration plumbing consistent and straightforward
* Dependency Injection to support better factoring of code
* Declarative "Open Session In View" functionality for Hibernate
* Declarative Transaction Demarcation
* The Acegi (now Spring Security) project made it easy to integrate a custom security model
* The Spring data access support removes the need for a lot of boilerplate from any JDBC access - maybe not such a boost for Hibernate usage, but we had a mix of both. It also allows you to use JDBC & Hibernate together fairly seamlessly | In addition to what has been said so far, I would focus on newer style annotations for both Spring (e.g. @Controller) and Hibernate (e.g. @Entity). It will further reduce your codebase leaving you with less code to maintain. On the downside, there is a pretty significant learning curve, but ultimately the lesson I learn time and again is that the benefits of Spring + Hibernate far outweigh the (learning curve) costs. You simply have to write a lot less code letting you focus on the business. | Have you found success with a Spring and Hibernate Web Application | [
"",
"java",
"hibernate",
"spring",
""
] |
I have a complicated background image with a lot of small regions that need rollover illustration highlights, along with additional text display and associated links for each one. The final illustration stacks several static images with transparency using z-index, and the highlight rollover illustrations need to display in one of the in-between “sandwich” layers to achieve the desired effect.
After some unsuccessful fiddling with blocks, I decided this might be done with an old-school image map. I made a schematic test map with four geometric shape outlines and “filled” them using with png rollovers. The idea is to associate the image map with the bottom background layer, initialize all the rollovers with css {visibility: hidden} and use Jquery’s hover method to make them visible as well as reveal associated text in a separate div. The separate text function is why I’m not trying to this with the :hover pseudoclass instead of jQuery hover. Because I was using the image map, I made all the rollover pngs (which have transparent backgrounds) sized to the full container for exact placement so everything lines up precisely.
What I got works... not really! The image map is correctly mapped to activate only the geometric areas. But the href from each rollover area works only intermittently, and using Jquery hover with css visibility is messed up. Desired behavior is that rolling into the area simply would make the shape solid. What actually happens is any motion inside the shape makes rapid toggling between visible and hidden; when the cursor stops within the shape, it might be visible or it might not. Any ideas appreciated!
sample hover setup (I’ll ultimately use arrays for real rollovers, associated links and text):
```
$('#triangle').hover(
function() {
$('#ID_triangle').css({'visibility' : 'visible'});
},
function() {
$('#ID_triangle').css({'visibility' : 'hidden'});
}
)
```
image map:
```
<div id="container">
<img src="images/testMap_w.png" width="800" height="220" alt="TestMap W" usemap="#testMap">
<map name="testMap">
<area shape="polygon" coords="20,20,106,20,106,106,20,106" href="http://www.stackoverflow.com" id="box" />
<area shape="polygon" coords="216,50,339,50,277,156" href="http://www.google.com" id="triangle" />
<area shape="polygon" coords="460,0,574,0,460,220" href="http://www.cnn.com" id="bordertriangle" />
<area shape="polygon" coords="704,65,769,115,744,196,665,196,640,115" href="http://slashdot.org" id="pentagon" />
</map>
<img src="images/testMap_box.png" width="800" height="220" alt="TestMap Box" id="ID_box">
<img src="images/testMap_triangle.png" width="800" height="220" alt="TestMap Triangle" id="ID_triangle">
<img src="images/testMap_border_triangle.png" width="800" height="220" alt="TestMap Border Triangle" id="ID_bordertriangle">
<img src="images/testMap_pentagon.png" width="800" height="220" alt="TestMap Pentagon" id="ID_pentagon">
</div>
``` | You should check out this plugin:
<https://github.com/kemayo/maphilight>
and the demo:
<http://davidlynch.org/js/maphilight/docs/demo_usa.html>
if anything, you might be able to borrow some code from it to fix yours. | This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.
[Image Mapster](http://www.outsharked.com/imagemapster/) is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.
It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.
There are a few examples on the web site that show most of the features. The [github repository](https://github.com/jamietre/ImageMapster) also has more examples and complete documentation. | Using JQuery hover with HTML image map | [
"",
"javascript",
"jquery",
"hover",
"imagemap",
""
] |
**Duplicate of the following question: [C function conflict](https://stackoverflow.com/questions/678254/c-function-conflict)**
---
Hi,
in my current project I have to use some kind of interface lib. The function names are given by this interface, what this functions do is developers choice. As far as I can tell a project shall use this functions and when it comes to compiling you choose the lib and with it the functionality. What I try to do is to use an existing lib and my lib at the same time by wrapping the other and call it in mein functions:
otherlib:
```
int function1 (int a) {
// do something
}
```
mylib:
```
int function1 (int a) {
//my code here
otherlib::function1(a);
}
```
Problem is I don't have access to the other lib and the other lib doesn't have any namespaces. I already tried
```
namespace old {
#include "otherlib.h"
}
```
and then call the old function by old::function1 in my function. This works as long as it's only header file. The lib exports it's symbol back into global space. Also something like
```
namespace new {
function1 (int a) {
::function1(a);
}
}
```
didn't work. Last but not least I tried ifdefs and defines suggested [here](https://stackoverflow.com/questions/189921/how-to-handle-a-class-name-conflict-when-porting-old-code)
but I wasn't successful.
Any ideas how to solve this? Thanks in advance.
EDIT: I neither have access to the old lib nor the project both libs shall be used in.
EDIT2: at least the old lib is a static one | Namespaces in C solved using library names prefixes like:
libfoo --> foo\_function1
libbar --> bar\_function1
These prefixes are actual namespaces. so if you write libbar
```
int bar_function1(int a) {
function1(a);
}
```
This is the way to solve problems.
C has namespaces --- they just called prefixes ;)
Another option is to do various dirty tricks with dynamic loading of libraries like:
```
h1=dlopen("libfoo.so")
foo_function1=dlsym(h1,"function1")
h2=dlopen("libbar.so")
bar_function1=dlsym(h2,"function1")
``` | It seems as if the other lib is C and your code is C++. You can be running into a mangling problem (C++ compilers mangle the symbols -- add extra stuff in the symbol name do differentiate overloads and the like).
If the library is pure C you can try:
```
extern "C" { // disable mangling of symbol names in the block
#include "otherlib.h"
}
namespace new_lib { // new is a reserved word
int function1( int a ) {
::function1(a);
}
}
```
I have not tried it. Also consider providing the error messages you are getting.
Another option would be (if the library is dynamic) dynamically loading the lib and calling the function. In linux (I don't know about windows) you can use dlopen to open the library, dlsym to obtain the symbol and call it:
```
// off the top of my head, not tried:
int function1( int a )
{
int (*f)(int); // define the function pointer
void * handle = dlopen( "library.so" );
f = dlsym( handle, "function1" );
f( a ); // calls function1(a) in the dynamic library
}
```
In this case, as you are not linking against the library you won't get a symbol conflict, but then again, it is only valid for dynamic libraries and it is quite cumbersome for regular usage.
**UPDATE**
If your users will not use 'otherlib' directly (they won't include their headers) and they will be only C++, then the first approach could be possible (even if horrible to read):
```
// newlib.h
namespace hideout {
int f( int a );
}
using namespace hideout; // usually I would not put this on the header
// newlib.cpp
extern "C" { // if otherlib is C, else remove this line
#include "otherlib.h"
}
namespace hideout {
int f( int a ) { return ::f( a*2 ); }
}
// main.cpp
#include "newlib.h"
int main()
{
std::cout << f( 5 ) << std::endl;
}
```
How does it work? User code will only see a declaration of function1 (in the example f()) as they are not including *otherlib.h*. Inside your compilation unit you see the two declarations but you differentiate through the use of the namespace. The using statement in the header does not bother you as you are fully qualifying in your cpp. The user *main.cpp* will include only your header, so the compiler will only see *hideout::f*, and will see it anywhere due to the using statement. The linker will have no problem as the C++ symbol is mangled identifying the real namespace:
```
// g++ 4.0 in macosx:
00002dbe T __ZN7hideout9function1Ei // namespace hideout, function1 takes int, returns int
00002db0 T _function1
```
If user code will include both your header and *otherlib.h* then it will have to qualify which function it wants to call. | How to use 2 C libs that export the same function names | [
"",
"c++",
"c",
"word-wrap",
"ambiguity",
""
] |
I have written the folllowing regex and would like to get empty strings removed automatically and could not find any equivalent to RemoveEmptyEntries for Regex which I found only for the Split method in string.
```
string test = "{ key1 = { key2= xx } | key3 = y | key4 = z }";
string[] help = Regex.Split(test, "(=)|({)|(})|(\\|)");
```
The result string array contains elements which are empty. I would like to run the regular expression without yielding any empty strings contained in the result.
I will run this code very, very frequently - thus I need it as efficient as possible.
Updates: As this is a parser I need to keep the tokens and I found only a way with Regex to keep them. | Maybe not a full solution to the question, but I have a few remarks for the problem at hand (tokenizing a string):
```
the original regex: (=)|({)|(})|(\|)
is equivalent to: (=|{|}|\|)
is equivalent to: ([={}|])
```
All of the above expressions return the same 21 elements, but they perform differently. I set up a quick test going over 100,000 iterations of `Split()` operations using pre-built Regex objects with `RegexOptions.Compiled` and the `Stopwatch` class.
* regex #1 takes 2002ms on my hardware
* regex #2 takes 1691ms
* regex #3 takes 1542ms
* regex #4 takes 1839ms (that's the one below)
YMMV.
However, the desired elements can still be surrounded by white space. I figure this is undesired as well, so the regex I would split on would be this:
```
\s*([={}|])\s*
```
The returned elements are:
```
["", "{", "key1", "=", "", "{", "key2", "=", "xx", "}", "", "|", "key3", "=", "y", "|", "key4", "=", "z", "}", ""]
```
The few remaining empty strings should not pose a big problem performance-wise when iterating the array and can be taken care of (read: ignored) when they are encountered.
EDIT: If you measure performance it is possible that you find splitting on `([={}|])` and trimming the array elements "manually" is faster than splitting on `\s*([={}|])\s*`. Just try what works better for you. | I don't think that option is built into RegEx. But with C#3.0 you could just use a simple `.Where()`:
```
string[] help = Regex.Split(test, "(=)|({)|(})|(\\|)")
.Where(s => !string.IsNullOrEmpty(s)).ToArray();
```
To make this more efficient, declare the RegEx once — perhaps at class level or make it static — rather than recreating it all the time. Additionally, odds are you're only using the returned array to iterate over the results. You can make this faster by skipping the `.ToArray()` call on the end and just keeping the IEnumerable for your iteration.
```
//earlier
RegEx KeySplitter = new RegEx ("(=)|({)|(})|(\\|)");
```
.
```
//later
string test = ""; //
for (string key in KeySplitter.Split(test).Where(s => !string.IsNullOrEmpty(s)))
{
// ...
}
```
One of the nice things about how linq-to-objects works is that this will still only iterate over your `.Split` results *once*, because the `GetEnumerator` method in the `Where` function will do lazy evaluation. Depending on what you need to do inside the for loop you might be able to gain a similar efficiency by adding a `.Select()` call. | Removing empty strings | [
"",
"c#",
".net",
"regex",
""
] |
When trying to save a thumbnail made with GD
```
imagejpeg($tnImage, "../../img/thumbs/".$maxWidth."x".$maxHeight."_".$filename);
```
I am getting the following error:
**Warning**: imagejpeg() [function.imagejpeg]: Unable to open '../../img/thumbs/80x80\_55865-drops.jpg' for writing: No such file or directory in **/home/user/workspace/stewart/server-side/libImg.php**
/home/user/workspace/img/thumbs has its permissions set to 0x777.
What can be wrong here? | Where are you running the file from? If it's from the `server-side` directory then I think you're missing a "../"
Try this:
```
var_dump(realpath("../../img/thumbs/".$maxWidth."x".$maxHeight."_".$filename));
``` | In
```
/home/user/workspace/stewart/server-side/
```
the directory
```
../../img/thumbs/
```
would equate to
```
/home/user/workspace/img/thumbs/
```
so you need
```
../../../img/thumbs/
``` | PHP-GD imagejpeg unable to open | [
"",
"php",
"gd",
""
] |
I have a huge table of > 10 million rows. I need to efficiently grab a random sampling of 5000 from it. I have some constriants that reduces the total rows I am looking for to like 9 millon.
I tried using order by NEWID(), but that query will take too long as it has to do a table scan of all rows.
Is there a faster way to do this? | If you can use a pseudo-random sampling and you're on SQL Server 2005/2008, then take a look at TABLESAMPLE. For instance, an example from SQL Server 2008 / AdventureWorks 2008 which works based on rows:
```
USE AdventureWorks2008;
GO
SELECT FirstName, LastName
FROM Person.Person
TABLESAMPLE (100 ROWS)
WHERE EmailPromotion = 2;
```
The catch is that TABLESAMPLE isn't exactly random as it generates a given number of rows from each physical page. You may not get back exactly 5000 rows unless you limit with TOP as well. If you're on SQL Server 2000, you're going to have to either generate a temporary table which match the primary key or you're going to have to do it using a method using NEWID(). | Have you looked into using the TABLESAMPLE clause?
For example:
```
select *
from HumanResources.Department tablesample (5 percent)
``` | Select random sampling from sqlserver quickly | [
"",
"sql",
"sql-server",
"database",
"performance",
"random",
""
] |
Greetings Everyone
I am currently trying to write a multi-language program (C, C++ and fortran) though am achieving segmentation errors. I've ruled out vectors and the like in: [Accessing public class memory from C++ using C](https://stackoverflow.com/questions/666320/accessing-public-class-memory-from-c-using-c)
I've narrowed now the cause to the use of 'cout' experssions in my C++ segments and printf(...) in C segments. Depending on which order I run these at I always get segmentation error when using the 2nd type, like so:
1. cout first, then printf(...) will crash at first C output function
2. printf(...), then cout will crash at first C++ output function
I am `#include <iostream>` in my C++ sources, and `#include <stdio.h>` & `#include <stdlib.h>` in my C sources.
Is there a library conflict that I am not aware of?
Requested code:
main.cpp
```
#include <iostream>
#include <vector>
#include "CFE.h"
ios::sync_with_stdio(true);
using namespace std;
vector<float> DensityArray;
vector<float> EnergyArray;
int main()
{
int X = ReturnX ();
int Y = ReturnY ();
cout << "X " << X << endl;
cout << "Y " << Y << endl;
EnergyArray.resize(Y*X);
DensityArray.resize(Y*X);
CFE(&DensityArray[0], &EnergyArray[0]);
cout << "X " << X << endl; //causes Segmentation break
cout << "Y " << Y << endl; //causes Segmentation break
system ("PAUSE");
return 0;
}
```
CFE.h
```
#ifdef __cplusplus
extern "C" {
#endif
int ReturnX ();
int ReturnY ();
void CFE(float density[], float energy[]);
#ifdef __cplusplus
}
#endif
```
CFE.cpp
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "BCs.h"
#include "EMatrix.h"
#include "Numbering.h"
#include "KMatrix.h"
#include "fg_types.h"
#include "Solve.h"
int ReturnX ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemX;
}
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
fclose(infile);
return elemY;
}
void CFE(float density[], float energy[])
{
FILE *infile;
infile = fopen("test05", "r");
int elemY, elemX;
fscanf(infile, "%i %i", &elemX, &elemY); //Will cause Segmentation break
int n;
float * dens;
dens = density;
float * engy;
engy = energy;
int Length = 10;
for ( n = 0; n < Length; n++)
{
engy[n] = n;
}
}
``` | You need to check that the files are opened correctly - i.e. the the pointer returned by fopen() is not NULL. Also,
```
int ReturnY ()
{
FILE *infile;
infile = fopen("test05", "r");
int elemX,elemY;
fscanf(infile, "%i %i", &elemX, &elemY);
return elemX;
}
```
I take it **return elemx** should be **return elemy**? | Any particular reason why you don't just use printf in your C++ code? Sure, it's not like what all the cool kids do, but it should still work. | Output conflicts between C & C++ | [
"",
"c++",
"c",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.