Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In my web app I use several asmx (Web Services) from the same provider, they have one for this, other for that, but all require a SOAP Header with Authentication.
It is simple to add the Authentication:
```
public static SoCredentialsHeader AttachCredentialHeader()
{
SoCredentialsHeader ch = new SoCredentialsHeader();
ch.AuthenticationType = SoAuthenticationType.CRM5;
ch.UserId = "myUsername";
ch.Secret = apUtilities.CalculateCredentialsSecret(
SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword");
return ch;
}
```
The problem is this SoCredentialsHeader come (derivation) from ONE webservice and I need to add the same code to the others, like:
```
public static wsContact.SoCredentialsHeader AttachContactCredentialHeader()
{
wsContact.SoCredentialsHeader ch = new wsContact.SoCredentialsHeader();
ch.AuthenticationType = wsContact.SoAuthenticationType.CRM5;
ch.UserId = "myUsername";
ch.Secret = apUtilities.CalculateCredentialsSecret(
wsContact.SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword");
return ch;
}
public static wsDiary.SoCredentialsHeader AttachDiaryCredentialHeader()
{
wsDiary.SoCredentialsHeader ch = new wsDiary.SoCredentialsHeader();
ch.AuthenticationType = wsDiary.SoAuthenticationType.CRM5;
ch.UserId = "myUsername";
ch.Secret = apUtilities.CalculateCredentialsSecret(
wsDiary.SoAuthenticationType.CRM5, apUtilities.GetDays(), "myUsername", "myPassword");
return ch;
}
```
Is there a way to implement a design pattern in order to use only one function but that suits all webServices?
sometimes I see the **T** letter, is this a case for that? if yes, how can I accomplish such feature?
P.S. I could pass an enum and use a switch to check the enum name and apply the correct Header but everytime I need to add a new WebService, I need to add the enum and the code, I'm searcging for an advanced technique for this.
Thank you. | Create a file called whatever.tt (the trick is the .tt extension) anywhere in your VS solution and paste the following code:
```
using System;
namespace Whatever
{
public static class Howdy
{
<#
string[] webServices = new string[] {"wsContact", "wsDiary"};
foreach (string wsName in webServices)
{
#>
public static <#=wsName#>.SoCredentialsHeader AttachContactCredentialHeader()
{
<#=wsName#>.SoCredentialsHeader ch = new <#=wsName#>.SoCredentialsHeader();
ch.AuthenticationType = <#=wsName#>.SoAuthenticationType.CRM5;
ch.UserId = "myUsername";
ch.Secret = apUtilities.CalculateCredentialsSecret(<#=wsName#>.SoAuthenticationType.CRM5,
apUtilities.GetDays(), "myUsername", "myPassword");
return ch;
}
}
<# } #>
}
```
Then watch as a whatever.cs magically appears with the desired code snippets.These are called T4 templates for code generation in VS.
You'll want to turn these into partial classes or extension methods or something. The above code will not function "as is" but you get the idea. | I don't know if this is something you wish to consider, as it definitely has it's down sides, but - as ultimately these ( the varoius SoCredentialsHeader classes) are all copies of the same class definition in different namespaces so with a little bit of refactoring you could simply have one class and one method.
Copy the SoCredentialsHeader class definition to a project of your own, add a reference to it and remove the class definition from all web service's proxies.
Add a using statement at the top of the proxy code file and it would not tell the difference.
Basically you told it to use the same class definition (yours) for all web services.
The obvious down side is that you have to repeat this exercise whenever you update and web service reference (and that it assumes all services keep using the same definition), but we've been doing this in a similar scenario and it worked quite well for us. | Create an "all-in-one" function using DS in C# | [
"",
"c#",
"asp.net",
"design-patterns",
""
] |
Say we have:
```
class Base
{
virtual void f() {g();};
virtual void g(){//Do some Base related code;}
};
class Derived : public Base
{
virtual void f(){Base::f();} override;
virtual void g(){/*Do some Derived related code*/} override;
};
int main()
{
Base *pBase = new Derived;
pBase->f();
return 0;
}
```
Which `g()` will be called from `Base::f()`? `Base::g()` or `Derived::g()`?
Thanks... | The g of the derived class will be called. If you want to call the function in the base, call
```
Base::g();
```
instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:
```
virtual void g() {
Base::g();
// some work related to derived
}
```
The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as [Non-Virtual-Interface](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface). It's widely used also in the C++ standard library (C++ stream buffers for example have functions `pub...` that call virtual functions that do the real work. For example `pubseekoff` calls the protected `seekoff`). I wrote an example of that in this answer: [How do you validate an object’s internal state?](https://stackoverflow.com/questions/343605/how-do-you-validate-an-objects-internal-state#343628) | It is the Derived::g, unless you call g in Base's constructor. Because Base constructor is called before Derived object is constructed, Derived::g can not logically be called cause it might manipulate variables that has not been constructed yet, so Base::g will be called. | virtual function call from base class | [
"",
"c++",
"polymorphism",
"virtual",
""
] |
Well, I must be brain-damaged, because I can't find the java source for Sun's persistence.jar or JBoss's ejb3-persistence.jar JPA package. They *are* open-source aren't they?
I looked all over the java.sun.com site as well as the GlassFish wiki, but came up empty.
I'd like a src.zip or folder like Sun delivers with Java JDKs.
Of course, I *really* don't *have* to have it, but I think it's fun to browse the source once in a while. And it helps me to debug my code sometimes. | I have found the version 1.0.2 GA it here: <http://grepcode.com/snapshot/repository.jboss.com/maven2/org.hibernate/ejb3-persistence/1.0.2.GA> | I just did a search on <http://www.mvnrepository.com> for persistence api
<http://mirrors.ibiblio.org/pub/mirrors/maven2/javax/persistence/persistence-api/1.0/persistence-api-1.0-sources.jar>
also available in the java.net maven 1 repository
<http://download.java.net/maven/1/javax.persistence/java-sources/>
for the implementations see hibernate entity manager, openjpa, eclipse toplink, glassfish persistence, ... | ejb3-persistence.jar source | [
"",
"java",
"jpa",
"open-source",
"persistence",
""
] |
I was wondering why `shared_ptr` doesn't have an implicit constructor. The fact it doesn't is alluded to here: [Getting a boost::shared\_ptr for this](https://stackoverflow.com/questions/142391/getting-a-boostsharedptr-for-this)
(I figured out the reason but thought it would be a fun question to post anyway.)
```
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace boost;
using namespace std;
void fun(shared_ptr<int> ptr) {
cout << *ptr << endl;
}
int main() {
int foo = 5;
fun(&foo);
return 0;
}
/* shared_ptr_test.cpp: In function `int main()':
* shared_ptr_test.cpp:13: conversion from `int*' to non-scalar type `
* boost::shared_ptr<int>' requested */
``` | In this case, the shared\_ptr would attempt to free your stack allocated int. You wouldn't want that, so the explicit constructor is there to make you think about it. | The logical reason is that:
* calling the `delete` operator is not implicit in C++
* **the creation of any owning smart pointer** (`shared_`whatever, `scoped_`whatever, ...) **is really a (delayed) call to the `delete` operator** | Why shared_ptr has an explicit constructor | [
"",
"c++",
"boost",
"refcounting",
""
] |
I have a few things that I cannot find a good way to perform in Visual Studio:
1. Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it does not work if I don't know names and/or the number of auto-generated source files. I can easily solve it in `GNU make` using `$(wildcard generated/*.c)`. How can I do something similar with Visual Studio?
2. Can I prevent pre-build/post-build event running if the files do not need to be modified (`"make"` behaviour)? The current workaround is to write a wrapper script that will check timestamps for me, which works, but is a bit clunky.
3. What is a good way to locate external libraries and headers installed outside of VS? In \*nix case, they would normally be installed in the system paths, or located with `autoconf`. I suppose I can specify paths with user-defined macros in project settings, but where is a good place to put these macros so they can be easily found and adjusted?
Just to be clear, I am aware that better Windows build systems exist (`CMake`, `SCons`), but they usually generate VS project files themselves, and I need to integrate this project into existing VS build system, so it is desirable that I have just plain VS project files, not generated ones. | 1. If you need make behavior and are used to it, you can create [visual studio makefile projects](http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.80).aspx) and include them in your project.
2. If you want less clunky, you can write visual studio [macros](http://visualstudiohacks.com/articles/general/customize-your-project-build-process/) and custom build events and tie them to specific build callbacks / hooks.
3. You can try something like [workspacewhiz](http://workspacewhiz.com/SolutionBuildEnvironmentReadme.html) which will let you setup environment variables for your project, in a file format that can be checked in. Then users can alter them locally. | I've gone through this exact problem and I did get it working using Custom Build Rules.
But it was always a pain and worked poorly. I abandoned visual studio and went with a Makefile system using cygwin. Much better now.
cl.exe is the name of the VS compiler.
Update: I recently switched to using cmake, which comes with its own problems, and cmake can generate a visual studio solution. This seems to work well. | Complex builds in Visual Studio | [
"",
"c++",
"c",
"windows",
"visual-studio",
"build",
""
] |
I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...
On the one occasion the crash occurred under the debugger, the debugger did not break---it showed the application still running. When I manually paused execution, I found that my process no longer had any threads.
How can I capture the reason this process is terminating? | You could try using the adplus utility in the [windows debugging tool package](http://www.microsoft.com/whdc/devtools/debugging/default.mspx).
```
adplus -crash -p yourprocessid
```
The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes. | If you are using Visual Studio 2003 or later, you should enable the debuggers "First Chance Exception" handler feature by turning on ALL the Debug Exception Break options found under the Debug Menu | Exceptions Dialog. Turn on EVERY option before starting the debug build of the process within the debugger.
By default most of these First Chance Exception handlers in the debugger are turned off, so if Windows or your code throws an exception, the debugger expects your application to handle it.
The First Chance Exception system allows debuggers to intercept EVERY possible exception thrown by the Process and/or System.
<http://support.microsoft.com/kb/105675> | How can I debug a win32 process that unexpectedly terminates silently? | [
"",
"c++",
"debugging",
"winapi",
"crash",
""
] |
In java, does `file.delete()` return `true` or `false` where `File file` refers to a non-existent file?
I realize this is kind of a basic question, and easy to very through test, but I'm getting strange results and would appreciate confirmation. | Doesn't that result in a FileNotFoundException?
EDIT:
Indeed it does result in false:
```
import java.io.File;
public class FileDoesNotExistTest {
public static void main( String[] args ) {
final boolean result = new File( "test" ).delete();
System.out.println( "result: |" + result + "|" );
}
}
```
prints `false` | From [<http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete()>](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#delete()):
Returns: true if and only if the file or directory is successfully deleted; false otherwise
Therefore, it should return false for a non-existent file. The following test confirms this:
```
import java.io.File;
public class FileTest
{
public static void main(String[] args)
{
File file = new File("non-existent file");
boolean result = file.delete();
System.out.println(result);
}
}
```
Compiling and running this code yields false. | Does file.delete() return true or false for non-existent file? | [
"",
"java",
"file",
""
] |
I want to cast both MenuItem objects and Button control objects to an object type of whose "Tag" property I can reference.
Is there such an object type?
E.g.
```
void itemClick(object sender, EventArgs e)
{
Control c = (Control)sender;
MethodInvoker method = new MethodInvoker(c.Tag.ToString(), "Execute");
method.Invoke();
}
```
Except this fails - "Unable to cast object type 'System.Windows.Forms.MenuItem' to type 'System.Windows.Forms.Control'
What can replace Control in this example? | Use "as" operator.
```
object tag;
Button button;
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
tag = menuItem.Tag;
}
else if( (button = sender as Button) != null )
{
tag = button.Tag;
}
else
{
//not button nor MenuItem
}
``` | I am writing this without IDE.
```
object myControlOrMenu = sender as MenuItem ?? sender as Button;
if (myControlOrMenu == null)
// neither of button or menuitem
``` | Is there a type of object, to which I can cast both Buttons AND MenuItem objects in order to access their Tag properties? | [
"",
"c#",
".net",
"casting",
""
] |
Is it possible to declare an instance of a generic without knowing the type at design-time?
Example:
```
Int i = 1;
List<typeof(i)> list = new List<typeof(i)>();
```
where the type of i could be anything, instead of having to do:
```
List<int> list = new List<int();
``` | If you don't know the type at compile-time, but you want the actual type (i.e. not `List<object>`) *and* you're not in a generic method/type with the appropriate type parameter, then you have to use reflection.
To make the reflection simpler, I've sometimes introduced a new generic type or method in my own code, so I can call that by reflection but then just use normal generics after that. For example:
```
object x = GetObjectFromSomewhere();
// I want to create a List<?> containing the existing
// object, but strongly typed to the "right" type depending
// on the type of the value of x
MethodInfo method = GetType().GetMethod("BuildListHelper");
method = method.MakeGenericMethod(new Type[] { x.GetType() });
object list = method.Invoke(this, new object[] { x });
// Later
public IList<T> BuildListHelper<T>(T item)
{
List<T> list = new List<T>();
list.Add(item);
return list;
}
```
Of course, you can't do an awful lot with the list afterwards if you don't know the type... that's why this kind of thing often falls down. Not always though - I've used something like the above on a few occasions, where the type system just doesn't quite let me express everything I need to statically.
EDIT: Note that although I'm calling Type.GetMethod in the code above, if you were going to execute it a lot you'd probably want to just call it once - after all, the method isn't going to change. You may be able to make it static (you could in the case above) and you probably want to make it private too. I left it as a public instance method for the simplicity of the GetMethod call in sample code - you'd need to specify the appropriate binding flags otherwise. | If you don't know the type at design-time, I'd say you have a list of OBJECTS (the base class for all other types).
```
List<object> list = new List<object>();
``` | Declare a generic type instance dynamically | [
"",
"c#",
".net",
"generics",
""
] |
I have this line of JavaScript and the behavior I am seeing is that the `selectedLi` instantly disappears without "sliding up". This is not the behavior that I expected.
What should I be doing so that the `selectedLi` slides up before it is removed?
```
selectedLi.slideUp("normal").remove();
``` | Might be able to fix it by putting the call to remove in a callback arg to slideUp?
e.g
```
selectedLi.slideUp("normal", function() { $(this).remove(); } );
``` | You need to be more explicit: rather than saying "this" (which I agree should work), you should do this:
```
$("#yourdiv").slideUp(1000, function() {
$(this).remove();
});
``` | jQuery slideUp().remove() doesn't seem to show the slideUp animation before remove occurs | [
"",
"javascript",
"jquery",
"animation",
""
] |
I think my eclipse's ctrl+clicking links might benefit greatly...
**Edit:** I'm using eclipse PDT.
**Edit 2:** I'm very happy with the solution of putting docblocks before functions (and variables) with an @return or @var statement, I've just updated the documentation of my app and now eclipse is showing me what functions are available to what objects!
Awesome. | ```
// [...]
/**
* Return the Request object
*
* @return Zend_Controller_Request_Abstract
*/
public function getRequest()
{
return $this->_request;
}
// [...]
```
works perfectly with Eclipse PDT. Which plugin do you use? | Short answer: no.
Long answer: consider adding docblocks with @return declarations. | Can you hint return types in PHP 5.2.5? | [
"",
"php",
"eclipse",
"return-value",
"php-5.2",
"type-hinting",
""
] |
I need to provide email sending and receiving capabilities within my java web-application. Think of it as providing a lightweight IMAP client embedded within the application.
Are there any good java based open-source libraries/projects/webmail solutions that provide similar functionality?
Please note that I don't want to emails would still be retrieved from the email server external to my application, I just need to provide an interface (matching the rest of my application) and accessible from within the application, to carry out common email operations such as reading and sending emails.
Regards,
-Deepak | The "canonical" Java IMAP solution would, in my experience, be [JavaMail](http://java.sun.com/products/javamail/). And yes, that's open-source now, too: <https://maven-repository.dev.java.net/nonav/repository/javax.mail/java-sources/> | Look here: [Open Source Web Mail Clients in Java](http://java-sources.org/open-source/web-mail) | Java based Webmail solutions | [
"",
"java",
"webmail",
""
] |
Let's say I have a payments table like so:
```
CREATE TABLE Payments (
PaymentID INT,
CustomerID INT,
Value INT,
PaidOn DATE
);
INSERT INTO Payments
VALUES
(1, 1, 5, '2000-01-01'),
(2, 1, 10, '2000-02-01'),
(3, 2, 10, '2000-01-02'),
(4, 2, 10, '2000-01-20'),
(5, 2, 5, '2000-02-02'),
```
And I want to run a query for the entire row for the maximum payment made by each customer. Is this possible using a single SQL query, to avoid having to dig through every row that I'm not interested -- or worse, run a query for each customer?
The best I have come up with so far is:
```
SELECT CustomerID, MAX(Value)
FROM Payments
GROUP BY CustomerID;
```
But this does not give me the `PaymentId` or `PaidOn` values for the rows it finds. | The following query will accomplish that. It pulls out all the rows for which there is not a greater Value.
```
SELECT *
FROM payments p
WHERE NOT EXISTS (
SELECT *
FROM payments p2
WHERE p2.CustomerID = p.CustomerId
AND p2.Value > p.Value
)
``` | ```
select PaymentID, CustomerID, Value, PaidOn
from payments
where (customerID, value) in
( select customerID, max(value)
from payments
group by customerID
);
```
Note that this can return more than one row per customer if they have more than one payment with the maximum value. | SQL query for finding representative rows in a table | [
"",
"sql",
"groupwise-maximum",
""
] |
I've implemented my own event handler and added it to the selection model of the table:
```
table.getSelectionModel().addListSelectionListener(event);
```
And implemented the method for "event" (mentioned above):
```
public void valueChanged(ListSelectionEvent e) {
log.debug("value changed");
}
```
Unfortunately the event fires twice if I chance the selection and it doesn't seem possible to find the associated table, because e.getSource provides javax.swing.DefaultListSelectionModel.
Hence my questions are:
1) Why does it fire twice although the eventListener is only registered once?
2) How can I find the table for which the selection applies? The DefaultListSelectionModel doesn't seem to offer any getSource() or similar.
Many thanks! | 1) I think you'll find it fires once for de-selecting the old selection and once for selecting the new selection. If you log the details of the event you should see exactly what's going on. I can't remember the details, so perhaps this is wrong. Either way you should be able to call getValueIsAdjusting() on the event and only use the last one in the chain (ie when it returns false).
2) You shouldn't normally need to, but AFAIK the only way to do this is to create your Listener specifically for the table (ie pass the table to the constructor and remember it). | Thanks Draemon..It Works fine....
## Our Code
```
vMachinesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
System.out.println("Selection Changed");
}
}
});
```
Thanks By
TF Team | JTable selection change event handling: find the source table dynamically | [
"",
"java",
"event-handling",
"jtable",
""
] |
What is the best way to have an associative array with arbitrary value types for each key in C++?
Currently my plan is to create a "value" class with member variables of the types I will be expecting. For example:
```
class Value {
int iValue;
Value(int v) { iValue = v; }
std::string sValue;
Value(std::string v) { sValue = v; }
SomeClass *cValue;
Value(SomeClass *v) { cValue = c; }
};
std::map<std::string, Value> table;
```
A downside with this is you have to know the type when accessing the "Value". i.e.:
```
table["something"] = Value(5);
SomeClass *s = table["something"].cValue; // broken pointer
```
Also the more types that are put in Value, the more bloated the array will be.
Any better suggestions? | [boost::variant](http://www.boost.org/doc/libs/1_37_0/doc/html/variant.html) seems exactly what you are looking for. | Your approach was basically into the right direction. You *will* have to know the type you put into. You can use `boost::any` and you will be able to put just about anything into the map, as long as you know what you put into:
```
std::map<std::string, boost::any> table;
table["hello"] = 10;
std::cout << boost::any_cast<int>(table["hello"]); // outputs 10
```
Some answers recommended the use of `boost::variant` to solve this problem. But it won't let you store arbitrary typed values in the map (like you wanted). You have to know the set of possible types before-hand. Given that, you can do the above more easily:
```
typedef boost::variant<int, std::string, void*> variant_type;
std::map<std::string, variant_type> table;
table["hello"] = 10;
// outputs 10. we don't have to know the type last assigned to the variant
// but the variant keeps track of it internally.
std::cout << table["hello"];
```
That works because `boost::variant` overloads `operator<<` for that purpose. It's important to understand that if you want to save what is currently contained in the variant, you still have to know the type, as with in the `boost::any` case:
```
typedef boost::variant<int, std::string, void*> variant_type;
std::map<std::string, variant_type> table;
table["hello"] = "bar";
std::string value = boost::get<std::string>(table["hello"]);
```
The order of assignments to a variant is a runtime property of the control flow of your code, but the type used of any variable is determined at compile time. So if you want to get the value out of the variant, you have to know its type. An alternative is to use visitation, as outlined by the variant documentation. It works because the variant stores a code which tells it which type was last assigned to it. Based on that, it decides *at runtime* which overload of the visitor it uses. `boost::variant` is quite big and is not completely standard compliant, while `boost::any` is standard compliant but uses dynamic memory even for small types (so it's slower. variant can use the stack for small types). So you have to trade off what you use.
If you actually want to put objects into it which differ only in the way they do something, polymorphism is a better way to go. You can have a base-class which you derive from:
```
std::map< std::string, boost::shared_ptr<Base> > table;
table["hello"] = boost::shared_ptr<Base>(new Apple(...));
table["hello"]->print();
```
Which would basically require this class layout:
```
class Base {
public:
virtual ~Base() { }
// derived classes implement this:
virtual void print() = 0;
};
class Apple : public Base {
public:
virtual void print() {
// print us out.
}
};
```
The [`boost::shared_ptr`](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm) is a so-called smart pointer. It will delete your objects automatically if you remove them out of your map and nothing else is referencing them them anymore. In theory you could have worked with a plain pointer too, but using a smart pointer will greatly increase safety. Read the shared\_ptr manual i linked to. | C++ associative array with arbitrary types for values | [
"",
"c++",
"arrays",
"stl",
"boost",
""
] |
I want to access Microsoft SQL Server Compact Edition databases from Java. How can I do that? I searched for JDBC driver for SQLCE, but I didn't find any. | According to [a newsgroup post sent this Tuesday (2008-12-09) by Jimmy Wu@Mircrosoft](http://groups.google.com/group/microsoft.public.sqlserver.jdbcdriver/browse_thread/thread/2ba56d70e6b35ee7):
> The Microsoft SQL Server JDBC Driver
> does not support connecting to SQL
> Server Compact. At this time there
> isn't a scheduled JDBC support for SQL
> Server Compact edition. Thank-you for
> your continuing support of SQL
> Server.
>
> Sincerely, Jimmy Wu | According to [MSDN](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=770916&SiteID=1), there isn't one and there aren't any plans neither. | How to use SQL Server Compact Edition (CE) from Java? | [
"",
"java",
"sql-server",
"jdbc",
"sql-server-ce",
""
] |
I want to spruce up some areas of my website with a few jQuery animations here and there, and I'm looking to replace my AJAX code entirely since my existing code is having some cross-browser compatibility issues. However, since jQuery is a JavaScript library, I'm worried about my pages not functioning correctly when JavaScript is turned off or doesn't exist in a user's browser.
I'll give an example: Currently, I'm using a pure CSS tooltip to give my users (players, the site is a browser game) information on other users. For example, if the other players in the game satisfy one or more conditions, a target icon is displayed next to their name, and upon hovering over that target icon information regarding the reasons behind the target is displayed. This is useful information, as it helps my players to know who they should plan to attack next in the game.
Currently, I do such tooltips using CSS. I have a parent div that holds the image of the target icon of class "info". I then have a div inside of that with class "tooltip" that, on the hover state of the "info" class that it is contained in, is shown, but on the normal state is hidden. I thought it was rather clever when I read about it, and since no JavaScript is used it works on any CSS compliant browser.
I would like to use jQuery to achieve the same effect, mostly because it would look much cleaner, but also because I believe quick and subtle animations can make such things "randomly appearing" make a lot more sense to the user, especially on the first encounter. I'm just wondering if the two will conflict. This is only one example of this, there are numerous other examples where the inability to use JavaScript would hinder the site.
So what I'm asking I guess is, how does one make a jQuery site degrade gracefully on browsers that do not support JavaScript, but otherwise *do* support most CSS? My goal is for the site to function on a basic level for all users, regardless of choice in browser. The animation is a good example, but I'm also worried about the more dynamic bits, like the auto-updating with AJAX, etc. Are there any good resources on how to achieve this, or do you have any advice about the best way such degradability could be achieved?
Thanks
PS: Totally irrelevant, but Firefox seems to think that "degradability" isn't a word, but "biodegradability" (with the "bio" prefix) is. Weird... | If you consider the "Cascading Order" of css, could you not just add a css style at the very end of all your previous css definition in order to cancel any css effect you currently have for tooltip effect ?
That css rule would only be declared if Javascript is activated and JQuery detected.
That way, you are sure your [css tooltip effect](http://psacake.com/web/jl.asp) is not in conflict with your JQuery effect.
Something like:
```
a.info:hover span{ display:none}
```
with the use of "js\_enabled" class to make this css rule conditional.
You also can do it by [adding css rule on the fly](http://forum.mootools.net/viewtopic.php?id=6635):
```
function createCSSRule(rule,attributes)
{
//Create the CSS rule
var newRule = "\n"+rule+"{\n";
for (var attribute in attributes)
{
newRule += "\t" + attribute + ": " + attributes[attribute] + ";\n";
}
newRule += "}\n";
//Inject it in the style element or create a new one if it doesn't exist
styleTag = $E('style[type="text/css"]') || new Element("style").setProperty('type','text/css').injectInside(document.head);
if(window.ie)
{
styleTag.styleSheet.cssText += newRule;
}
else
{
styleTag.appendText(newRule);
}
}
```
---
The most simple solution for [Separation of CSS and Javascrip](http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html) is to **remove your css class**
```
function jscss(a,o,c1,c2)
{
switch (a){
case 'swap':
o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): <-
o.className.replace(c1,c2);
break;
case 'add':
if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
break;
case 'remove':
var rep=o.className.match(' '+c1)?' '+c1:c1;
o.className=o.className.replace(rep,'');
break;
case 'check':
return new RegExp('\\b'+c1+'\\b').test(o.className)
break;
}
}
```
This example function takes four parameters:
`a`
defines the action you want the function to perform.
`o`
the object in question.
`c1`
the name of the first class
`c2`
the name of the second class
Possible actions are:
`swap`
replaces class c1 with class c2 in object o.
`add`
adds class c1 to the object o.
`remove`
removes class c1 from the object o.
`check`
test if class c1 is already applied to object o and returns true or false. | If something can be done completely in CSS I say keep it that way. If lack of javascript in the browser is a concern, then most of the time I show the entire page unaffected.
Say for instance I'm going to use jQuery to toggle an element when a checkbox is clicked. On page load I look at the checkbox and update the element accordingly. If javascript is not enabled the element will still appear and the site will still be usable. Just not as nice. | jQuery Graceful Degradation | [
"",
"javascript",
"jquery",
"css",
"backwards-compatibility",
""
] |
Is there something like python's interactive REPL mode, but for Java?
So that I can, for example, type `InetAddress.getAllByName( localHostName )` in a window, and immediately get results, without all this public static void nightmare() thing? | **edit**
Since Java 9 there's [JShell](https://en.wikipedia.org/wiki/JShell)
*Original answer follows*
You can also use [Groovy Console](http://www.groovy-lang.org/groovyconsole.html). It is an interactive console where you can do what you want. Since Groovy also includes classes from the core java platform, you'll be able to use those classes as well.
It looks like this:
 | Eclipse has a feature to do this, although it's not a loop. It's called a "Scrapbook Page". I assume the analogy is supposed to be that you have a scrapbook where you collect little snippets of code.
Anyway, to make it work, open a project in Eclipse (your Scrapbook Page is going to be associated with a project -- Eclipse likes it when projects own things).
Then:
1. In the project navigator window, select a folder that exists somewhere in your project.
2. Either select the menu File -> New -> Other, or hit Control-N.
3. Select Java -> Java Run/Debug -> Scrapbook Page.
4. Hit "Next", then give it a filename, then hit "Finish".
Now you have a scrapbook page. Type some code, like maybe this:
`System.out.println(System.getProperties());`
Then select the text with the mouse, and either hit Control-U or select "Execute" from the context menu. The code will run and the output will appear on the console.
You can also type an expression, select it, and select Display from the context menu. It'll evaluate the expression and print its type. For example, running Display on `1 + 2` will print `(int) 3`. | Is there something like python's interactive REPL mode, but for Java? | [
"",
"java",
"read-eval-print-loop",
""
] |
I have a DataGridView that I want to query using Linq (C# WinForm). I want to "count" rows where a certain criteria is met. For example,
```
variable1 = "count rows where ColumnBoxAge > 3 || < 5"
label1.Text = variable1
```
How to do this in C# WinForm using Linq? | I don't know if it could work but you can try this;
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 ||
c.Field<int>("ageColumn") < 5).Count();
```
Edit : Where instead of Select. | So your query is wrong! Try to put '&&' instead of '||';
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
c.Field<int>("ageColumn") < 5).Count();
```
Edit : Where instead of Select. | How to Query A DataGridView Using Linq | [
"",
"sql",
"sql-server",
"linq",
"datagridview",
""
] |
I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do
```
<li>
<%= Html.ActionLink("Modify Villa", "Modify", "Villa", new { @id = "1" })%></li>
public ActionResult Modify(string ID)
{
ViewData["Title"] =ID;
return View();
}
```
That's what a tutorial I followed recommended, but it's not working, it's also putting ?Length=5 at the end of the URL!
Here is the route I'm using, it's default
```
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
``` | Doesn't look like you are using the correct overload of ActionLink. Try this:-
```
<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>
```
This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-
```
<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>
``` | In MVC 4 you can link from one view to another controller passing the Id or Primary Key via
```
@Html.ActionLink("Select", "Create", "StudentApplication", new { id=item.PersonId }, null)
``` | ASP.NET MVC passing an ID in an ActionLink to the controller | [
"",
"c#",
"asp.net-mvc",
""
] |
I have a YouTube's player in the webpage. I need to change the video played by this player dynamicaly.
This is (relatively) easy using YouTube's chromeless player. It has method [`loadVideoById()`](http://code.google.com/apis/youtube/chromeless_player_reference.html#loadVideoById) which works perfectly. The problem is, that the chromeless player doesn't have any controls (play/pause, etc.). The [regular YouTube player](http://code.google.com/apis/youtube/js_api_reference.html#Functions) has all this, but it doesn't have the `loadVideoById()` method.
Is there any way to include the controls of regular player into chromeless player, or to implement `loadVideoById()` method in the regular player?
Thanks. | You can not do that, cause the calls in the "regular youtube player" have the VideoID in the URL instead as a parameter:
* Regular Video: <http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer>
* Chromeless: <http://www.youtube.com/apiplayer?enablejsapi=1>
Instead of that you can easily create your own function that changes the Embbebed SWF, i mean, say that you are using [swfobject](http://code.google.com/p/swfobject/) for the "Regular Player", then using [createSWF function](http://code.google.com/p/swfobject/wiki/api#swfobject.createSWF(attObj,_parObj,_replaceElemIdStr)) you will be able to replace the previous video for the actual one dynamically.
Hope this help you. | You can do this...
<http://code.google.com/apis/ajax/playground/#change_the_playing_video> | loadVideoById() in YouTube's regular player (not chromeless) | [
"",
"javascript",
"api",
"youtube",
""
] |
any generic way to trace/log values of all local variables when an exception occurs in a method?
(in C# 3) | Answer: Using PostSharp (Policy Injection), XTraceMethodBoundary attribute, override OnException .
this logs all the method input and return parameters types and values. I modified PostSharp to add a simple method to log parameters. not perfect but good enough
```
private static void TraceMethodArguments(MethodExecutionEventArgs eventArgs)
{
object[] parameters = eventArgs.GetReadOnlyArgumentArray();
if (parameters != null)
{
string paramValue = null;
foreach (object p in parameters)
{
Type _type = p.GetType();
if (_type == typeof(string) || _type == typeof(int) || _type == typeof(double) || _type == typeof(decimal))
{
paramValue = (string)p;
}
else if (_type == typeof(XmlDocument))
{
paramValue = ((XmlDocument)p).OuterXml;
}
else
{ //try to serialize
try
{
XmlSerializer _serializer = new XmlSerializer(p.GetType());
StringWriter _strWriter = new StringWriter();
_serializer.Serialize(_strWriter, p);
paramValue = _strWriter.ToString();
}
catch
{
paramValue = "Unable to Serialize Parameter";
}
}
Trace.TraceInformation("[" + Process.GetCurrentProcess().Id + "-" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + " Parameter: " + paramValue);
}
}
}
``` | You can't, basically. Reflection lets you get at *instance* (and static) variables but if you want to log local variables, you'll have to do so explicitly. It's possible that you could do a bit better using the profiling API, but that would be a pretty extreme step. | How to Trace all local variables when an exception occurs | [
"",
"c#",
".net",
"exception",
"logging",
""
] |
I want to change the behavior of a JavaScript used to display a banner, coming from a central source.
Today I include a script-tag inline in code, like this:
```
<script type="text/javascript" src="http://banner.com/b?id=1234"></script>
```
But what that returns is code which uses `document.write`, like this:
```
if(condition) {
document.write('<a href="..."><img src="..." /></a>')
}
```
I want to somehow override this `document.write` and maybe evaluate the returned code and instead use a JavaScript-framework to bind code to a div-element at DOM ready.
Is there a way to do that? Something like this?:
```
OnDOMReady() {
BindBanner(1234);
}
BindBanner(bannerId) {
var divTag = document.getElementById('banner_' + bannerId);
divTag.innerHtml = ManipulatedReturenedCode(bannerId);
}
```
Can JavaScript's prototyping handle something like this?
**Edit**: It has to be somewhat waterproof cross-platform, cross-browser-compatible, so I don't know if changing `document.write` is ok. | Yes, you can override document.write. Prototyping is not necessary, you can do it directly on the document object itself. I do this commonly for analysing malware, but it could certainly be used to capture ad script output, as long as the ad script doesn't do any particularly convoluted processing that would turn up the difference between document.write and whatever you replaced it with.
Here's a wrapper that loads an ad onload (slightly later than DOMReady):
```
<div id="advertgoeshere"></div>
<script type="text/javascript">
function rewrite(w) {
document.getElementById('advertgoeshere').innerHTML+= w;
}
window.onload= function() {
document.write= rewrite;
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://externalsite/ads.js';
document.body.appendChild(script);
}
</script>
``` | Have you tried overriding document.write? I don't have time to try it right now but give this a go:
```
var foo = document.write;
var bannerCode = '';
document.write = function(str) { bannerCode += str; };
```
Then include the script file, then do
```
document.write = foo;
alert(bannerCode);
``` | JavaScript Banner changing | [
"",
"javascript",
"html",
""
] |
I'm working on a windows client written in WPF with C# on .Net 3.5 Sp1, where a requirement is that data from emails received by clients can be stored in the database. Right now the easiest way to handle this is to copy and paste the text, subject, contact information and time received manually using an arthritis-inducing amount of ctrl-c/ctrl-v.
I thought that a simple way to handle this would be to allow the user to drag one or more emails from Outlook (they are all using Outlook 2007 currently) into the window, allowing my app to extract the necessary information and send it to the backend system for storage.
However, a few hours googling for information on this seem to indicate a shocking lack of information about this seemingly basic task. I would think that something like this would be useful in a lot of different settings, but all I've been able to find so far have been half-baked non-solutions.
Does anyone have any advice on how to do this? Since I am just going to read the mails and not send anything out or do anything evil, it would be nice with a solution that didn't involve the hated security pop ups, but anything beats not being able to do it at all.
Basically, if I could get a list of all the mail items that were selected, dragged and dropped from Outlook, I will be able to handle the rest myself!
Thanks!
Rune | I found a great [article](http://www.codeproject.com/KB/office/outlook_drag_drop_in_cs.aspx) that should do exactly what you need to.
**UPDATE**
I was able to get the code in that article working in WPF with a little tweaking, below are the changes you need to make.
Change all references from System.Windows.Forms.IDataObject to System.Windows.IDataObject
In the OutlookDataObject constructor, change
```
FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance);
```
To
```
FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("_innerData", BindingFlags.NonPublic | BindingFlags.Instance);
```
Change all DataFormats.GetFormat calls to DataFormats.GetDataFormat
Change the SetData implementation from
```
public void SetData(string format, bool autoConvert, object data)
{
this.underlyingDataObject.SetData(format, autoConvert, data);
}
```
TO
```
public void SetData(string format, object data, bool autoConvert)
{
this.underlyingDataObject.SetData(format, data, autoConvert);
}
```
With those changes, I was able to get it to save the messages to files as the article did. Sorry for the formatting, but numbered/bulleted lists don't work well with code snippets. | I found a lot of solutions suggesting you use the “FileGroupDescriptor” for all the file names and the “FileContents” on the DragEventArgs object to retrieve the data of each file. The “FileGroupDescriptor” works fine for the email message names, but “FileContents” returns a null because the implementation of the IDataObject in .Net cannot handle the IStorage object that is returned by COM.
David Ewen has a great explanation, excellent sample and code download that works great at <http://www.codeproject.com/KB/office/outlook_drag_drop_in_cs.aspx>. | Drag'n'drop one or more mails from Outlook to C# WPF application | [
"",
"c#",
"wpf",
"outlook",
"drag-and-drop",
""
] |
How would I go about dynamically allocating a multi-dimensional array? | If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:
```
typedef int dimensions[3][4];
dimensions * dim = new dimensions[10];
dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42;
delete [] dim;
```
instead of `10`, a runtime determined value can be passed. Since it's not part of the type operator new returns, that's allowed. This is nice if you know the number of columns, but want to keep the number of rows variable, for example. The typedef makes it easier to read the code. | How about using Boost.Multiarray ? I believe it answers your need quite well !
<http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/user.html#sec_introduction>
Here is an excerpt from the documentation page :
```
#include < boost/multi_array.hpp >
#include < cassert >
int main ()
{
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array< double, 3 > array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);
return 0;
}
``` | C++ Multi-dimensional Arrays on the Heap | [
"",
"c++",
"arrays",
"memory",
"heap-memory",
"allocation",
""
] |
Given the following class
```
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
```
I have overridden the `Equals` method because `Foo` represent a row for the `Foo`s table. Which is the preferred method for overriding the `GetHashCode`?
Why is it important to override `GetHashCode`? | Yes, it is important if your item will be used as a key in a dictionary, or `HashSet<T>`, etc - since this is used (in the absence of a custom `IEqualityComparer<T>`) to group items into buckets. If the hash-code for two items does not match, they may *never* be considered equal ([Equals](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals?view=netframework-4.8) will simply never be called).
The [GetHashCode()](https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8) method should reflect the `Equals` logic; the rules are:
* if two things are equal (`Equals(...) == true`) then they *must* return the same value for `GetHashCode()`
* if the `GetHashCode()` is equal, it is *not* necessary for them to be the same; this is a collision, and `Equals` will be called to see if it is a real equality or not.
In this case, it looks like "`return FooId;`" is a suitable `GetHashCode()` implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that `new Foo(3,5)` has a different hash-code to `new Foo(5,3)`):
In modern frameworks, the `HashCode` type has methods to help you create a hashcode from multiple values; on older frameworks, you'd need to go without, so something like:
```
unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
int hash = 13;
hash = (hash * 7) + field1.GetHashCode();
hash = (hash * 7) + field2.GetHashCode();
...
return hash;
}
```
Oh - for convenience, you might also consider providing `==` and `!=` operators when overriding `Equals` and `GetHashCode`.
---
A demonstration of what happens when you get this wrong is [here](https://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array/639098#639098). | It's actually very hard to implement `GetHashCode()` correctly because, in addition to the rules Marc already mentioned, the hash code should not change during the lifetime of an object. Therefore the fields which are used to calculate the hash code must be immutable.
I finally found a solution to this problem when I was working with NHibernate.
My approach is to calculate the hash code from the ID of the object. The ID can only be set though the constructor so if you want to change the ID, which is very unlikely, you have to create a new object which has a new ID and therefore a new hash code. This approach works best with GUIDs because you can provide a parameterless constructor which randomly generates an ID. | Why is it important to override GetHashCode when Equals method is overridden? | [
"",
"c#",
"overriding",
"hashcode",
""
] |
I've several textboxes. I would like to make the Enter button act as Tab. So that when I will be in one textbox, pressing Enter will move me to the next one. Could you please tell me how to implement this approach without adding any code inside textbox class (no override and so on if possible)? | Here is the code that I usually use.
It must be on KeyDown event.
```
if (e.KeyData == Keys.Enter)
{
e.SuppressKeyPress = true;
SelectNextControl(ActiveControl, true, true, true, true);
}
```
**UPDATE**
Other way is sending "TAB" key! And overriding the method make it so easier :)
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Enter))
{
SendKeys.Send("{TAB}");
}
return base.ProcessCmdKey(ref msg, keyData);
}
``` | You can write on the **keyDown** of any control:
```
if (e.KeyCode == Keys.Enter)
{
if (this.GetNextControl(ActiveControl, true) != null)
{
e.Handled = true;
this.GetNextControl(ActiveControl, true).Focus();
}
}
```
GetNextControl doesn't work on [Vista](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.getnextcontrol(VS.80).aspx).
To make it work with Vista you will need to use the code below to replace the this.GetNextControl...:
```
System.Windows.Forms.SendKeys.Send("{TAB}");
``` | How to make Enter on a TextBox act as TAB button | [
"",
"c#",
".net",
"winforms",
""
] |
We're a team of a designer and a programmer. Me, the programmer, is hopeless on design of all sorts, so the user interface of the game must be created by the designer. We were thinking of a main screen, where the character walks around, a small minimap in the top, an inventory section, etc.
All these things would have to be designed in a way that looks pretty, i.e nice graphics/buttons/colors etc. I'm assuming that the designer will create an outline of this interface in photoshop/illustrator, then send me the file in .png or .jpeg format and I'll implement it into the program, making sure the buttons all work, etc.
My question is, is this the correct method for doing this? Should he send me the interface's layout in a .png/.jpeg format, or send me only the buttons and I have to code the rest of the interface manually in java, putting the buttons/icons where they need to be, etc. If so, how can I do this? Any classes/frameworks that do this?
Any guidelines at all will be helpful. Thanks! | It really depends on a few things..Is it for J2ME or are you considering this for desktop (OpenGL/JOGL)?
For J2ME you have to really know a bit about making games for devices with constrained memory. J2ME comes with its own GameCanvas and Sprite related classes that you can utilise. I Would recommend you read up on J2ME game development either through google or buy a book. While there are 3D libraries for the J2ME environment, I have never been impressed by it.
For a desktop based game, I would recommend using some form of accelerated hardware based libraries for 2D or 3D based games. Bit of a steep learning curve but better in the long run. Plenty of libraries out there to help you get started(Jogl and JAva3D for example) You should look into using some called a scene graph, which will help you provide a good foundation to start from. Once again steep learning curve but much easier to maintain and develop with.
In regards to your design/implementation question, it seems you dont have much experience in this area.Generally graphic designers/UI interaction designer will have a better understanding of how to provide an interface for the game. They will generally develop a mock of some sort,you will implement it, a test will be done with user's and feedback will determine where you go from there. If you dont have some form of interaction designer, you or your designers will need to read up on it. Interaction through an interface,especially for games, is not an easy thing, and can make or break your game.
But it seems that you should definitely do some reading up on game architectures before proceeding to implementation phase if you do not have experience in this area. It will help you understand some theory and get a foundation before going ahead and building something which inevitably turns out to be completely wrong. | take a look at this:
<http://www.cs.qub.ac.uk/~P.Hanna/CSC207/lectures/lectures.htm> | How to design interface for a game in Java | [
"",
"java",
"swing",
"2d",
""
] |
I want to retrieve a set of records from a database, do a rs.next() and then assign the result of this to a variable to pass to a method that will use this record, in the same way that I would without assigning it to a variable and passing it to a method
is there any way to do this?
I'm using JAVA (1.5)
---
Thank you for all the answers
I do not want to pass the whole resultSet to a method, only the current row, but as I understand, it is not possible to do this | You want to assign the result of *rs.next()* to a variable?
I'm afraid you cannot do that. You can have a reference from that rs and process it in other method ( the same way you would without assign it to a var )
When you pass the rs as an argument to a method that is exactly what you're doing already.
```
while( rs.next() ) {
list.add( createFrom( rs ) );
}
...
public Object createFrom( ResultSet rs ) { // Here rs is a copy of the reference in the while above.
}
```
Did I get right your question? | No, that is not supported out of the box, but maybe the following idea may help you:
```
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map<String,Object> row = new HashMap<String,Object>();
for (int i = 1; i <= meta.getColumnCount(); ++i) {
row.put(meta.getColumnName(i), rs.getObject(i));
}
processRow(row);
}
```
The problem is, you need to cast the values from the `row`-map in `processRow()` and it will not work for all type/driver combinations (BLOBs, ...). | assigning a specific record in a ResultSet to a variable | [
"",
"java",
"jdbc",
"resultset",
""
] |
I have an app that display's the current time when a page opens. I would like that time to update every 30 seconds. I've read about prototype's Ajax.PeriodicalUpdater and it seems to be an answer. This is how I achieve the static time display on page load with php:
```
<tr>
<td>
<input class="standard" type="text" name="start_time"
value="<?php echo prev_end();?>">
<!--prev_end is last end time from database-->
</td>
<td>
<input class="standard" type="text" name="end_time"
value="<?php echo $now;?>">
<!--$now = date("G:i");-->
</td>
```
This is what I've attempted with prototype:
```
<script type="javascript">
new Ajax.PeriodicalUpdater("updater", "unow.php", {frequency : 30});
</script>
...
<tr>
<td>
<input class="standard" type="text" name="start_time"
value="<?php echo prev_end();?>">
</td>
<td>
<input id="updater" class="standard" type="text" name="end_time"
value="">
</td>
```
Where "unow.php" does this
```
<?php
$unow=date("G:i");
echo $unow;
?>
```
It seems that I don't need a callback to put the value from unow.php into the input "updater" since PeriodicalUpdater calls for an element id. What am I missing? | Unless you want your time output to always match the timezone of the server, you could do this very quickly with a bit of Javascript on the client side and skip contacting the server entirely.
```
<html>
<body onload="init();">
<div id=time></div>
</body>
</html>
<script type=text/javascript>
function init()
{
updateTime();
window.setInterval(updateTime,30000);
}
function updateTime()
{
var time = document.getElementById('time');
time.innerText = new Date().toLocaleString();
}
</script>
``` | This can be accomplished without hitting up the server. Prototype's PeriodicalExecuter class encapsulates JavaScript's setInterval function, which allows you to run a JavaScript function every X seconds.
**time.html**
```
<html>
<head>
<title>Time</title>
<script type="text/javascript" src="time.js">
</head>
<body>
<span id="timeDisplay"></span>
</body>
</html>
```
**time.js**
```
document.observe("dom:loaded", function() {
new PeriodicalExecuter(updateTimeDisplay, 30);
});
updateTimeDisplay = function(pe) { // accepts the PeriodicalExecuter instance
var now = new Date();
$('timeDisplay').innerHTML = now.toString();
};
``` | Display Current Time each minute (with Prototype's Ajax.PeriodicalUpdater ?) | [
"",
"javascript",
"prototypejs",
""
] |
I want to insert multiple invisible watermarks into my JPEG pictures through C# code. That means that I need a .NET library that does this work and not some external batch application.
Any suggestions? | there is a port of image magick library to c# , and it can easily perform that operation for you... | Storing "invisible" data in pictures is known as "steganography". A Google-search for "steganography .net" yields [this article](http://www.devx.com/dotnet/Article/22667/0/page/1) as its top hit - might prove useful. | Adding an invisible image watermark in C#? | [
"",
"c#",
".net",
"image",
"watermark",
"invisible",
""
] |
Something's slowing down my Javascript code in IE6 to where there's a noticeable lag on hover. It's fine in FF, so using firebug isn't that helpful. What tools are out there to help debug this in IE?
**A little more info:** I don't think there's actually any JS running on the objects that I'm mousing over. (At least none that I've put in.) Just css :hover stuff. Also, I've got both jquery and dojo running on the project, so who knows what they're doing in the background. | I think I've found the source of the slowdown for anyone who's curious: I'm using [bgiframe](http://plugins.jquery.com/project/bgiframe) to solve the IE6 select box z-index problem ([discussed elsewhere](https://stackoverflow.com/questions/224471/iframe-shimming-or-ie6-and-below-select-z-index-bug) on SO). | Just a tip of what that "something" could be...
**String concatenation** in IE is (or at least was when I [tested](http://forums.thedailywtf.com/forums/p/8931/169331.aspx)) very slow. Opera finished after 0.2s, Firefox after 4.1s and Internet Explorer 7 still hadn’t finished after 20 **minutes**!!!
Don't do:
```
for (var i=0, i < 200; i++) { s = s + "something";}
```
Instead, temporarily use an array, and then join it:
```
var s=[];
for (var i=0; i < 200; i++) s.push("something");
s=s.join("");
``` | How to find slow-down in Javascript in IE6 | [
"",
"javascript",
"debugging",
"internet-explorer-6",
""
] |
Ok, I have the following structure. Basically a plugin architecture
```
// assembly 1 - Base Class which contains the contract
public class BaseEntity {
public string MyName() {
// figure out the name of the deriving class
// perhaps via reflection
}
}
// assembly 2 - contains plugins based on the Base Class
public class BlueEntity : BaseEntity {}
public class YellowEntity : BaseEntity {}
public class GreenEntity : BaseEntity {}
// main console app
List<BaseEntity> plugins = Factory.GetMePluginList();
foreach (BaseEntity be in plugins) {
Console.WriteLine(be.MyName);
}
```
I'd like the statement
```
be.MyName
```
to tell me whether the object is BlueEntity, YellowEntity or GreenEntity. The important thing is that the MyName property should be in the base class, because I don't want to reimplement the property in every plugin.
Is this possible in C#? | I think you can do it through GetType:
```
public class BaseEntity {
public string MyName() {
return this.GetType().Name
}
}
``` | ```
public class BaseEntity {
public string MyName() {
return this.GetType().Name;
}
}
```
"this" will point to the derived class, so if you were to do:
```
BaseEntity.MyName
"BaseEntity"
BlueEntitiy.MyName
"BlueEntity"
```
EDIT: Doh, Gorky beat me to it. | How to get the name of the class | [
"",
"c#",
"visual-studio-2008",
""
] |
Apparently I can't move files on different volumes using Directory.Move.
I have read that I have to copy each file individually to the destination, then delete the source directory.
Do I have any other option? | Regardless of whether or not Directory.Move (or any other function) performed the move between volumes, it would essentially be doing a copy and delete anyway underneath. So if you want a speed increase, that's not going to happen. I think the best solution would be to write your own reusable move function, which would get the volume label (C:,D:) from the to and from paths, and then either perform a move, or copy+delete when necessary. | To my knowledge there is no other way however deleting a directory has a catch: Read Only Files might cause a `UnauthorizedAccessException` when deleting a directory and all of its contents.
This recurses a directory and unsets all the read only flags. Call before `Directory.Delete`:
```
public void removeReadOnlyDeep(string directory)
{
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.ReadOnly) != 0)
{
File.SetAttributes(file, ~FileAttributes.ReadOnly);
}
}
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
removeReadOnlyDeep(dir);
}
}
``` | Moving files on different volumes in .NET | [
"",
"c#",
".net",
"file-io",
"directory-structure",
""
] |
When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class? | Static classes are automatically sealed, so people can't inherit and override their behavior.
That is the only real difference (unless there is something special in the IL)
So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.
I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values. | A static class can never be instantiated. No way, no how.
A non-static class with a private constructor but all static methods can be abused in various ways - inheritance, reflection, call the private constructor in a static factory - to instantiate the class.
If you never want instantiation, I'd go with the static class.
---
*Edit - Clarification for FosterZ's comment*
Say you have this utility class:
```
public class Utility
{
public static string Config1 { get { return "Fourty Two"; } }
public static int Negate(int x) { return -x; }
private Utility() { }
}
```
If another developer isn't clear on its intent, they could do this:
```
public class Utility
{
public static string Config1 { get { return "Fourty Two"; } }
public int Config2 { get; set; }
public static int Negate(int x) { return -x; }
private Utility() { }
/// Get an instance of Utility
public static Utility GetUtility()
{
return new Utility();
}
}
```
Now you have a Frankenstein class. Some of its features require instantiation and some don't. Maybe that's what you want but maybe it's not. You could prevent this with code review, but why not make your intentions explicit in code? Marking the class as `static` eliminates any possible confusion. You can't instantiate a static class or inherit from it. | Static Class Vs. Class with private constructor and all static properties and methods? | [
"",
"c#",
".net",
""
] |
Let's assume I'm a complete lazy bum and I don't want to invest the several dozen keystrokes needed for my own exception class (it's not utterly important which gets used, really). However, to pretend I'm following good practices here, I want a pre-existing one that best fits my situation.
**Problem:** I need to throw an exception when my class's constructor receives an object in its parameters that is not found within a given list I've built elsewhere.
Which exception class would be appropriate to throw for that? | `IllegalArgumentException` | Winner by Accuracy:
[java.lang.IllegalArgumentException](http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html) | Which Java exception should I use? | [
"",
"java",
"exception",
""
] |
I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.
The existing C application works fine but I want to have a single script I can maintain for all platforms. At the same time, I do not want to lose a lot of performance but am willing to lose some.
Startup cost of the script is very important. This script can be called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important.
So basically I'm looking for the best scripting languages that is:
* Cross platform.
* Capable of XML parsing and HTTP Posts.
* Low memory and low startup time.
Possible choices include but are not limited to: bash/ksh + curl, Perl, Python and Ruby. What would you recommend for this type of a scenario? | Because of your requirement for fast startup time and a calling frequency greater than 1Hz I'd recommend either staying with C and figuring out how to make it portable (not always as easy as a few ifdefs) or exploring the possibility of turning it into a service daemon that is always running. Of course this depends on how
Python can have lower startup times if you compile the module and run the .pyc file, but it is still generally considered slow. Perl, in my experience, in the fastest of the scripting languages so you might have good luck with a perl daemon.
You could also look at cross platform frameworks like gtk, wxWidgets and Qt. While they are targeted at GUIs they do have low level cross platform data types and network libraries that could make the job of using a fast C based application easier. | Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available. | Scripting language choice for initial performance | [
"",
"python",
"ruby",
"perl",
"bash",
"scripting-language",
""
] |
I have a database table with a large number of rows and one numeric column, and I want to represent this data in memory. I could just use one big integer array and this would be very fast, but the number of rows could be too large for this.
Most of the rows (more than 99%) have a value of zero. Is there an effective data structure I could use that would only allocate memory for rows with non-zero values and would be nearly as fast as an array?
Update: as an example, one thing I tried was a Hashtable, reading the original table and adding any non-zero values, keyed by the row number in the original table. I got the value with a function that returned 0 if the requested index wasn't found, or else the value in the Hashtable. This works but is slow as dirt compared to a regular array - I might not be doing it right.
**Update 2: here is sample code.**
```
private Hashtable _rowStates;
private void SetRowState(int rowIndex, int state)
{
if (_rowStates.ContainsKey(rowIndex))
{
if (state == 0)
{
_rowStates.Remove(rowIndex);
}
else
{
_rowStates[rowIndex] = state;
}
}
else
{
if (state != 0)
{
_rowStates.Add(rowIndex, state);
}
}
}
private int GetRowState(int rowIndex)
{
if (_rowStates.ContainsKey(rowIndex))
{
return (int)_rowStates[rowIndex];
}
else
{
return 0;
}
}
``` | I would expect that the map/dictionary/hashtable of the non-zero values should be a fast and economical solution.
In Java, using the Hashtable class would introduce locking because it is supposed to be thread-safe. Perhaps something similar has slowed down your implementation.
**--- update: using Google-fu suggests that C# Hashtable *does* incur an overhead for thread safety. Try a Dictionary instead.** | This is an example of a *sparse* data structure and there are multiple ways to implement such sparse arrays (or matrices) - it all depends on how you intend to use it. Two possible strategies are:
* Store only non-zero values. For each element different than zero store a pair (index, value), all other values are known to be zero by default. You would also need to store the total number of elements.
* Compress consecutive zero values. Store a number of (count, value) pairs. For example if you have 12 zeros in a row followed by 200 and another 22 zeros, then store (12, 0), (1, 200), (22, 0). | Data structure question | [
"",
"c#",
".net",
""
] |
Py3k [just came out](http://mail.python.org/pipermail/python-list/2008-December/518408.html) and has gobs of [neat new stuff](http://docs.python.org/3.0/whatsnew/3.0.html)! I'm curious, what are SO pythonistas most excited about? What features are going to affect the way you write code on a daily basis, or have you been looking forward to? | There are a few things I'm quite interested in:
* *Text and data* instead of *unicode and 8 bit*
* [Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132)
* [Function annotations](http://www.python.org/dev/peps/pep-3107/)
* Binary literals
* [New exception catching syntax](http://www.python.org/dev/peps/pep-3110/)
* A number of Python 2.6 features, eg: the *with* statement | I hope that [exception chaining](http://www.python.org/dev/peps/pep-3134/) catches on. Losing exception stack traces due to the antipattern presented below had been my pet peeve for a long time:
```
try:
doSomething( someObject)
except:
someCleanup()
# Thanks for passing the error-causing object,
# but the original stack trace is lost :-(
raise MyError("Bad, bad object!", someObject)
```
I know, I know, adding some context info to the original exception **and** preserving the original stack trace was possible, but it required a really ugly hack. Now you can (and **should!**) just:
```
raise MyError("Bad, bad object!", someObject) from original_exception
```
and easily get both of the above. So, as a part of my holy mission against lost stack traces:
Folks, don't forget the **from** clause when reraising exceptions! Thank you. | What features of Python 3.0 will change your everyday coding? | [
"",
"python",
"python-3.x",
""
] |
I'm the developer of twittertrend.net, I was wondering if there was a faster way to get headers of a URL, besides doing curl\_multi? I process over 250 URLs a minute, and I need a really fast way to do this from a PHP standpoint. Either a bash script could be used and then output the headers or C appliation, anything that could be faster? I have primarily only programmed in PHP, but I can learn. Currently, CURL\_MULTI (with 6 URLs provided at once, does an ok job, but I would prefer something faster?
Ultimately I would like to stick with PHP for any MySQL storing and processing.
Thanks,
James Hartig | I think you need a multi-process batch URL fetching daemon. PHP does not support multithreading, but there's nothing stopping you from spawning multiple PHP daemon processes.
Having said that, PHP's lack of a proper garbage collector means that long-running processes can leak memory.
Run a daemon which spawns lots of instances (a configurable, but controlled number) of the php program, which will of course have to be capable of reading a work queue, fetching the URLs and writing the results away in a manner which is multi-process safe; multiple procs shouldn't end up trying to do the same work.
You'll want all of this to run autonomously as a daemon rather than from a web server. Really. | I recently wrote a blog post on how to speed up curl\_multi. Basically I process each request as soon as it finishes and use a queue to keep a large number of requests going at once. I've had good success with this technique and am using it to process ~6000 RSS feeds a minute. I hope this helps!
<http://onlineaspect.com/2009/01/26/how-to-use-curl_multi-without-blocking/> | Better support for CURL with PHP and Linux | [
"",
"php",
"mysql",
"linux",
"curl",
"curl-multi",
""
] |
I hope someone could help me on this.
I want to add a month to a database date, but I want to prevent two jumping over month on those days at the end.
For instance I may have:
Jan 31 2009
And I want to get
Feb 28 2009
and not
March 2 2009
Next date would be
March 28 2009
Jun 28 2009
etc.
Is there a function that already perform this kind of operation in oracle?
**EDIT**
Yeap. I want to copy each month all the records with some status to the next ( so the user don't have to enter again 2,000 rows each month )
I can fetch all the records and update the date manually ( well in an imperative way ) but I would rather let the SQL do the job.
Something like:
```
insert into the_table
select f1,f2,f3, f_date + 30 /* sort of ... :S */ from the_Table where date > ?
```
But the problem comes with the last day.
Any idea before I have to code something like this?
```
for each record in
createObject( record )
object.date + date blabala
if( date > 29 and if februrary and the moon and the stars etc etc 9
end
update.... et
```
**EDIT:2**
Add months did the trick.
now I just have this:
```
insert into my_table
select f1, add_months( f2, 1 ) from my_table where status = etc etc
```
Thanks for the help. | Oracle has a built-in function [ADD\_MONTHS](http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/functions5a.htm) that does exactly that:
```
SQL> select add_months(date '2008-01-31',1) from dual;
ADD_MONTHS(
-----------
29-FEB-2008
SQL> select add_months(date '2008-02-29',1) from dual;
ADD_MONTHS(
-----------
31-MAR-2008
``` | I think you're looking for LAST\_DAY:
<http://download.oracle.com/docs/cd/B28359_01/olap.111/b28126/dml_functions_2006.htm> | Add date without exceeding a month | [
"",
"sql",
"oracle",
"function",
"date",
"math",
""
] |
In my app I have 2 divs, one with a long list of products that can be dragged into another div (shopping cart). The product div has the overflow but it breaks prototype draggable elements. The prototype hacks are very obtrusive and not compatible with all browsers.
So I am taking a different approach, is it possible to have a scrollable div without using CSS `overflow:auto`? | Theres a css property to control that.
```
<div style="width:100px;height:100px;overflow:scroll">
</div>
```
<http://www.w3schools.com/Css/pr_pos_overflow.asp> | You can use a frame with content larger than its window. Might make it hard to pass JS events though. | Scrollable div without overflow:auto? | [
"",
"javascript",
"prototypejs",
"scriptaculous",
""
] |
I just recently noticed `Dictionary.TryGetValue(TKey key, out TValue value)` and was curious as to which is the better approach to retrieving a value from the Dictionary.
I've traditionally done:
```
if (myDict.Contains(someKey))
someVal = myDict[someKey];
...
```
unless I know it *has* to be in there.
Is it better to just do:
```
if (myDict.TryGetValue(somekey, out someVal)
...
```
Which is the better practice? Is one faster than the other? I would imagine that the Try version would be slower as its 'swallowing' a try/catch inside itself and using that as logic, no? | TryGetValue is slightly faster, because FindEntry will only be called once.
> How much faster? It depends on the
> dataset at hand. When you call the
> Contains method, Dictionary does an
> internal search to find its index. If
> it returns true, you need another
> index search to get the actual value.
> When you use TryGetValue, it searches
> only once for the index and if found,
> it assigns the value to your variable.
FYI: It's not actually catching an error.
It's calling:
```
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
```
ContainsKey is this:
```
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
``` | Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
**Edit:**
Ok, I understand your confusion so let me elaborate:
**Case 1:**
```
if (myDict.Contains(someKey))
someVal = myDict[someKey];
```
In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it
**Case 2:**
```
myDict.TryGetValue(somekey, out someVal)
```
In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method. | Retrieving Dictionary Value Best Practices | [
"",
"c#",
".net",
"dictionary",
""
] |
Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS.
What I'd like to model is:
A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.
My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done.
Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.
Any suggestions on the most efficient way to approach this on GAE? | Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.
Class A = Articles. Has a StringListProperty which can be queried on it's list elements
Class B = Tags. One entity per tag, also keeps a running count of the total number of articles using each tag.
Data modifications to A are accompanied by maintenance work on B. Thinking that counts being pre-computed is a good approach in a read-heavy environment. | counts being pre-computed is not only practical, but also necessary because the count() function returns a maximum of 1000. if write-contention might be an issue, make sure to check out the sharded counter example.
<http://code.google.com/appengine/articles/sharding_counters.html> | Data Modelling Advice for Blog Tagging system on Google App Engine | [
"",
"python",
"google-app-engine",
"data-modeling",
""
] |
How can I get a record id after saving it into database. Which I mean is actually something like that.
I have Document class (which is entity tho from DataBase) and I create an instance like
```
Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.SubmitChanges();
```
than what I want is to retrieve it's id value (docId) which is located in database and it's primary key also automatic number. One thing, there will be lots of users on the system and submits tons of records like that.
Thanks in advance everybody :) | Once you have run .SubmitChanges then doc.docId should be populated with the Id that was created on the database. | Like everyone has said you should be able to do something like this:
```
Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.SubmitChanges();
```
then get the Id with:
```
int ID = doc.docId;
``` | Get Id using LINQ to SQL | [
"",
"c#",
"asp.net",
"linq-to-sql",
".net-3.5",
""
] |
I am creating a pdf document using C# code in my process. I need to protect the docuemnt
with some standard password like "123456" or some account number. I need to do this without
any reference dlls like pdf writer.
I am generating the PDF file using SQL Reporting services reports.
Is there are easiest way. | > I am creating a pdf document using C#
> code in my process
Are you using some library to create this document? The [pdf specification](http://www.adobe.com/devnet/acrobat/pdfs/PDF32000_2008.pdf) (8.6MB) is quite big and all tasks involving pdf manipulation could be difficult without using a third party library. Password protecting and encrypting your pdf files with the free and open source [itextsharp](http://itextsharp.sourceforge.net/) library is quite easy:
```
using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
}
``` | It would be very difficult to do this without using a PDF library. Basically, you'll need to develop such library yourselves.
With help of a PDF library everything is much simpler. Here is a sample that shows how a document can easily be protected using [Docotic.Pdf library](https://bitmiracle.com/pdf-library/):
```
public static void protectWithPassword(string input, string output)
{
using (PdfDocument doc = new PdfDocument(input))
{
// set owner password (a password required to change permissions)
doc.OwnerPassword = "pass";
// set empty user password (this will allow anyone to
// view document without need to enter password)
doc.UserPassword = "";
// setup encryption algorithm
doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;
// [optionally] setup permissions
doc.Permissions.CopyContents = false;
doc.Permissions.ExtractContents = false;
doc.Save(output);
}
}
```
Disclaimer: I work for the vendor of the library. | Password protected PDF using C# | [
"",
"c#",
"pdf-generation",
""
] |
One doubt in MSSQL.
There are two tables in a databases.
Table 1 named Property contain
fields PRPT\_Id(int),PRPT\_Name(varchar), PRPT\_Status(bit)
Table 2 named PropertyImages contain fields PIMG\_Id(int),PIMG\_ImageName(varchar),PRPT\_Id(int),PIMG\_Status(bit)
These two tables follow a one-to-many relationship.
That means the each Property can have zero, one or more PropertyImages corresponding to it.
What is required is a query to display
PRPT\_Id, PRPT\_Name, ImageCount(Count of all images corresponding to a PRPT\_Id where PIMG\_Status is true. o if there arent any images), FirstImageName(if there are n images, the name of the first image in the image table corresponding to the PRPT\_Id with PIMG\_Status true. if there aren't any images we fill that with whitespace/blank) . another condition is that PRPT\_Status should be true.
Edit Note - Both the tables are having autoincremented integers as primary key.
So first Image name will be the name with MIN(PIMG\_Id), isn't that so?
I want the PIMG\_ImageName corresponding to the MIN(PIMG\_ID) in the resultset | Assuming that FirstImage means the one with the lowest Id, then this should be at least close enough to test to completion:
> SELECT
> PRPT\_Id,
> PRPT\_Name,
> ISNULL(pi1.ImageName, '') AS FirstImageName,
> COUNT(1) AS ImageCount
>
> FROM Property AS p
>
> LEFT JOIN PropertyImages AS pi
> ON p.PRPT\_Id = pi.PRPT\_Id
>
> LEFT JOIN PropertyImage AS pi1
> ON p.PRPT\_Id = pi1.PRPT\_Id
>
> LEFT JOIN PropertyImgage AS pi2
> ON p.PRPT\_Id = pi2.PRPT\_Id
> AND pi1.PIMG\_Id > pi2.PIMG\_Id
>
> WHERE PRPT\_Status = TRUE
> AND pi1.PIMG\_Status = TRUE
> AND pi2.PIMG\_ImageName IS NULL
The double LEFT JOIN assures that you get the first image record in pi1. If the "First" rule is different, then adjust this join accordingly.
This should be about as efficient as possible. It has no subqueries. | It seems that you have to write nested queries to display what you want.
If that's the case (I'm no SQL expert), I'd recommend you to start with the innermost query, then you go out until you reach the outermost (and final) query.
First, you have to retrieve the PIMGs and group them by PRPT.
```
SELECT PRPT_Id, COUNT(PIMG_Id) AS PRPT_ImageCount, MIN(PIMG_Id) AS PRPT_MinImage
FROM PropertyImages
GROUP BY PRPT_Id
```
That retrieves the PRPT\_Id's of the properties that do have associated images. However, you don't get any results for the properties that don't have any associated images.
After that, we will left join the Properties table with the previous query. The left join ensures that all the Properties will be retrieved, even if they don't appear in the results of the right query (that is, even if they don't have any associated images).
```
SELECT Properties.*, PRPT_ImageCount, PRPT_MinImage
FROM Properties LEFT JOIN (
SELECT PRPT_Id, COUNT(PIMG_Id) AS PRPT_ImageCount, MIN(PIMG_Id) AS PRPT_MinImage
FROM PropertyImages
GROUP BY PRPT_Id ) Temp ON ( Properties.PRPT_Id = Temp.PRPT_Id )
```
I hope that my SQL isn't wrong and that this post helps you.
Regards,
---
Edit:
```
SELECT Properties.*,
PRPT_ImageCount,
PRPT_MinImage,
PIMG_ImageName
FROM ( Properties LEFT JOIN
( SELECT PRPT_Id,
COUNT(PIMG_Id) AS PRPT_ImageCount,
MIN(PIMG_Id) AS PRPT_MinImage
FROM PropertyImages
GROUP BY PRPT_Id ) Temp1
ON ( Properties.PRPT_Id = Temp1.PRPT_Id ) ) Temp2 LEFT JOIN
PropertyImages ON ( PropertyImages.PIMG_Id = Temp2.PRPT_MinImage )
```
Now, I'm really unsure of my SQL. | Sql Query Linking Two Tables | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
In a bunch o' places in my code, I have something like this:
```
public Class mySpecialMethod() {
return MySpecialClass.class;
}
```
which causes the warning
> Class is a raw type. References to
> generic type Class should be
> parameterized.
But, if I replace
`Class`
with
`Class<? extends Object>`
the warning goes away.
Is this simple practice ok, or could it cause trouble later? | It's the correct thing to do only if there really is no common base class or interface that the Class object needs to represent.
Also `Class<?>` is effectively the same as `Class<? extends Object>`. | Yes, it's totally right.
It's a requirement that you specify the type. And if you can't, you have to specify the wildcard.
Further reading: [Java Language Specification: Parameterized Types](http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.5.1) | Is it good practice to replace Class with Class<? extends Object> to avoid warnings? | [
"",
"java",
"generics",
"warnings",
"raw-types",
""
] |
I'm learning C# by writing a home library manager.
I have a BookController that will store the books in a data structure and perform operations on them.
Does C# have a way of saving the data in the dictionary to a local file perhaps in an XML fashion to load later, or am I going to have to write it myself?
What is the best method of saving and loading this data available to C#? Just need pointed in a good direction. | Actually, C# (the language) doesn't know **anything** about serialization, but .NET (the framework) provides lots of ways... `XmlSerializer`, `BinaryFormatter`, `DataContractSerializer` (.NET 3.0) - or there are a few bespoke serialization frameworks too.
Which to use depends on your requirements; `BinaryFormatter` is simple to use, but burns assembly metadata information into the file - making it non-portable (you couldn't open it in Java, for example). `XmlSerializer` and `DataContractSerializer` are primarily xml-based, making it quite portable, but fairly large unless you compress it.
Some proprietary serializers are half-way between the two; [protobuf-net](http://code.google.com/p/protobuf-net/) is a binary formatter (so very dense data), but which follows a portable standard for the data format (Google's protocol buffers spec). Whether this is useful depends on your scenario.
Typical code (here using `XmlSerializer`):
```
XmlSerializer ser = new XmlSerializer(typeof(Foo));
// write
using (var stream = File.Create("foo.xml"))
{
ser.Serialize(stream, foo); // your instance
}
// read
using (var stream = File.OpenRead("foo.xml"))
{
Foo newFoo = (Foo)ser.Deserialize(stream);
}
``` | Look at [Serialization](http://www.codeproject.com/KB/cs/objserial.aspx) and the [ISerializable interface](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx)
It allows you to save an object's state in a portable form. | Saving Data Structures in C# | [
"",
"c#",
"serialization",
""
] |
I've done quite a bit of searching on this and haven't had much luck finding something cohesive. I'm a relatively new developer and have just started in my first professional development position. I know that I have a great deal to learn even in the realm of the basics. Based on listening to PodCasts, reading blogs, papers etc; I've come to understand that keeping separation of concerns, IOC, Dependency Injection in mind when designing and building software seems to be the right thing to do. I get the concepts at a VERY high level and want to approach what I do with this in mined as much as I can.
So, here's the rub. HOW the heck do I design stuff this way? I work on a team that has inherited a web based product that is very tightly coupled, very poorly documented and generally not an easy to maintain bit of sofware. Evryone seems to like the idea of removing some of this couple. They like the idea of developing automated tests (which from what I've read is easier to do with loosely coupled components). Nobody seems to know how to do it. I'm willing to take a stab at it, but I need guidance. Everything I've found always seems to talk about this stuff in a very high level way, or conversely, focuses on just a small piece of the whole. I'd like some guidance on a book, or series of tutorials, or videos, or SOMETHING that takes a somewhat real-world example and shows you how to apply these principles. Ideally, I'd LOVE to see something that says..."Take this order entry app, for example. THIS is how most people put it together today using standard ADO.NET DataSets, blah...blah...blah. NOW! If we apply the IOC principles to make this a loosely coupled project, here's what you do differently. Here's WHY you do it this way, and here's what you have to consider when you try to accomplish this."
I know this is a bit long winded, I'm just a bit frustrated that most of the comprehensive trainig material out there that I've found simply doesn't discuss this topic in a way that someone starting out can apply good practices from day one.
Thanks all for your time.
Steve | I was in the same situation and i bought these two books
(The PDF version to print out)
<http://www.manning.com/osherove/>
and
<http://www.manning.com/prasanna/> | You should definitely check out the IoC screencasts on [dimecasts.net](http://www.dimecasts.net/). They are very straight-forward and will help you to grasp some of the concepts. | IOC Design Resources | [
"",
"c#",
".net",
"dependency-injection",
"inversion-of-control",
"alt.net",
""
] |
Is it possible to just send a JPanel or any other component to the printer? Or do I have to implement all the drawing to the graphics object by hand?
I have tried to use the Print\* functions of the JPanel to print to the graphics object but the page that gets printed is blank. | Check out the Java printing API [and tutorial](http://java.sun.com/docs/books/tutorial/2d/printing/gui.html) along with JComponent.print(Graphics).
Here is a rudimentary class which will print any component which fits on 1 page (I can't take credit for this, I got the code from [Marty Hall's tutorial](http://courseweb.xu.edu.ph/courses/ics10/swing/Printing.htm)):
```
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
/**
* Generic component printer. This object allows any AWT or Swing component (or DCT system)
* to be printed by performing it pre and post print responsibilities.
* <p>
* When printing components, the role of the print method is nothing more than to scale the Graphics, turn off double
* buffering, and call paint. There is no particular reason to put that print method in the component being printed. A
* better approach is to build a generic printComponent method to which you simply pass the component you want printed.
* <p>
* With Swing, almost all components have double buffering turned on by default. In general, this is a great benefit,
* making for convenient and efficient painting. However, in the specific case of printing, it can is a huge problem.
* First, since printing components relies on scaling the coordinate system and then simply calling the component's
* paint method, if double buffering is enabled printing amounts to little more than scaling up the buffer (off-screen
* image) which results in ugly low-resolution printing like you already had available. Secondly, sending these huge
* buffers to the printer results in huge print spooler files which take a very long time to print. Consequently this
* object globally turns off double buffering before printing and turns it back on afterwards.
* <p>
* Threading Design : [x] Single Threaded [ ] Threadsafe [ ] Immutable [ ] Isolated
*/
public class ComponentPrinter
extends Object
implements Printable
{
// *****************************************************************************
// INSTANCE PROPERTIES
// *****************************************************************************
private Component component; // the component to print
// *****************************************************************************
// INSTANCE CREATE/DELETE
// *****************************************************************************
public ComponentPrinter(Component com) {
component=com;
}
// *****************************************************************************
// INSTANCE METHODS
// *****************************************************************************
public void print() throws PrinterException {
PrinterJob printJob=PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if(printJob.printDialog()) {
printJob.print();
}
}
public int print(Graphics gc, PageFormat pageFormat, int pageIndex) {
if(pageIndex>0) {
return NO_SUCH_PAGE;
}
RepaintManager mgr=RepaintManager.currentManager(component);
Graphics2D g2d=(Graphics2D)gc;
g2d.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
mgr.setDoubleBufferingEnabled(false); // only for swing components
component.paint(g2d);
mgr.setDoubleBufferingEnabled(true); // only for swing components
return PAGE_EXISTS;
}
// *****************************************************************************
// STATIC METHODS
// *****************************************************************************
static public void printComponent(Component com) throws PrinterException {
new ComponentPrinter(com).print();
}
} // END PUBLIC CLASS
``` | [This tutorial](http://java.sun.com/docs/books/tutorial/2d/printing/gui.html) mentions translating the `Graphics` object. Have you tried that? | Send a JPanel to the printer | [
"",
"java",
"swing",
"printing",
""
] |
I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.
How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?
Finally, would you say that one is more Pythonic than the other? | I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results.
Pyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a straightforward and readable example going very quickly, and it uses decorators to good effect for event handling. It also didn't force a particular program structure, which made it easy for me to mix in the physics modelling of Pymunk (<http://code.google.com/p/pymunk/>).
While it is based on OpenGL and you can use those features for special effects, I was able to do just fine without any knowledge of them.
It also works well with py2exe and py2app, which is important because a lot of people do not have a Python interpreter installed.
On the downside, there is less information about it on the web because it is newer, as well as fewer sample games to look at.
Also, it changed quite a bit from previous versions, so some of the tutorials which are there are now out of date (there is the "new style event loop"
and the Sprite class as major additions.)
I would recommend downloading the examples (there is a nice Asteroids clone called Astraea included) and seeing if you like the style. | ### License:
* Pygame: LGPL license
* Pyglet: BSD license
### Library dependencies:
* Pygame relies on SDL libraries heavily
* Pyglet is a pure python library with fewer dependencies, I think it requires better understanding of OpenGL
### Community:
* Pygame is around here for a long time, a lot of people used it
* Pyglet is a new lib
### Audience:
* Pygame is geared towards game development (cursors, sprites, joystick/gamepad support)
* Pyglet is more general purpose (though it has a Sprite class)
I found also this discussion on pyglet-users mailing list: [from pygame+pyopengl to pyglet](http://www.mail-archive.com/pyglet-users@googlegroups.com/msg00482.html)
Disclaimer: I did not use either yet, only tried some tutorials ;-) | Differences between Python game libraries Pygame and Pyglet? | [
"",
"python",
"pygame",
"pyglet",
""
] |
I have a java class which fires custom java events. The structure of the code is the following:
```
public class AEvent extends EventObject {
...
}
public interface AListener extends EventListener {
public void event1(AEvent event);
}
public class A {
public synchronized void addAListener(AListener l) {
..
}
public synchronized void removeAListener(AListener l) {
..
}
protected void fireAListenerEvent1(AEvent event) {
..
}
}
```
Everything works correctly, but I'd like to create a new subclass of A (call it B), which may fire a new event. I'm thinking of the following modification:
```
public class BEvent extends AEvent {
...
}
public interface BListener extends AListener {
public void event2(BEvent event);
}
public class B extends A {
public synchronized void addBListener(BListener l) {
..
}
public synchronized void removeBListener(BListener l) {
..
}
protected void fireBListenerEvent2(AEvent event) {
..
}
}
```
Is this the correct approach? I was searching the web for examples, but couldn't find any.
There are a few things I don't like in this solution:
1. `BListener` has two methods one uses `AEvent` the other uses `BEvent` as a parameter.
2. `B` class both has `addAListener` and `addBListener` methods. Should I hide addAListener with private keyword? **[UPDATE: it's not possible to hide with private keyword]**
3. Similar problem with `fireAListenerEvent1` and `fireBListenerEvent1` methods.
I'm using Java version 1.5. | I don't see a reason why `BListener` should extend `AListener`.
Do you really want to force everyone interested in `B` events to also implement `event1()`?
Also you can't add `addAListener()`, since a derived class can not reduce the visibility of a method that's present in the parent class. Also, you shouldn't need to, or you would violate the [Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle) (every B must be able to do everything an A can do).
And as a last remark, I'd make the `fire*()` methods protected. There's usually no reason at all to keep them public and reducing the number of public members keeps your public interface clean. | Don't use inheritence, it's not what you want and will lead to a brittle and difficult to change design. Composition is a more flexible and a better approach for the design. Always try to design interfaces as granular as possible because they should not be changed event. They are your contract with the rest of the system. If new functionality needs to be added the first option is to add more information to the event. If that's not appropriate, then you should design a new interface for delivering that event. This prevents having to change any existing code which isn't affected.
Here's my favorite pattern for this, I beleive it's commonly referred to as an Observer.
Make a new interface defining a methods for that event type (fooEvent() addFooEventListener() removeFooEventListener()). Implement this interface in the concrete class which generates these events. (I usually calls this something like SourcesFooEvent, FiresFooEvent, FooEventSource, etc)
If you want to reduce code duplication you can construct a helper class which handles registration of the listeners, stores them in a collection, and provides a fire method for publishing the events.
Generics can help here. First, a generic listener interface:
```
public interface Listener<T> {
void event(T event);
}
```
Next, a matching EventSource interface:
```
public interface EventSource<T> {
void addListener(Listener<T> listener);
}
```
Finally an abstract base class to quickly construct a helper class to handle registration of listeners and event dispatch:
```
public abstract class EventDispatcher<T> {
private List<Listener<T>> listeners = new CopyOnWriteArrayList<T>();
void addListener(Listener<T> listener) {
listeners.add(listener);
}
void removeListener(Listener<T> listener) {
listeners.remove(listener);
}
void fireEvent(T event) {
for (Listener<T> listener : listeners) {
listener.event(event);
}
}
}
```
You'd make use of the abstract EventDispatcher through encapsulation, allowing any other class to easily implement EventSource while not requiring it to extend any particular class.
```
public class Message {
}
public class InBox implements EventSource<Message> {
private final EventDispatcher<Message> dispatcher = new EventDispatcher<Message>();
public void addListener(Listener<Message> listener) {
dispatcher.addListener(listener);
}
public void removeListener(Listener<Message> listener) {
dispatcher.removeListener(listener);
}
public pollForMail() {
// check for new messages here...
// pretend we get a new message...
dispatcher.fireEvent(newMessage);
}
}
```
Hopefully this illustrates the nice balance between type safety (important), flexibility and code reuse. | Java Listener inheritance | [
"",
"java",
"inheritance",
"events",
"listener",
""
] |
I fail to understand why this code won't compile
```
ExecutorService executor = new ScheduledThreadPoolExecutor(threads);
class DocFeeder implements Callable<Boolean> {....}
...
List<DocFeeder> list = new LinkedList<DocFeeder>();
list.add(new DocFeeder(1));
...
executor.invokeAll(list);
```
The error msg is:
```
The method invokeAll(Collection<Callable<T>>) in the type ExecutorService is
not applicable for the arguments (List<DocFeeder>)
```
`list` is a `Collection` of `DocFeeder`, which implements `Callable<Boolean>` - What is going on?! | Just to expand on saua's answer a little...
In Java 5, the method was declared as:
```
invokeAll(Collection<Callable<T>> tasks)
```
In Java 6, the method is declared as:
```
invokeAll(Collection<? extends Callable<T>> tasks)
```
The wildcarding difference is very important - because `List<DocFeeder>` *is* a `Collection<? extends Callable<T>>` but it's *not* a `Collection<Callable<T>>`. Consider what would happen with this method:
```
public void addSomething(Collection<Callable<Boolean>> collection)
{
collection.add(new SomeCallable<Boolean>());
}
```
That's legal - but it's clearly bad if you can call `addSomething` with a `List<DocFeeder>` as it will try to add a non-DocFeeder to the list.
So, if you are stuck with Java 5, you need to create a `List<Callable<Boolean>>` from your `List<DocFeeder>`. | That code compiles perfectly fine with Java 6, but fails to compile with Java 5 giving
```
Foo.java:9: cannot find symbol
symbol : method invokeAll(java.util.List)
location: interface java.util.concurrent.ExecutorService
executor.invokeAll(list);
^
1 error
```
However changing the `list` like this:
```
Collection<Callable<Boolean>> list = new LinkedList<Callable<Boolean>>();
```
Makes it work on both Java 5 and Java 6. | invokeAll() is not willing to accept a Collection<Callable<T>> | [
"",
"java",
"executorservice",
"callable",
""
] |
if you browse the internet it's relatively easy to find code that modifies existing script maps (to switch between .NET versions, for example). However, the relatively obvious code to actually add or remove a script map doesn't seem to work. Has anyone succeeded in writing something that can add or delete a scriptmap in IIS 6? | Here you go:
<http://blogs.msdn.com/david.wang/archive/2004/12/02/273681.aspx> | Look here: [how to add new application mapping in iis](https://stackoverflow.com/questions/265613/how-to-add-new-application-mapping-in-iis) | Adding an extension mapping to IIS | [
"",
"c#",
"iis",
"wmi",
""
] |
My company develop web apps using combination of mod\_perl, axkit and apache.
We have tons of Perl modules, javascripts, etc, all in unix operating system.
Whenever I need to write a new function, I try to do some code reuse, but the thing is all the Perl modules and javascripts are scattered across folders.
i hate to write some code only later to discover that there's already a function which done the same thing, my current method involves trying to grep for the table name to see if there's a redundant function, but besides that, i'm pretty much will just give up and write a new function because i don't want to spend too much time searching and finding nothing.
Is there a better way to do this? Or even better, are there freeware tools that I can install which can help me properly manage all the functions and modules, and even allow developers to log comments, etc.
## EDIT
There is [this discussion](https://stackoverflow.com/questions/191614/how-to-detect-code-duplication-during-development) on detecting code duplication on c++ using tools, do we have anything like this for perl codes in unix platform?
thanks
~steve | **Organize** your source directory so that each functionality has only one place where it should be and it's easy to find something.
Make sure to share **naming convention** to prevent duplication.
**Design** your module so that they do one thing only - and do it well.
**Review** the code to make sure names and locations are correct.
Provide a efficient **search engine** based on a code indexer so that it's easy to look if there is already a function doing a peculiar task.
Don't underestimate the time to **generalize** an existing component so that it can effectively be reused.
**Document** the modules, with API documentation an/or unit-tests.
**Communicate** within the Team so that every one has a good grasp of what has possibly been already written, who has or knows who may have working on/used a module. | I trust you have some form of version control software ([svn](http://subversion.tigris.org/), [Mercurial](http://selenic.com/wiki/Mercurial), git, whatever but not VSS)? If you don't now is time to get one and start using it. That way, you have at least an idea of which modules you are using and where the code is. You can also use a [ctags-like](http://en.wikipedia.org/wiki/Ctags) to index all the modules you have written (or are using).
An IDE (as much as I dislike these) can also help finding code and refactor. | How can I efficiently manage Perl modules for code reuse? | [
"",
"javascript",
"perl",
"code-reuse",
"module-management",
""
] |
When reading data from the Input file I noticed that the ¥ symbom was not being read by the StreamReader. Mozilla Firefox showed the input file type as Western (ISO-8859-1).
After playing around with the encoding parameters I found it worked successfully for the following values:
```
System.Text.Encoding.GetEncoding(1252) // (western iso 88591)
System.Text.Encoding.Default
System.Text.Encoding.UTF7
```
Now I am planning on using the "Default" setting, however I am not very sure if this is the right decision. The existing code did not use any encoding and I am worried I might break something.
I know very little (OR rather nothing) about encoding. How do I go about this? Is my decision to use System.Text.Encoding.Default safe? Should I be asking the user to save the files in a particular format ? | Code page 1252 isn't quite the same as ISO-Latin-1. If you want ISO-Latin-1, use `Encoding.GetEncoding(28591)`. However, I'd expect them to be the same for this code point (U+00A5). UTF-7 is completely different (and almost never what you want to use).
`Encoding.Default` is *not* safe - it's a really bad idea in most situations. It's specific to the particular computer you're running on. If you transfer a file from one computer to another, who knows what encoding the original computer was using?
If you know that your file is in ISO-8859-1, then explicitly use that. What's producing these files? If they're just being saved by the user, what program are they being saved in? If UTF-8 is an option, that's a good one - partly because it can cope with the whole of Unicode.
I have an [article on Unicode](http://pobox.com/~skeet/csharp/unicode.html) and another on [debugging Unicode issues](http://pobox.com/~skeet/csharp/debuggingunicode.html) which you may find useful. | > The existing code did not use any encoding
It may not have explicitly specified the encoding, in which case the encoding probably defaulted to Encoding.UTF8.
The name Encoding.Default might give the impression that this is the default encoding used by classes such as StreamReader, but this is not the case: As Jon Skeet pointed out, Encoding.Default is the encoding for the operating system's current ANSI code page.
Personally I think this makes the property name Encoding.Default somewhat misleading. | StreamReader problem - Unknown file encoding (western iso 88591) | [
"",
"c#",
"encoding",
"character-encoding",
"inputstream",
"streamreader",
""
] |
Aloha
I have a method with (pseudo) signature:
```
public static T Parse<T>(string datadictionary) where T : List<U>
```
This doesn't build. How can I restrict the in the method to accept only generic List<> objects (which should of cource not contain T's but something else :)
I need to restrict the type of T because I need to call a method on it in this code. The type passed in is a custom collection (based on List).
```
public class MyCollection<T> : List<T> where T: MyClass, new()
{
public void Foo();
}
public static T Parse<T>(string datadictionary) where T : MyCollection<U>
{
T.Foo();
}
```
-Edoode | Well, you can have two type parameters:
```
public static T Parse<T, U>(string datadictionary) where T : List<U>
```
That way you'll also actually know what U is (in a compile-time manner)...
EDIT: Alternatively (and better), just specify the element type and change the return type:
```
public static List<T> Parse<T>(string datadictionary)
```
e.g.
```
List<int> data = Parse<int>(whatever);
```
Note that you may wish to change from `List<T>` to `IList<T>` or even a broader interface. | Assuming I read the question correctly, and you want to return `T` where `T : List<U>` (for some `T` and `U`)...
As an aside - subclassing `List<T>` isn't usually very useful... `List<T>` doesn't provide any useful virtual methods. Subclassing `Collection<T>` provides more flexibility. Of course, you can make your code not care, by simply coding against the `IList<T>` interface, perhaps adding `: new()` so you can create the list itself:
```
public static TList Parse<TList, TItem>(string datadictionary)
where TList : IList<TItem>, new() {...}
``` | How can I specifiy a generic collection as restriction in a generic method | [
"",
"c#",
"generics",
""
] |
We have a PageRoles xml file which contains the page path and the user role that can access that page.
We are maintaining a Dictionary in a static class, which gets loaded int static constructor for the class.
The class has a method CheckIfRoleAllowed that takes in a page path and returns a bool.
Each page call the CheckIfRoleAllowed on Page Init.
```
static class PageAccessChecker
{
static Dictionary<string, UserRoleType[]> _PageAccessPermissions;
static FileSystemWatcher _XmlWatcher;
static PageAccessChecker()
{
// Load page access permissions from xml
// Set FileSystemWatcher watcher to watch for changes
}
public static CheckIfRoleAllowed(string pagePath)
{
}
}
```
Would we be better off doing this using the singleton pattern?
If yes, why?
Kind regards. | You do use a singleton. Simply, there are 2 usual implementations for singletons, the other being instantiating the class and having a static member referencing this instance.
Your implementation makes calls simpler IMO :
```
PageAccessChecker.CheckIfRoleAllowed(path);
```
instead of:
```
PageAccessChecker._default.CheckIfRoleAllowed(path);
``` | I can see two advantages of using the singleton pattern (if implemented through, say, a static property):
1. you can delay loading the XML file until the first page is accessed.
2. you can check whether the XML file has changed on disk, and automatically reload it on the next access.
A disadvantage might be that you need to make access thread-safe using a lock. | Singleton vs Static Class for exposing data read from xml | [
"",
"c#",
".net",
"static",
"singleton",
""
] |
i want to get an ending html tag like `</EM>` only if somewhere before it i.e. before any previous tags or text there is no starting `<EM>` tag my sample string is
```
ddd d<STRONG>dfdsdsd dsdsddd<EM>ss</EM>r and</EM>and strong</STRONG>
```
in this string the output should be `</EM>` and this also the second `</EM>` because it lacks the starting `<EM>`. i have tried
```
(?!=<EM>.*)</EM>
```
but it doesnt seem to work please help thnks | I am not sure regex is best suited for this kind of task, since tags can always be nested.
Anyhow, a C# regex like:
```
(?<!<EM>[^<]+)</EM>
```
would only bring the second `</EM>` tag
Note that:
* `?!` is a negative look*ahead* which explains why both `</EM>` are found.
So... `(?!=<EM>.*)`xxx actually means capture xxx if it is not followed by `=<EM>.*`. I am not sure you wanted to include an `=` in there
* `?<!` is a negative look*behind*, more suited to what you wanted to do, but which would not work with java regex engine, since this look-behind regex does not have an obvious maximum length.
However, with a .Net regex engine, as tested on [RETester](http://regexlib.com/RETester.aspx), it does work. | You need a [pushdown automaton](http://en.wikipedia.org/wiki/Pushdown_automaton) here. Regular expressions aren't powerful enough to capture this concept, since they are equivalent to [finite-state automata](http://en.wikipedia.org/wiki/Finite_state_automaton), so a regex solution is strictly speaking a no-go.
That said, .NET regular expressions *do* have a pushdown automaton behind them so they can theoretically cope with such cases. If you really feel you need to do this with regular expressions rather than a formal HTML parser, take a glimpse [here](http://blog.stevenlevithan.com/archives/balancing-groups). | Regex - Match an end html tag if start tag is not present | [
"",
"c#",
".net",
"regex",
""
] |
I'm getting a NullPointerException in a Class from a 3rd party library. Now I'd like to debug the whole thing and I would need to know from which object the class is held. But it seems to me that I cannot set a breakpoint in a Class from a 3rd party.
Does anyone know a way out of my trouble? Of course I'm using Eclipse as my IDE.
Update: the library is open-source. | The most sure-fire way to do this (and end up with something that's actually useful) is to download the source (you say that it is open-source), and set up another "Java Project" pointing at that source.
To do that, get the source downloaded and unzipped somewhere on your system. Click "File"->"New"->"Java Project". In the next dialog, give it a project name and select "Create Project from Existing Source". Browse to the root location of the open source library.
Supposing that all the additional libraries that are required by the project and such are included in the project you downloaded, Eclipse will figure everything out and set the build path up for you.
You'll need to remove the open source jar from your project's build path, and add this new project to the build path of your project.
Now, you can just treat this as your code, and debug at will.
This gets around at least a couple of problems with other approaches:
1. You could "attach source" to the jar file, but if the jar file was compiled without debug information, this still won't work. If the jar file was compiled with debug information (`lines,source,vars`...see <http://java.sun.com/j2se/1.3/docs/tooldocs/win32/javac.html>, and the `-g` option).
2. You could add an "exception breakpoint" to see when the NullPointerException is raised, but that's a common exception, and may well get raised and dealt with many (hundreds of?) times prior to the one you're looking for. Plus, without the original source, you won't be able to really see much of anything about the code that is throwing the NullPointerException - the likelihood you'll be able to figure out what's wrong is pretty low. | You can easily set method breakpoints in 3rd party libraries without having the source. Just open the class (you'll get the "i-have-no-source" view). Open the outline, right-click on the method you want and click on `Toggle Method Breakpoint` to create the method breakpoint. | How to set a breakpoint in Eclipse in a third party library? | [
"",
"java",
"eclipse",
"debugging",
"breakpoints",
""
] |
I have a CheckedListBox, and I want to automatically tick one of the items in it.
The `CheckedItems` collection doesn't allow you to add things to it.
Any suggestions? | You need to call **[`SetItemChecked`](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.setitemchecked.aspx)** with the relevant item.
The [documentation for `CheckedListBox.ObjectCollection`](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.objectcollection.aspx) has an example which checks every other item in a collection. | This is how you can select/tick or deselect/untick all of the items at once:
```
private void SelectAllCheckBoxes(bool CheckThem) {
for (int i = 0; i <= (checkedListBox1.Items.Count - 1); i++) {
if (CheckThem)
{
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
else
{
checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
}
}
}
``` | How to programmatically check an item in a CheckedListBox in C#? | [
"",
"c#",
"winforms",
"checkedlistbox",
""
] |
I'm trying to open a file and create a list with each line read from the file.
```
i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
```
But this sample code gives me an error because of the `i+=1` saying that `index is out of range`.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile? | It's a lot easier than that:
```
List = open("filename.txt").readlines()
```
This returns a list of each line in the file. | I did it this way
```
lines_list = open('file.txt').read().splitlines()
```
Every line comes with its end of line characters (\n\r); this way the characters are removed. | Create a List that contain each Line of a File | [
"",
"python",
""
] |
Can someone give me some example code that creates a surface with a transparent background in pygame? | This should do it:
```
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
```
Make sure that the color depth (32) stays explicitly set else this will not work. | You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:
```
surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple
```
Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don't require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead. | How to make a surface with a transparent background in pygame | [
"",
"python",
"transparency",
"pygame",
""
] |
I have a PHP file, Test.php, and it has two functions:
```
<?php
echo displayInfo();
echo displayDetails();
?>
```
JavaScript:
```
<html>
...
<script type="text/javascript">
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
$("#response").html(data);
}
});
</script>
...
<div id="response">
</div>
</html>
```
It returns the response from jQuery. The response shows as `<a href=Another.php?>Link</a>`. When I click the Another.php link in `test.php`, it loads in another window. But I need it to load the same `<div> </div>` area without changing the content of `test.php`, since it has `displayInfo(), displayDetails()`. Or is it possible to load a PHP page inside `<div> </div>` elements?
How can I tackle this problem? | If I understand correctly, you'd like for the `a` link to cancel navigation, but fire the AJAX function?
In that case:
```
$("#mylink").click(function() {
$.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
$("#response").html(data);
});
return false;
});
``` | You could just use [MooTools](http://en.wikipedia.org/wiki/MooTools) and class [Request.HTML](http://mootools.net/docs/Request/Request.HTML). | How load a PHP page in the same window in jQuery | [
"",
"php",
"jquery",
"ajax",
""
] |
The question is in the title, why :
```
return double.IsNaN(0.6d) && double.IsNaN(x);
```
Instead of
```
return (0.6d).IsNaN && x.IsNaN;
```
I ask because when implementing custom structs that have a special value with the same meaning as NaN I tend to prefer the second.
Additionally the performance of the property is normally better as it avoid copying the struct on the stack to call the IsNaN static method (And as my property isn't virtual there is no risk of auto-boxing). Granted it isn't really an issue for built-in types as the JIT could optimize this easilly.
My best guess for now is that as you can't have both the property and the static method with the same name in the double class they favored the java-inspired syntax. (In fact you could have both as one define a get\_IsNaN property getter and the other an IsNaN static method but it will be confusing in any .Net language supporting the property syntax) | Interesting question; don't know the answer - but if it really bugs you, you could declare an extension method, but it would still use the stack etc.
```
static bool IsNaN(this double value)
{
return double.IsNaN(value);
}
static void Main()
{
double x = 123.4;
bool isNan = x.IsNaN();
}
```
It would be nicer (for the syntax) if C# had extension properties, but the above is about the closest you can get at the moment, but it should "inline" quite well anyway.
---
~~Update; thinking about it, there is another difference between static and instance; C# *always* calls instance methods with "`callvirt`" rather than "`call`", even if ther type is sealed an non-nullable. So perhaps there is a performance benefit from having it static? Luckily, extension methods still count as static, so you get to retain this behavior.~~ | Static Methods are thread safe, methods on primitives generally need to be thread safe to support threading in the platform (meaning at least safe from internal race conditions), instance methods take a managed pointer to a structure, meaning that the structure/primitive might be modified concurrently while the method executes, on the other hand static methods take a copy of the structure/primitive and therefore are safe from threading race conditions.
If the structure is intended to be thread safe, then the methods should be made instance methods only if they do atomic operations, else static methods should be chosen.
(As another option, instance methods that use locking could be used but they are more expensive than, copying)
Edit: @VirtualBlackFox I've prepared and example to show that instance methods on structures are not thread safe even on immutable structures:
```
using System;
using System.Threading;
namespace CA64213434234
{
class Program
{
static void Main(string[] args)
{
ManualResetEvent ev = new ManualResetEvent(false);
Foo bar = new Foo(0);
Action a = () => bar.Display(ev);
IAsyncResult ar = a.BeginInvoke(null, null);
ev.WaitOne();
bar = new Foo(5);
ar.AsyncWaitHandle.WaitOne();
}
}
public struct Foo
{
private readonly int val;
public Foo(int value)
{
val = value;
}
public void Display(ManualResetEvent ev)
{
Console.WriteLine(val);
ev.Set();
Thread.Sleep(2000);
Console.WriteLine(val);
}
}
}
```
The display Instance method prints:
0
5
even though the structure is immutable. For thread safe methods use static methods. | Why IsNan is a static method on the Double class instead of an instance property? | [
"",
"c#",
"oop",
""
] |
Does anyone have any suggestions as to how I can clean the body of incoming emails? I want to strip out disclaimers, images and maybe any previous email text that may be also be present so that I am left with just the body text content. My guess is it isn't going to be possible in any reliable way, but has anyone tried it? Are there any libraries geared towards this sort of thing? | In email, there is couple of agreed markings that mean something you wish to strip. You can look for these lines using [regular expressions](http://www.regular-expressions.info/). I doubt you can't really well "sanitize" your emails, but some things you can look for:
1. Line starting with "> " (greater than then whitespace) marks a quote
2. Line with "-- " (two hyphens then whitespace then linefeed) marks the beginning of a signature, see [Signature block on Wikipedia](http://en.wikipedia.org/wiki/Signature_block)
3. Multipart messages, boundaries start with **--**, beyond that you need to do some searching to separate the message body parts from unwanted parts (like base64 images)
As for an actual C# implementation, I leave that for you or other SOers. | A few obvious things to look at:
1. if the mail is anything but pure plain text, the message will be multi-part mime. Any part whose type is "image/\*" (image/jpeg, etc), can probably be dropped. In all likelyhood any part whose type is not "text/\*" can go.
2. A HTML message will probably have a part of type "multipart/alternative" (I think), and will have 2 parts, one "text/plain" and one "text/html". The two parts should be just about equivalent, so you can drop the HTML part. If the only part present is the HTML bit, you may have to do a HTML to plain text conversion.
3. The usual format for quoted text is to precede the text by a ">" character. You should be able to drop these lines, unless the line starts ">From", in which case the ">" has been inserted to prevent the mail reader from thinking that the "From " is the start of a new mail.
4. The signature should start with "-- \r\n", though there is a very good chance that the trailing space will be missing. | Is it possible to programmatically 'clean' emails? | [
"",
"c#",
".net",
"email",
"email-processing",
""
] |
I'm trying to use the library released by Novell (Novell.Directory.Ldap). Version 2.1.10.
What I've done so far:
* I tested the connection with an application ([LdapBrowser](http://www.mcs.anl.gov/~gawor/ldap/index.html)) and it's working, so its not a communication problem.
* It's compiled in Mono, but I'm working with Visual Studio. So created a project with the sources. I also included a reference to Mono.Security, because the project depended on it.
* I commented a call (freeWriteSemaphore(semId); ) in the error catching part of the connection, because it was throwing more exceptions. I checked what that call did, and its just a error tracing mechanism.
* I followed the basics steps provided in the documentation by Novell (<http://www.novell.com/coolsolutions/feature/11204.html>).
// Creating an LdapConnection instance
LdapConnection ldapConn= new LdapConnection();
ldapConn.SecureSocketLayer = ldapPort == 636;
//Connect function will create a socket connection to the server
ldapConn.Connect(ldapHost,ldapPort);
//Bind function will Bind the user object Credentials to the Server
ldapConn.Bind(userDN,userPasswd);
* Right now it's crashing at the Bind() function. I get the error 91.
So, has someone ever used this library and seen it work? If so, what did you do to make it work, is there some special configuration needed? Is there a way to make it work in .NET environment without Mono (I can have references to Mono dlls, but I don't want it to be installed on the server)?
(UPDATE)
The connection is on port 636, thus using SSL. I checked with WireShark the communication and compared with what I get from LDAP Browser. I've seen that the step where the SSL certicate is communicated, is not done by the LDAP library. So, what is the best way to make it do what its supposed to?
(UPDATE) I checked the documentation and it's indicating that it doesn't support SSL. <http://www.novell.com/coolsolutions/feature/11204.html>
> Authenticate to the LDAP server with
> LdapConnection.Bind(). We support only
> cleartext authentication. SSL/TLS
> support is yet to be added.
But the documentation date from 2004, and since then, many updates have been made. And there is a parameter in the library to define if the connection uses SSL. So now I'm confused.
(UPDATE) Found a more up-to-date documentation : <http://developer.novell.com/documentation//ldapcsharp/index.html?page=/documentation//ldapcsharp/cnet/data/bqwa5p0.html>. The way the SSL connection is made, is by registering the certificate on the server. The problem is that what I'm doing is not bound to a specific Novell server, so the certificate must be obtained dynamically. | I finally found a way to make this work.
First, theses posts helped me get on the right track : <http://directoryprogramming.net/forums/thread/788.aspx>
Second, I got a compiled dll of the Novell LDAP Library and used the Mono.Security.Dll.
The solution:
I added this function to the code
```
// This is the Callback handler - after "Binding" this is called
public bool MySSLHandler(Syscert.X509Certificate certificate, int[] certificateErrors)
{
X509Store store = null;
X509Stores stores = X509StoreManager.LocalMachine;
store = stores.TrustedRoot;
//Import the details of the certificate from the server.
X509Certificate x509 = null;
X509CertificateCollection coll = new X509CertificateCollection();
byte[] data = certificate.GetRawCertData();
if (data != null)
x509 = new X509Certificate(data);
//List the details of the Server
//if (bindCount == 1)
//{
Response.Write("<b><u>CERTIFICATE DETAILS:</b></u> <br>");
Response.Write(" Self Signed = " + x509.IsSelfSigned + " X.509 version=" + x509.Version + "<br>");
Response.Write(" Serial Number: " + CryptoConvert.ToHex(x509.SerialNumber) + "<br>");
Response.Write(" Issuer Name: " + x509.IssuerName.ToString() + "<br>");
Response.Write(" Subject Name: " + x509.SubjectName.ToString() + "<br>");
Response.Write(" Valid From: " + x509.ValidFrom.ToString() + "<br>");
Response.Write(" Valid Until: " + x509.ValidUntil.ToString() + "<br>");
Response.Write(" Unique Hash: " + CryptoConvert.ToHex(x509.Hash).ToString() + "<br>");
// }
bHowToProceed = true;
if (bHowToProceed == true)
{
//Add the certificate to the store. This is \Documents and Settings\program data\.mono. . .
if (x509 != null)
coll.Add(x509);
store.Import(x509);
if (bindCount == 1)
removeFlag = true;
}
if (bHowToProceed == false)
{
//Remove the certificate added from the store.
if (removeFlag == true && bindCount > 1)
{
foreach (X509Certificate xt509 in store.Certificates)
{
if (CryptoConvert.ToHex(xt509.Hash) == CryptoConvert.ToHex(x509.Hash))
{
store.Remove(x509);
}
}
}
Response.Write("SSL Bind Failed.");
}
return bHowToProceed;
}
```
And i used it in the binding process
```
// Create Connection
LdapConnection conn = new LdapConnection();
conn.SecureSocketLayer = true;
Response.Write("Connecting to:" + ldapHost);
conn.UserDefinedServerCertValidationDelegate += new
CertificateValidationCallback(MySSLHandler);
if (bHowToProceed == false)
conn.Disconnect();
if (bHowToProceed == true)
{
conn.Connect(ldapHost, ldapPort);
conn.Bind(loginDN, password);
Response.Write(" SSL Bind Successfull ");
conn.Disconnect();
}
quit = false;
```
The key elements are using the SSL Handler to dynamically obtain the Certificate, and using X509StoreManager.LocalMachine so that when the website is running its able to save and fetch the certificates. | I came looking for a solution to a similar problem. My bind command would fail as well while using the same code from Novell's website. The solution that worked for me was adding a dynamic Certificate Validation Call back. You can read about it [here](http://msdn.microsoft.com/en-us/library/exchange/dd633677%28v=exchg.80%29.aspx).
```
// Creating an LdapConnection instance
LdapConnection ldapConn = new LdapConnection();
ldapConn.SecureSocketLayer = true;
ldapConn.UserDefinedServerCertValidationDelegate += new
CertificateValidationCallback(MySSLHandler);
//Connect function will create a socket connection to the server
ldapConn.Connect(ldapHost, ldapPort);
//Bind function will Bind the user object Credentials to the Server
ldapConn.Bind(userDN, userPasswd);
// Searches in the Marketing container and return all child entries just below this
//container i.e. Single level search
LdapSearchResults lsc = ldapConn.Search("ou=users,o=uga",
LdapConnection.SCOPE_SUB,
"objectClass=*",
null,
false);
while (lsc.hasMore())
{
LdapEntry nextEntry = null;
try
{
nextEntry = lsc.next();
}
catch (LdapException e)
{
Console.WriteLine("Error: " + e.LdapErrorMessage);
// Exception is thrown, go for next entry
continue;
}
Console.WriteLine("\n" + nextEntry.DN);
LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
while (ienum.MoveNext())
{
LdapAttribute attribute = (LdapAttribute)ienum.Current;
string attributeName = attribute.Name;
string attributeVal = attribute.StringValue;
Console.WriteLine(attributeName + "value:" + attributeVal);
}
}
ldapConn.Disconnect();
Console.ReadKey();
}
public static bool MySSLHandler(Syscert.X509Certificate certificate,
int[] certificateErrors)
{
X509Store store = null;
X509Stores stores = X509StoreManager.CurrentUser;
//string input;
store = stores.TrustedRoot;
X509Certificate x509 = null;
X509CertificateCollection coll = new X509CertificateCollection();
byte[] data = certificate.GetRawCertData();
if (data != null)
x509 = new X509Certificate(data);
return true;
}
``` | Novell LDAP C# - Novell.Directory.Ldap - Has anybody made it work? | [
"",
"c#",
".net",
"ldap",
"novell",
""
] |
Is it possible to add a jQuery function so that a click in a table cell will invoke
a hidden <a href="javascript: ..." /> element (that is a descendant of the TD) ?
I've tried with
$('#table td').click(function() {
$(this).find('a').click();
});
An other variants, but to no luck.
--larsw | ```
<html>
<head></head>
<body>
<table border=1>
<tr>
<td>a1<a href=# onclick='alert("a1")' /></td>
<td>a2<a href=# onclick='alert("a2")' /></td>
</tr>
<tr>
<td>b1<a href=# onclick='alert("b1")' /></td>
<td>b2<a href=# onclick='alert("b2")' /></td>
</tr>
</table>
<script src="scripts/jquery-1.2.6.min.js" ></script>
<script>
$(function(){
$('table td').click(function(){ $(this).find('a').click()});
})
</script>
</body>
</html>
```
I have it working fine with that clip above. However see your jQuery selector has a # in front of it , which would be failing unless your table has an *id* of 'table'.
Having said that, there is probably a better way to do what your after than hidden a tags with javascript embedded in them. | Why don't you move your JavaScript code out of the `href` attribute and into your click event? jQuery was made to write unobtrusive JavaScript.
Edit:
No, but really, consider removing those hidden links in favor of unobtrusive JavaScript. Here are the relevant parts of Corey's example rewritten:
JS:
```
$(document).ready(function() {
$('table td').click(function(event) {
alert($(this).html())
})
})
```
HTML:
```
<table border="1">
<tr>
<td>a1</td>
<td>a2</td>
</tr>
<tr>
<td>b1</td>
<td>b2</td>
</tr>
</table>
``` | jQuery: invoke <a /> sub element of table cell | [
"",
"javascript",
"jquery",
"dhtml",
""
] |
Yesterday I thought it would be nice to implement my own Trigger in a WPF app. I created a class MyTrigger which inherited TriggerBase. TriggerBase is a public abstract class. So inheritance isn't a problem. But the constructors inside this class are marked internal. The compiler throws an error because the is no valid constructor. Why does anyone create a public class but marks the constructors as internal? | If you want the class to be visible, but only allow it to be subclassed within your own assembly. The subclasses may have public constuctors themselves - or they may be accessed with a factory.
I can't comment on whether that's a good design decision for TriggerBase in WPF, but it's at least reasonable in some situations. | One reason that I could think of is that the actual creation of new instances would be handled by another public class in the same assembly. This would force that you create the instance through this other class - possibly some sort of a factory pattern implementation. | internal constructor | [
"",
"c#",
".net",
""
] |
How do I return a constant from an sql statement?
For example how would I change the code below so "my message" would return if my (boolean expression) was true
```
if (my boolean expression)
"my message"
else
select top 1 name from people;
```
I am using ms sql 2000 | Did you try:
```
select 'my message';
``` | ```
select "my message" as message
``` | How do you return a constant from an sql statement? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2000",
""
] |
I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted.
My code goes as follows:
```
if( ! m_Container.empty() )
{
for( typedefedcontainer::iterator it = m_Container.begin();
it != m_Container.end();
++it )
{
if( ! ( SomeFunction( (*it), "test", "TEST!", false )) )
{
// If function returns false, delete object.
m_Container.erase( it );
AsyncResponseStore::iterator it = m_asyncResponses.begin();
}
}
}
```
But of course, when I erase an object I get an error : "Map / set iterator not incrementable". Can someone suggest a better way of doing this?
See:
[What happens if you call erase() on a map element while iterating from begin to end?](https://stackoverflow.com/questions/263945/what-happens-if-you-call-erase-on-a-map-element-while-iterating-from-begin-to-e) | It depends on the container. The list container supports deletion during enumeration by returning a new iterator from the erase method that represents the next item in the list. map doesn't support this.
A simple method for map is to accumulate the items you want to erase in a separate list, and then iterate over that list when you have finished processing the map to erase the items from the map. This assumes that you can defer the deletion until the iteration has completed. If not then you have no choice but the restart the iteration for each deletion. | If the container supports it (which I suspect yours doesn't, but the question title is generic so this may be useful to others if not you):
```
struct SomePredicate {
bool operator()(typedefedcontainer::value_type thing) {
return ! SomeFunction(thing, "test", "TEST", false);
}
};
typedefedcontainer::iterator it;
it = std::remove_if(m_Container.begin(), m_Container.end(), SomePredicate());
m_Container.erase(it, m_Container.end());
```
m\_Container must have an erase range method, which includes any Sequence or Associative Container. It does have to have a mutable iterator, though, and I just noticed that I originally misread the error message: it says "map / set iterator not incrementable". So I guess your container is a map or a set.
Note that the last three could be a truly marvellous one-liner, but this margin is too narrow to contain it.
Also that SomePredicate could have a constructor with parameters to store the additional parameters to SomeFunction, since in real life I guess they're non-constant.
You could actually get rid of SomePredicate entirely if you use boost:bind to construct the functor. Your one-liner would then be truly massive.
[Edit: Rob Walker correctly notes in his answer an assumption that I make here and that the question doesn't state, which is that all erasing can be deferred until after the iterate-and-test is done. If SomeFunction accesses m\_Container by a hidden route (e.g. a global, or because SomeFunction is actually a member function of this), and its results depend on the contents of the container, then my code may not be equivalent to the questioner's code. But I think my code is the "unless there's a reason not to" default.] | Best way to in situ delete an element | [
"",
"c++",
"stl",
"set",
""
] |
When developing with .NET 3.5 I naturally use LINQ for data access.
But for .NET 2.0 projects, what data access model is the best one to use? I tend to use TableAdapters mainly, but sometimes also write my own SQL depending on the situation. | Have you tried [NHibernate](http://nhibernate.org)? I haven't used it much myself, but my experience with its Java cousin was very positive.
There are other alternatives such as [LLBLGen](http://www.llblgen.com/defaultgeneric.aspx) as well.
It would be very hard to recommend an overall "best" solution without knowing more about the problem though. | [CodeSmith](http://www.codesmithtools.com/) is another good tool from what I've heard.
There's no such thing as the *best* DAL, only the *best* for the current solution.
We used an in-house one for many years which wasn't too bad but ultimately unmaintainable vs commercial products. | Best data access method in .NET 2.0 | [
"",
".net",
"sql",
"dao",
""
] |
Whenever I write a stored procedure for selecting data based on string variable (varchar, nvarchar, char) I would have something like:
```
procedure dbo.p_get_user_by_username(
@username nvarchar(256)
as
begin
select
u.username
,u.email
--,etc
from
sampleUserTable u
where
u.username = @username
end
```
So in other words to match the record I would have
```
u.username = @username
```
But sometimes I come across code that would use ***LIK***E in place of ***=***
```
u.username like(@username)
```
When would you use it?
Shouldn't that be used only when you need some wildcard matching?
**EDIT**
Thanks for the answers.
I think that I need to clarify that what I was really trying to ask was: if there could be a situation when it was preferred to use like in place of "=" for exact string matching. From the answers I could say that there would not be.
From my own experience even in situations when I need to ignore e.g case, and leading and ending spaces i would use ltrim, rtrim, lower on both strings and then "=". Thanks again for your input. | You are correct. There is no benefit in using LIKE unless you are doing wild card matching. In addition, using it without wildcard could lead to the use of an inefficient queryplan. | Sunny almost got it right :)
Run the following in QA in a default install of SQL2005
```
select * from sysobjects where name = 'sysbinobjs '
-- returns 1 row
select * from sysobjects where name like 'sysbinobjs '
-- returns 0 rows
```
So, LIKE does not match on trailing spaces, on the query plan side both perform almost equally, but the '=' join performs a tiny bit better.
An additional thing you MUST keep in mind when using LIKE is to escape your string properly.
```
declare @s varchar(40)
set @s = 'escaped[_]_%'
select 1 where 'escaped[_]_%' like @s
--Return nothing = BAD
set @s = '_e_s_c_a_p_e_d_[___]___%'
select 1 where 'escaped[_]_%' like @s escape '_'
--Returns 1 = GOOD
```
In general people do not use LIKE for exact matching, because the escaping issues cause all sorts of complications and subtle bugs, people forget to escape and there is a world of pain.
But ... if you want a real exact match that is efficient, LIKE can solve the problem.
Say, you want to match username to "sam" and do not want to get "Sam" or "Sam " and unfortunately the collation of the column is case insensitive.
Something like the following (with the escaping added) is the way to go.
```
select * from sysobjects
WHERE name = 'sysbinobjs' and name COLLATE Latin1_General_BIN LIKE 'sysbinobjs'
```
The reason you do a double match is to avoid a table scan.
However ....
I think the [varbinary casting trick](https://stackoverflow.com/questions/306906/how-do-i-perform-an-exact-string-match-is-a-non-case-sensitive-field#306918) is less prone to bugs and easier to remember. | Like vs. "=" for matching strings using SQL Server | [
"",
"sql",
"sql-server",
"like-keyword",
""
] |
I have a script that animates a small DIV popping up on the page. It all works fine in IE, and in FF if I remove the DOCTYPE, but when the DOCTYPE is XHTML/Transitional, in Firefox, the width does not change.
```
this.container.style.visibility = "visible";
alert("this.container.style.width before = " + this.container.style.width)
this.container.style.width = this.width;
alert("this.container.style.width after = " + this.container.style.width);
this.container.style.height = this.height;
```
In IE, and in FF with no DOCTYPE, the first alert says 0, and the second says 320 (which is the width set elsewhere in the code)
in FF, with the DOCTYPE to XHTML/Transitional, both alerts show 0. Any idea what's going on here? I'm thinking I may need to explicitly set positions on the DIVs in Transitional, but I'm not sure. | Have you tried setting:
```
this.container.style.visibility = "visible";
alert("this.container.style.width before = " + this.container.style.width);
this.container.style.width = this.width + 'px';
alert("this.container.style.width after = " + this.container.style.width);
this.container.style.height = this.height + 'px';
//Note the 'px' above
```
I find that trying to set a width/height of a number, without the units can cause issues. | * Using !important in CSS will override the above JavaScript and the width will not change. ie.
width: 16.5% !important;
* Should become:
width: 16.5%; | javascript style.width not working in firefox with transitional doctype | [
"",
"javascript",
"css",
"doctype",
"transitional",
""
] |
The question is in Java why can't I define an abstract static method? for example
```
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
``` | The `abstract` annotation to a method indicates that the method MUST be overriden in a subclass.
In Java, a `static` member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.) A `static` member may be **hidden**, but that is fundamentally different than **overridden**.
Since static members cannot be overriden in a subclass, the `abstract` annotation cannot be applied to them.
As an aside - other languages do support static inheritance, just like instance inheritance. From a syntax perspective, those languages usually require the class name to be included in the statement. For example, in Java, assuming you are writing code in ClassA, these are equivalent statements (if methodA() is a static method, and there is no instance method with the same signature):
```
ClassA.methodA();
```
and
```
methodA();
```
In SmallTalk, the class name is not optional, so the syntax is (note that SmallTalk does not use the . to separate the "subject" and the "verb", but instead uses it as the statemend terminator):
```
ClassA methodA.
```
Because the class name is always required, the correct "version" of the method can always be determined by traversing the class hierarchy. For what it's worth, I do occasionally miss `static` inheritance, and was bitten by the lack of static inheritance in Java when I first started with it. Additionally, SmallTalk is duck-typed (and thus doesn't support program-by-contract.) Thus, it has no `abstract` modifier for class members. | Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction. | Why can't static methods be abstract in Java? | [
"",
"java",
"abstract-class",
"static-methods",
""
] |
I have an application that uses a cron like job to update a set of data. The update process happens once a minute and doesn't last long. A servlet exposes this data set to the users. My problem is that during the update process, the servlet requests should block and wait for the process to complete.
In bottom line I have these two functions:
```
private void updateData() {
}
public List getData() {
}
```
The first function runs once a minute. The second one can be called any number of times simultaneously. When updateData runs, all calls of getData must wait for it to complete. One getData call shouldn't block subsequent calls of the same function. The updateData function has higher priority than the getData, i.e. when updateData is to run, it has to wait for all calls of getData to complete, but new calls shouldn't be allowed to start.
What synchronization mechanism should I use for a case like this? I am using a Java server, but I would be interested to know what solutions exist for other platforms as well. | Take a look at this article: [Read / Write Locks in Java](http://tutorials.jenkov.com/java-concurrency/read-write-locks.html)
The only drawback I can see in this example is the notifyAll() waking all waiting threads.
It does, however, give priority to write lock requests. | You can use a [ReadWriteLock](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html) instead of synchronize.
> A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
```
public void updateData() {
lock.writeLock().lock();
try {
/* do stuff. */
} finally {
lock.writeLock().unlock();
}
}
public List getData() {
lock.readLock().lock();
try {
/* process/return data. */
} finally {
lock.readLock().unlock();
}
```
} | How to synchronize requests for data with data update process? | [
"",
"java",
"synchronization",
""
] |
What's the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:
```
/**
* Returns an Iterator over the integers from first to first+count.
*/
Iterator<Integer> iterator(Integer first, Integer count);
```
Something like
```
(first..first+count).iterator()
``` | Straight-forward implementation of your homework:
```
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
ints.add(first + i);
}
``` | This implementation does not have a memory footprint.
```
/**
* @param begin inclusive
* @param end exclusive
* @return list of integers from begin to end
*/
public static List<Integer> range(final int begin, final int end) {
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return begin + index;
}
@Override
public int size() {
return end - begin;
}
};
}
```
## Edit:
In Java 8 and later you can simply say:
```
IntStream.range(begin, end).iterator() // returns PrimitiveIterator.OfInt
```
or if you need the boxed version:
```
IntStream.range(begin, end).boxed().iterator() // returns Iterator<Integer>
``` | Shortest way to get an Iterator over a range of Integers in Java | [
"",
"java",
"iterator",
""
] |
Last weekend I changed webhosts for my website. The host server I was on was a 32-bit OS and the one I moved to is 64-bit. Unexpectedly, some of my PHP scripts started giving incorrect results.
In my case the << and >> (bit shift) operations were the culprit. I ended up having to mask the result with 0xFFFFFFFF and then changing the result if negative for it to work as it did before.
Are there any other possible problems in my PHP scripts I should look for? | It's a high level language, so anything non-bit related (bitwise operators, bitshift) will be the same. | An integer may be 64bit instead of 32bit. There are some bizarre [cases](http://www.mysqlperformanceblog.com/2007/01/09/mysql-automatic-data-truncation-can-backfire/) where this may cause problems. | 32 to 64 bit "Gotchas" in PHP | [
"",
"php",
"32bit-64bit",
""
] |
I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.
Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful? | MSDN says:
> This delegate is used by the
> Array.ForEach method and the
> List.ForEach method to perform an
> action on each element of the array or
> list.
Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value. | Here is a small example that shows the usefulness of the Action delegate
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Action<String> print = new Action<String>(Program.Print);
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(print);
Console.Read();
}
static void Print(String s)
{
Console.WriteLine(s);
}
}
```
Notice that the foreach method iterates the collection of names and executes the `print` method against each member of the collection. This a bit of a paradigm shift for us C# developers as we move towards a more functional style of programming. (For more info on the computer science behind it read this: [http://en.wikipedia.org/wiki/Map\_(higher-order\_function)](http://en.wikipedia.org/wiki/Map_%28higher-order_function%29).
Now if you are using C# 3 you can slick this up a bit with a lambda expression like so:
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(s => Console.WriteLine(s));
Console.Read();
}
}
``` | Uses of Action delegate in C# | [
"",
"c#",
"lambda",
"delegates",
"action",
""
] |
I have a windows service written in c#. It has a timer inside, which fires some functions on a regular basis. So the skeleton of my service:
```
public partial class ArchiveService : ServiceBase
{
Timer tickTack;
int interval = 10;
...
protected override void OnStart(string[] args)
{
tickTack = new Timer(1000 * interval);
tickTack.Elapsed += new ElapsedEventHandler(tickTack_Elapsed);
tickTack.Start();
}
protected override void OnStop()
{
tickTack.Stop();
}
private void tickTack_Elapsed(object sender, ElapsedEventArgs e)
{
...
}
}
```
It works for some time (like 10-15 days) then it stops. I mean the service shows as running, but it does not do anything. I make some logging and the problem can be the timer, because after the interval it does not call the tickTack\_Elapsed function.
I was thinking about rewrite it without a timer, using an endless loop, which stops the processing for the amount of time I set up. This is also not an elegant solution and I think it can have some side effects regarding memory.
The Timer is used from the System.Timers namespace, the environment is Windows 2003. I used this approach in two different services on different servers, but both is producing this behavior (this is why I thought that it is somehow connected to my code or the framework itself).
Does somebody experienced this behavior? What can be wrong?
---
### Edit:
I edited both services. One got a nice try-catch everywhere and more logging. The second got a timer-recreation on a regular basis. None of them stopped since them, so if this situation remains for another week, I will close this question. Thank you for everyone so far.
---
### Edit:
I close this question because nothing happened. I mean I made some changes, but those changes are not really relevant in this matter and both services are running without any problem since then. Please mark it as "Closed for not relevant anymore". | Like many respondents have pointed out exceptions are swallowed by timer. In my windows services I use System.Threading.Timer. It has Change(...) method which allows you to start/stop that timer. Possible place for exception could be reentrancy problem - in case when tickTack\_Elapsed executes longer than timer period. Usually I write timer loop like this:
```
void TimeLoop(object arg)
{
stopTimer();
//Do some stuff
startTimer();
}
```
You could also `lock(...)` your main loop to protect against reentrancy. | unhandled exceptions in timers are swallowed, and they silently kill the timer
wrap the body of your timer code in a try-catch block | .NET Windows Service with timer stops responding | [
"",
"c#",
"windows-services",
"timer",
""
] |
I'm running on win2003 server, PHP 526, via the cmd-line.
I have a cmdline string:
```
$cmd = ' "d:\Prog Files\foo.exe" -p "d:\data path\datadir" ';
```
Trying to do this in php code
```
$out = `$cmd`; # note use of backticks AKA shell_exec
```
results in a failure by foo.exe as it interprets the -p arg as "d:\data".
However, the same `$cdm` string copied to the windows shell cmdline executes successfully.
How do I properly handle spaces in PHP `shell_exec`? | Use escapeshellarg() to escape your arguments, it should escape it with an appropriate combination of quotation marks and escaped spaces for your platform (I'm guessing you're on Windows). | Unlike Unix, which requires quotes within quotes to be escaped, Windows doesn't seem to work this way. How it keeps track of the quotes is beyond me, but this actually seems to work, despite all logic to the contrary:
$cmd = '" "C:\Path\To\Command" "Arg1" "Arg2" "';
$fp = popen($cmd, 'r');
$output='';
while ($l = fgets($fp, 1024))
$output.=$l;
I'm guessing command.exe is taking the command string total and nixing the (otherwise redundant) outside quotes. Without these outside quotes, DOS does some weird things. This solution is similar to post by user187383, but does away with the "cmd /c" which only obfuscates what's actually happening along with a mild performance cut, since cmd /c is implicit by the shell call in the first place! | How do I to properly handle spaces in PHP Shell_exec? | [
"",
"php",
"shell-exec",
""
] |
I have a function that looks something like this:
```
//iteration over scales
foreach ($surveyScales as $scale)
{
$surveyItems = $scale->findDependentRowset('SurveyItems');
//nested iteration over items in scale
foreach ($surveyItems as $item)
{
//retrieve a single value from a result table and do some stuff
//depending on certain params from $item / $scale
}
}
```
**QUESTION**: is it better to do a db query for every single value within the inner foreach or is it better to fetch all result values into an array and get the value from there? | One query that returns a dozen pieces of data is almost 12x faster than 12 queries that return 1 piece of data.
Oh, and NEVER EVER NEVER put a SQL inside a loop, it will always lead in a disaster.
Depending on how your app works, a new connection might be opened for each query, this is especially bad as every DB server has a limit on the number of connections. Then also realize this will happen for each user, so 50 queries with 5 users and you already have 250 queries at any given moment. But even if all the queries do share just 1 connection, you're taxing the DB server X times more, slowing it down for everything else, every page, because users are hogging the DB server on this page, and everybody has to share.
I've seen an entire application fail in the past because of this 1 design flaw, just don't do it. | I agree with the others -- and I'm the one who designed and coded the table-relationships API in Zend Framework that you're using!
The `findDependentRowset()` is useful if you *already* have a reference to the parent row, and you *might* need to fetch related rows. This function is not efficient in the least, compared to a query joining both tables. You shouldn't call `findDependentRowset()` in a loop, ever, if performance is a priority at all. Instead, write an SQL query consisting of a JOIN of both tables.
It's unfortunate in retrospect that Zend's goal for their Framework was simplicity of design, rather than performance.
If I had continued working at Zend, I would have tried to improve the Table interface with a convenient way to perform joined queries against related Zend\_Db\_Table objects. The solution implemented after I left the project is to build a Select object and pass it to `fetchAll()`, which is terribly ugly.
**edit:** In reply to your comment, I did my best to create a solution given a set of requirements. I feel fine about what I did. But Zend is an IDE tools company, so naturally their value is in convenience of coding, not runtime performance. "Rapid Application Development" can mean to develop rapid applications, or to develop applications rapidly. For a tools company, it means the latter. | PHP - Query single value per iteration or fetch all at start and retrieve from array? | [
"",
"php",
"database",
"performance",
""
] |
Suppose I have the following class:
```
public class TestBase
{
public bool runMethod1 { get; set; }
public void BaseMethod()
{
if (runMethod1)
ChildMethod1();
else
ChildMethod2();
}
protected abstract void ChildMethod1();
protected abstract void ChildMethod2();
}
```
I also have the class
```
public class ChildTest : TestBase
{
protected override void ChildMethod1()
{
//do something
}
protected override void ChildMethod2()
{
//do something completely different
}
}
```
I'm using Moq, and I'd like to write a test that verifies ChildMethod1() is being called when I call BaseMethod() and runMethod1 is true. Is it possible to create an implemention of TestBase with Moq, call BaseMethod() and verify that ChildMethod was called on the Moq implementation?
```
[Test]
public BaseMethod_should_call_correct_child_method()
{
TestBase testBase;
//todo: get a mock of TestBase into testBase variable
testBase.runMethod1 = true;
testBase.BaseMethod();
//todo: verify that ChildMethod1() was called
}
``` | You can also set the expectation/setup as Verifiable and do without a strict mock:
```
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce()
.Verifiable();
...
//make sure the method was called
testBase.Verify();
```
**Edit**
This syntax does not work in current versions of Moq. See [this question](https://stackoverflow.com/questions/3728873/verify-the-number-of-times-a-protected-method-is-called-using-moq) for how to do it as of at least 4.0.10827 | I figured out how to do this. You can can mock protected methods with Moq, and by making a strict mock, you can verify that they were called. Now I can test the base class without having to make any subclasses.
```
[Test]
public BaseMethod_should_call_correct_child_method()
{
//strict mocks will make sure all expectations are met
var testBaseMock = new Mock<TestBase>(MockBehavior.Strict);
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce();
var testBase = testBaseMock.Object;
testBase.runMethod1 = true;
testBase.BaseMethod();
//make sure the method was called
testBase.VerifyAll();
}
``` | Verifying protected abstract methods are called using Moq | [
"",
"c#",
"unit-testing",
"testing",
"moq",
""
] |
I've a need to add method that will calculate a weighted sum of worker salary and his superior salary. I would like something like this:
```
class CompanyFinanse
{
public decimal WeightedSumOfWorkerSalaryAndSuperior(Worker WorkerA, Worker Superior)
{
return WorkerA.Salary + Superior.Salary * 2;
}
}
```
Is this a good design or should I put this method somewhere else? I'm just staring designing project and think about a good, Object Oriented way of organize methods in classes. So I would like start from beginning with OOP on my mind. Best practice needed! | So it may be impossible to give you a complete answer about "best practices" without knowing more about your domain, but I can tell you that you may be setting yourself up for disaster by thinking about the implementation details this early.
If you're like me then you were taught that good OOD/OOP is meticulously detailed and involves [BDUF](http://en.wikipedia.org/wiki/BDUF). It wasn't until later in my career that I found out this is **the** reason so many projects become egregiously unmaintainable later on down the road. Assumptions are made about how the project might work, instead of allowing the design to emerge naturally from how the code is actually going to be used.
Simply stated: You need to being doing [BDD](http://en.wikipedia.org/wiki/Behavior_driven_development) / [TDD](http://en.wikipedia.org/wiki/Test-driven_development) (Behavior/Test Driven Development).
1. Start with a rough domain model sketched out, but avoid too much detail.
2. Pick a functional area that you want to get started with. Preferably at the top of the model, or one the user will be interacting with.
3. Brainstorm on expected functionality that the unit should have and make a list.
4. Start the TDD cycle on that unit and then refactor aggressively as you go.
What you will end up with is exactly what you do need, and nothing you don't (most of the time). You gain the added benefit of having full test coverage so you can refactor later on down the road without worrying about breaking stuff :)
I know I haven't given you any code here, but that is because anything I give you will probably be wrong, and then you will be stuck with it. Only you know how the code is actually going to be used, and you should start by writing the code in that way. TDD focuses on how the code should look, and then you can fill in the implementation details as you go.
A full explanation of this is beyond the scope of this post, but there are a myriad of resources available online as well as a number of books that are excellent resources for beginning the practice of TDD. These two guys should get you off to a good start.
* [Martin Fowler](http://martinfowler.com/)
* [Kent Beck](http://www.threeriversinstitute.org/) | I would either put it in the worker class, or have a static function in a finance library. I don't think a Finance object really makes sense, I think it would be more of a set of business rules than anything, so it would be static.
```
public class Worker {
public Worker Superior {get;set;}
public readonly decimal WeightedSalary {
get {
return (Superior.Salary * 2) + (this.Salary)
}
}
public decimal Salary {get;set;}
}
```
or
```
public static class Finance {
public static decimal WeightedSumOfWorkerSalaryAndSuperior(Worker WorkerA, Worker Superior) {
return WorkerA.Salary + Superior.Salary * 2; }
}
``` | Where should I put my first method | [
"",
"c#",
"oop",
"methods",
""
] |
Is there a way to record the screen, either desktop or window, using .NET technologies?
My goal is something free. I like the idea of small, low CPU usage, and simple, but I would consider other options if they created a better final product.
In a nutshell, I know how to take a screenshot in C#, but how would I record the screen, or area of the screen, as a video? | There isn’t any need for a third-party DLL. This simple method captures the current screen image into a .NET Bitmap object.
```
private Image CaptureScreen()
{
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
Bitmap target = new Bitmap(screenSize.Width, screenSize.Height);
using(Graphics g = Graphics.FromImage(target))
{
g.CopyFromScreen(0, 0, 0, 0, new Size(screenSize.Width, screenSize.Height));
}
return target;
}
```
I am sure you can figure out how to capture a smaller portion of the screen, if that is needed :-). | You can use the Windows media Encoder SDK to build a C# application to record the screen. There are in-built options to record the entire desktop, a particular window or a portion of the screen. | Record a video of the screen using .NET technologies | [
"",
"c#",
".net",
"video",
"capture",
"video-capture",
""
] |
I have two bitmaps, produced by different variations of an algorithm. I'd like to create a third bitmap by subtracting one from the other to show the differences.
How can this be done in .NET? I've looked over the Graphics class and all its options, including the ImageAttributes class, and I have a hunch it involves the color matrix or remap tables functionality.
Does anyone have a link to some example code, or can point me in the right direction? A google search doesn't reveal much, unless my google-fu is failing me today. | The real question is, what differences do you want to show? If you just need to operate on RGB color values, the best bet in my opinion is to just scan through both bitmaps and compare the Color values using GetPixel, and use SetPixel to generate your 'difference' bitmap. Perhaps you simply want to subtract the values and use those as the new Color value for the third bitmap. Or perhaps you want to calculate out the luminosity and use that. Even better, if you have three metrics for comparison, assign each one to the R G and B components of the color. I've used this approach for fractal colorization before.
There are other approaches, but with this one you are limited only to your imagination. It may not be the fastest approach, but it does not sound like performance is necessary for this scenario. | Check out this project. It is a motion detector made by Andrew Kirillov. He implements a couple of filters to get the differences between two pictures and uses that to calculate movements. It is really nice done and its easy to modify and use in your own application.
<http://www.codeproject.com/KB/audio-video/Motion_Detection.aspx> | How to subtract one bitmap from another in C#/.NET? | [
"",
"c#",
".net",
"image",
"subtraction",
""
] |
What does the `[string]` indexer of `Dictionary` return when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.
Do I get `null`, or do I get an exception? | If you mean the indexer of a `Dictionary<string,SomeType>`, then you should see an exception (`KeyNotFoundException`). If you don't want it to error:
```
SomeType value;
if(dict.TryGetValue(key, out value)) {
// key existed; value is set
} else {
// key not found; value is default(SomeType)
}
``` | As ever, the [documentation](http://msdn.microsoft.com/en-us/library/9tee9ht2.aspx) is the way to find out.
Under Exceptions:
```
KeyNotFoundException
The property is retrieved and key does not exist in the collection
```
(I'm assuming you mean `Dictionary<TKey,TValue>`, by the way.)
Note that this is different from the [non-generic Hashtable behaviour](http://msdn.microsoft.com/en-us/library/system.collections.hashtable.item.aspx).
To try to get a key's value when you don't know whether or not it exists, use [TryGetValue](http://msdn.microsoft.com/en-us/library/bb347013.aspx). | C#: What does the [string] indexer of Dictionary return? | [
"",
"c#",
"dictionary",
""
] |
In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:
```
$string = 'hello';
echo $string{0}; // h
echo $string[0]; // h
```
My question is, is there a benefit of one over the other? What's the difference between {} and []?
Thanks. | use `$string[0]`, the other method (braces) has been removed in PHP 8.0.
For [strings](https://www.php.net/manual/en/language.types.string.php):
> Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
And for [arrays](https://www.php.net/manual/en/language.types.array.php):
> Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0. | [**There is no difference.**](https://stackoverflow.com/a/26809707/632951) Owen's answer is outdated, the latest version of PHP Manual no longer states that it is deprecated [§](http://php.net/manual/en/language.types.string.php#language.types.string.substr):
> Characters within strings may be accessed and modified by specifying
> the zero-based offset of the desired character after the string using
> square array brackets, as in `$str[42]`. **Think of a string as an array
> of characters for this purpose**. [...]
>
> Note: Strings may also be accessed using braces, as in `$str{42}`, **for
> the same purpose**.
However it seems that more people/projects use `[]`, and that many people don't even know `{}` is possible. If you need to share your code publicly or with people who don't know the curly brace syntax, it **may** be beneficial to use `[]`.
UPDATED : accessing string characters with `{}` is deprecated, use `[]` instead. | PHP $string{0} vs. $string[0]; | [
"",
"php",
"string",
""
] |
So the chain of events is:
1. The user submits a form.
2. During the processing of the submission, there is a message generated, such as "Your record was saved."
3. The user is redirected to a new page, say the search results.
4. The new page needs to display the message.
So, the question is how to get the message from step 2 to step 3? This is only one simple example...there are many other much more complicated examples.
I am using PHP.
Needs:
* supports multiple messages and need to be formatted on the receiving machine as required
* messages can be added on the same page (such as within step 4)
* messages added from inside any function or object
Some options I have come up with:
* store in a session variable as an array and emptied after each display
* pass as a get or query parameter; can get annoying as you are constantly processing this and have to remember to get it; as it can get long, it could easily go over the max length of the query string
* store in the database on a per session basis (may not always be for a logged in user); this would require an extra insert on each page where they are added, possibly multiple, and an extra select on every page
Currently I have been storing the messages in the session in an array, but I'm wondering if there is a better way. I don't think the other 2 options above are very good.
**Edit:** I use 2 functions for the session method: AddStatusMsg() (adds an element to the array) and DisplayStatusMsg() (returns an HTML formatted message and empties the array). | I would recommend AGAINST storing these messages either in the database or in the session, for one simple reason: tabs. (Well, really, the stateless nature of HTTP.)
Think of a person who's got multiple tabs open of different sections of your website. This person performs some action and while that loads, switches to another tab and clicks on a link. If you're storing the messages in the session/database and the switched-to tab is a page that can display these messages too, the user has now entered a race condition where depending on which request the server responds to first, the messages may display where they were not intended.
Now, there are some situations where this legitimately might not matter, but it could also be extremely confusing in some cases.
Putting the messages in the request doesn't have to be as bad as it initially seems. Perhaps you could store all the messages you want to display in the database with a numeric (or, for bonus obfuscation, hash) ID, and pass a list of IDs in the query string. This keeps the query string short, and all you have to do is keep track of what ID corresponds to what message in your code. | I would stick with the session approach only perhaps adding support for this messaging system on the master page. You are on the right way as the all other approaches have a greater cost, of simplicity or performance.
I suppose you have a master page which is the template for all other pages. If you don't have it's a good reason to have one, so you don't need to take care of handling the displaying of the messages on every page you need it as long as you have a specific place to show them.
You can also use a specific div rendered by the master page for that and let the position be handled by the current page. If I understand correctly you need some kind of timing between the showing of the message and the user redirection to another page. This could be achieved using any AJAX library to show that div I said before and then redirecting to a new page.
I suggest taking a look into [jQuery](http://www.jquery.com). | How best to pass a message for the user between pages | [
"",
"php",
"session",
"message",
"status-message",
""
] |
I'm looking for an implementation of IDictionary with better performance of the standard BCL one.
I'm looking for something with constant lookup time that performs really well with large number of elements (>10K) and is more GC friendly.
Ps: No, I'm not able to write one by myself :) | I have not been able to benchmark the implementation, but an alternative - and more comprehensive - selection of generic collection classes is available from the University of Copenhagen here:
<http://www.itu.dk/research/c5/>
They offer a number of generic Dictionary implementations with differing backing solutions (Trees, HashTables etc.) It may be that one of these suits your needs. Performance was a prime factor in the development of this class library.
Of course, I'd recommend that you try the BCL generic Dictionary class first, as it will save you time and may suit your performance requirements just fine. | The BCL dictionary already performs with amortized constant time and can easily handle 10K elements.
You say it should be "more GC friendly" - what's bothering you about the current version?
Are you adding elements to the dictionary frequently? If so, create it with a large initial capacity to avoid churn. | Is there any implementation of IDictionary<K,V> with better performance of the BCL one? | [
"",
"c#",
".net",
"dictionary",
"hashtable",
""
] |
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
```
void divide(int dividend, int divisor, int& quotient, int& remainder);
```
A variation is to return one value and pass the other through a reference parameter:
```
int divide(int dividend, int divisor, int& remainder);
```
Another way would be to declare a struct to contain all of the results and return that:
```
struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
```
Is one of these ways generally preferred, or are there other suggestions?
Edit: In the real-world code, there may be more than two results. They may also be of different types. | For returning two values I use a `std::pair` (usually typedef'd). You should look at `boost::tuple` (in C++11 and newer, there's `std::tuple`) for more than two return results.
With introduction of structured binding in C++ 17, returning `std::tuple` should probably become accepted standard. | In C++11 you can:
```
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
```
In C++17:
```
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
```
or with structs:
```
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
``` | Returning multiple values from a C++ function | [
"",
"c++",
""
] |
I'm trying to find URLs in some text, using javascript code. The problem is, the regular expression I'm using uses \w to match letters and digits inside the URL, but it doesn't match non-english characters (in my case - Hebrew letters).
So what can I use instead of \w to match all letters in all languages? | Because `\w` only matches ASCII characters 48-57 ('0'-'9'), 67-90 ('A'-'Z') and 97-122 ('a'-'z'). Hebrew characters and other special foreign language characters (for example, umlaut-o or tilde-n) are outside of that range.
Instead of matching foreign language characters (there are so many of them, in many different ASCII ranges), you might be better off looking for the characters that delineate your words - spaces, quotation marks, and other punctuation. | The ECMA 262 v3 standard, which defines the programming language commonly known as JavaScript, stipulates that `\w` should be equivalent to [a-zA-Z0-9\_] and that `\d` should be equivalent to [0-9]. `\s` on the other hand matches both ASCII and Unicode whitespace, according to the standard.
JavaScript does not support the `\p` syntax for matching Unicode things either, so there isn't a good way to do this. You could match all Hebrew characters with:
```
[\u0590-\u05FF]
```
This simply matches any code point in the Hebrew block.
You can match any ASCII word character or any Hebrew character with:
```
[\w\u0590-\u05FF]
``` | Why does \w match only English words in javascript regex? | [
"",
"javascript",
"regex",
"hebrew",
""
] |
I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to another folder with a unique name.When I am getting this error
> The process cannot access the file 'D:\RD\dotnet\abc\abcimageupload\images\TempStorage\tempImage.jpg' because it is being used by another process
Can anyone tell me how to solve this. | Generally, I think your code should looking something like this.
```
WebClient wc = new WebClient();
wc.DownloadFile("http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");
FileStream fooStream;
using (fooStream = new FileStream("foo.png", FileMode.Open))
{
// do stuff
}
File.Move("foo.png", "foo2.png");
``` | I've had very good success using the tools from SysInternals to track which applications are accessing files and causing this kind of issue.
[Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) is the tool you want - set it up to filter the output to just files in the folder you're interested in, and you'll be able to see every access to the file.
Saves having to guess what the problem is. | Cant Access File because it is being used by another process | [
"",
"c#",
".net",
"exception",
""
] |
I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE
```
<!DOCTYPE video-faq SYSTEM "videofaq.dtd">
```
I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:
```
getClass().getResourceAsStream("videofaq.xml")
```
The XML is found correctly, but for the DTD in the same package, Xerces gives me a FileNotFoundException, and displays the path to the Tomcat startup script with "videofaq.dtd" appended to the end. What hints, if any, can I pass on to Xerces to make it load the DTD properly? | A custom EntityResolver will work, but you might be able to avoid having to create a custom class by setting a SystemID to allow the processor to "find" relative paths.
<http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=5>
> By providing a system identifier as a
> parameter to the StreamSource, you are
> telling the XSLT processor where to
> look for commonFooter.xslt. Without
> this parameter, you may encounter an
> error when the processor cannot
> resolve this URI. The simple fix is to
> call the setSystemId( ) method as
> follows:
```
// construct a Source that reads from an InputStream
Source mySrc = new StreamSource(anInputStream);
// specify a system ID (a String) so the
// Source can resolve relative URLs
// that are encountered in XSLT stylesheets
mySrc.setSystemId(aSystemId);
``` | When you do
```
getClass().getResourceAsStream("videofaq.xml")
```
It's not xerces you are calling and as such, when you give the stream to xerces, it can't know where the file is loaded from. It loads it from the application root path (which you have described).
A simple solution would be to specify the whole path in your xml file to the dtd.
Also, xerces seems to try multiple places. So you should have a look at the grammar caching mecanism or the entity resolvers (which are used in that order I think).
Xerces grammar doc: <http://xerces.apache.org/xerces2-j/faq-grammars.html>
Xerces features use-entity-resolver2: <http://xerces.apache.org/xerces2-j/features.html> | How do I include a DTD in an XML file that will be loaded using getResourceAsStream()? | [
"",
"java",
"xml",
"xerces",
""
] |
Suppose you're maintaining an API that was originally released years ago (before java gained `enum` support) and it defines a class with enumeration values as ints:
```
public class VitaminType {
public static final int RETINOL = 0;
public static final int THIAMIN = 1;
public static final int RIBOFLAVIN = 2;
}
```
Over the years the API has evolved and gained Java 5-specific features (generified interfaces, etc). Now you're about to add a new enumeration:
```
public enum NutrientType {
AMINO_ACID, SATURATED_FAT, UNSATURATED_FAT, CARBOHYDRATE;
}
```
The 'old style' int-enum pattern has no type safety, no possibility of adding behaviour or data, etc, *but it's published and in use*. I'm concerned that mixing two styles of enumeration is inconsistent for users of the API.
I see three possible approaches:
* Give up and define the new enum (`NutrientType` in my fictitious example) as a series of ints like the `VitaminType` class. You get consistency but you're not taking advantage of type safety and other modern features.
* Decide to live with an inconsistency in a published API: keep `VitaminType` around as is, and add `NutrientType` as an `enum`. Methods that take a `VitaminType` are still declared as taking an int, methods that take a `NutrientType` are declared as taking such.
* Deprecate the `VitaminType` class and introduce a new `VitaminType2` enum. Define the new `NutrientType` as an enum.
Congratulations, for the next 2-3 years until you can kill the deprecated type, you're going to deal with deprecated versions of every single method that took a `VitaminType` as an int and adding a new `foo(VitaminType2 v)` version of each. You also need to write tests for each deprecated `foo(int v)` method as well as its corresponding `foo(VitaminType2 v)` method, so you just multiplied your QA effort.
What is the best approach? | Personal opinion is that it's probably not worth the effort of trying to convert. For one thing, the "public static final int" idiom isn't going away any time soon, given that it's sprinkled liberally all over the JDK. For another, tracking down usages of the original ints is likely to be really unpleasant, given that your classes will compile away the reference so you're likely not to know you've broken anything until it's too late
(by which I mean
```
class A
{
public static final int MY_CONSTANT=1
}
class B
{
....
i+=A.MY_CONSTANT;
}
```
gets compiled into
```
i+=1
```
So if you rewrite A you may not ever realize that B is broken until you recompile B later.
It's a pretty well known idiom, probably not so terrible to leave it in, certainly better than the alternative. | How likely is it that the API consumers are going to confuse VitaminType with NutrientType? If it is unlikely, then maybe it is better to maintain API design consistency, especially if the user base is established and you want to minimize the delta of work/learning required by customers. If confusion is likely, then NutrientType should probably become an *enum*.
This needn't be a wholesale overnight change; for example, you could expose the old int values via the enum:
```
public enum Vitamin {
RETINOL(0), THIAMIN(1), RIBOFLAVIN(2);
private final int intValue;
Vitamin(int n) {
intValue = n;
}
public int getVitaminType() {
return intValue;
}
public static Vitamin asVitamin(int intValue) {
for (Vitamin vitamin : Vitamin.values()) {
if (intValue == vitamin.getVitaminType()) {
return vitamin;
}
}
throw new IllegalArgumentException();
}
}
/** Use foo.Vitamin instead */
@Deprecated
public class VitaminType {
public static final int RETINOL = Vitamin.RETINOL.getVitaminType();
public static final int THIAMIN = Vitamin.THIAMIN.getVitaminType();
public static final int RIBOFLAVIN = Vitamin.RIBOFLAVIN.getVitaminType();
}
```
This allows you to update the API and gives you some control over when to deprecate the old type and scheduling the switch-over in any code that relies on the old type internally.
Some care is required to keep the literal values in sync with those that may have been in-lined with old consumer code. | What's the best way to handle coexistence of the "int enum" pattern with java enums as an API evolves? | [
"",
"java",
"api",
"enums",
""
] |
I've got a JScript error on my page. I know where the error's happening, but I'm attempting to decipher the JScript on that page (to figure out where it came from -- it's on an ASPX page, so any number of user controls could have injected it).
It'd be easier if it was indented properly. Are there any free JScript reformatters for Windows? | You really should use Firebug or some similar debugging tool to actually *find* the problem, but, if you want to just format your JavaScript code, [here's a reformatter I found on Google](http://javascript.about.com/library/blformat.htm). | You can use [Aptana Studio](http://www.aptana.com/studio), its free and really good, and you can [customize your formatting preferences](http://www.aptana.com/docs/index.php/Customizing_your_formatting_preferences). | Reformatting JavaScript/JScript code? | [
"",
"javascript",
"pretty-print",
""
] |
I've noticed that boost.asio has a lot of examples involving sockets, serial ports, and all sorts of non-file examples. Google hasn't really turned up a lot for me that mentions if asio is a good or valid approach for doing asynchronous file i/o.
I've got gobs of data i'd like to write to disk asynchronously. This can be done with native overlapped io in Windows (my platform), but I'd prefer to have a platform independent solution.
I'm curious if
1. boost.asio has any kind of file support
2. boost.asio file support is mature enough for everyday file i/o
3. Will file support ever be added? Whats the outlook for this? | ## Has boost.asio any kind of file support?
Starting with (I think) Boost 1.36 (which contains Asio 1.2.0) you can use [boost::asio::]windows::stream\_handle or windows::random\_access\_handle to wrap a HANDLE and perform asynchronous read and write methods on it that use the OVERLAPPED structure internally.
User Lazin also mentions boost::asio::windows::random\_access\_handle that can be used for async operations (e.g. named pipes, but also files).
## Is boost.asio file support mature enough for everyday file i/o?
As Boost.Asio in itself is widely used by now, and the implementation uses overlapped IO internally, I would say yes.
## Will file support ever be added? Whats the outlook for this?
As there's no roadmap found on the [Asio](http://asio.sourceforge.net/) website, I would say that there will be no new additions to Boost.Asio for this feature. Although there's always the chance of contributors adding code and classes to Boost.Asio. Maybe you can even contribute the missing parts yourself! :-) | **boost::asio file i/o on Linux**
On Linux, asio uses the [`epoll`](http://linux.die.net/man/4/epoll) mechanism to detect if a socket/file descriptor is ready for reading/writing. If you attempt to use vanilla asio on a regular file on Linux you'll get an "operation not permitted" exception because [epoll does not support regular files on Linux](https://bugzilla.kernel.org/show_bug.cgi?id=15272).
The workaround is to configure asio to use the [`select`](http://linux.die.net/man/2/select) mechanism on Linux. You can do this by defining `BOOST_ASIO_DISABLE_EPOLL`. The trade-off here being [select tends to be slower than epoll](https://stackoverflow.com/questions/17355593/why-is-epoll-faster-than-select) if you're working with a large number of open sockets. Open a file regularly using `open()` and then pass the file descriptor to a [`boost::asio::posix::stream_descriptor`](http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/posix__stream_descriptor.html).
**boost::asio file i/o on Windows**
On Windows you can use [`boost::asio::windows::object_handle`](http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/windows__basic_object_handle.html) to wrap a `Handle` that was created from a file operation. See [example](http://theboostcpplibraries.com/boost.asio-platform-specific-io-objects). | What's the deal with boost.asio and file i/o? | [
"",
"c++",
"boost",
"file-io",
"boost-asio",
""
] |
I'm using PHP 5.2. I'd like to find a way to output a unique id for every object, so it's easy when looking over logs to see which objects are the same.
In Ruby, I'd just say object.object\_id to get Ruby's internal identifier for the object. There doesn't seem to be an obvious way to do this in PHP.
Is there is a built-in way of doing this? If there isn't, can you offer any other suggestions? | Use [`spl_object_hash()`](http://php.net/manual/en/function.spl-object-hash.php) for that.
It returns an unique identifier for each object instance, and not the name of the class, so it seems more suitable for you.
**Edit:**
For PHP < 5.2.x users, see [this answer](https://stackoverflow.com/a/19250740/179104). | There is currently no way to do this in PHP, as of version 5.3.6.
spl\_object\_hash() does not do what you want - because it recycles the identifiers when objects get deleted, this will lead to errors in (for example) an object-relational mapper trying to keep track of objects in a session.
The description at the top of the documentation page ("This function returns a unique identifier for the object. This id can be used as a hash key for storing objects or for identifying an object.") is wrong - the truth is revealed in the note on that page: "When an object is destroyed, its hash may be reused for other objects", or in other words, the function does *not* always return a unique identifier, and can *not* always be used for storing or identifying objects.
The technique demonstrated in [this comment](http://us.php.net/manual/en/function.spl-object-hash.php#94060) may work in some cases, but it not reliable and will not work consistently either, since attempting to access an undefined property will invoke the \_\_get() and \_\_set() magic methods, the results of which are unpredictable.
In conclusion, the short answer to your question (unfortunately) is "no" - there is no such method in PHP, and there is no way to write a method like this that will work consistently for any object.
If you would like to see this feature added to PHP, please vote and/or comment here:
<http://bugs.php.net/bug.php?id=52657> | How to find Object ID in PHP? | [
"",
"php",
"object",
""
] |
What would be the simplest way to create some graphical representations of the usage of electricity by month? | The best way is to use [JFreeChart](http://www.jfree.org/jfreechart/) to produce an image from your data, and then display the image in the jsp. | Easy solution for me was outputting numerical arrays in the backend and displaying with [flot](http://code.google.com/p/flot/) (google javascript library). All you need to do is generate your series of points
(e.g. something like ([1,0], [2,1.1], [3,1.4],[4, ] ... ). | JSP: Creating Graph | [
"",
"java",
"jsp",
"graphics",
"charts",
"graph",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.