instruction stringlengths 0 30k ⌀ |
|---|
The book 'Real-Time Collision Detection' by Christer Ericson (ISBN: 1-55860-732-3) is a recent (2005) and widely praised book which should give you some good answers.
It starts with a basic primer of some of the maths you will need to know, and then goes into various types of bounding volumes (spheres, axis-aligned bounding boxes, oriented bounding boxes) commonly used in collision detection.
Next up for discussion are numerous algorithms for detecting collisions between various combinations of primitives, such as lines, triangles, spheres, polygons, planes, bounding volumes etc.
Also of importance is the coverage of some of the major methods of spatial division and organisation of your objects (volume hierarchies, BSP trees, Octrees, etc.). This essentially speeds up collision detection, as it allows you to subdivide your objects so you can avoid unnecessary comparisons between objects (e.g. I know from my data structures that object A is too far away to hit object B, so I won't even do a distance check).
It also includes some coverage of how to actually check for collisions between moving objects (intervals, etc) but be aware that even though this is a fairly hefty book and covers the material well, it is for collision *detection*, not *resolution* or *response*. So it will help you determine whether two objects have collided, but not really what to do about it, i.e. how to resolve it. The intersection tests will usually give you the data you need to make such decisions, but in terms of the general problem of writing a *solver*, which uses collision detection routines to detect collisions and then decide what to do about them, this book does not cover that in depth. |
One potential thing you can do is contain the object rather than extend from the other class. This will give you the most flexibility in terms of exposing what you want to expose, but if you absolutely need the object to be of that type it is not the ideal solution (however you could expose the object from a getter).
Thus:
public class MyClass : BaseClass
{
// Your stuff here
}
Becomes:
public class MyClass
{
private BaseClass baseClass;
public void ExposeThisMethod()
{
baseClass.ExposeThisMethod();
}
}
Or:
public class MyClass
{
private BaseClass baseClass;
public BaseClass BaseClass
{
get
{
return baseClass;
}
}
} |
Hiding inherited members in C# |
|c#|polymorphism|silverlight|dependencyproperties|wpf| |
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using intellisense or using the classes in a visual designer.
These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about `ICustomTypeDescriptor` and `ICustomPropertyProvider`, but I'm pretty certain those can't be used in Silverlight.
It's not as much a functional issue as a usability issue. What should I do? |
|c#|wpf|silverlight|polymorphism|dependencyproperties| |
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using intellisense or using the classes in a visual designer.
These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about `ICustomTypeDescriptor` and `ICustomPropertyProvider`, but I'm pretty certain those can't be used in Silverlight.
It's not as much a functional issue as a usability issue. What should I do?
**update:**
Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the `new` operator. (I know, it's ridiculous) |
If you use Visual Studio you can use Visual C++ 2008 Feature Pack Release, this implements some of TR1, and includes regular expression parsing. [Get it][1]
[1]: http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en |
Some time ago I wrote a quick and dirty exe that would update the version #'s in an assemblyinfo.{cs/vb} - I also have used rxfind.exe (a simple and powerful regex-based search replace tool) to do the update from a command line as part of the build process. A couple of other helpfule hints:
1. separate the assemblyinfo into product parts (company name, version, etc.) and assembly specific parts (assembly name etc.). See [here](http://blog.darrenstokes.com/2007/12/17/ease-versioning-multiple-assemblies-by-splitting-up-assemblyinfo/)
2. Also - i use subversion, so I found it helpful to set the build number to subversion revision number thereby making it really easy to always get back to the codebase that generated the assembly (e.g. 1.4.100.1502 was built from revision 1502). |
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5.
write(MD5(SecretKey + ConfigFileText));
Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.
Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored.
A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.
If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.
**Update:** I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the users computer (which you *must* do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification, the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.
**Update:** The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances. |
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5.
write(MD5(SecretKey + ConfigFileText));
Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.
Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored.
A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.
If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.
**Update:** I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the users computer (which you *must* do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification, the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.
**Update:** The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances.
**UPDATE:** For a Credit Card system you might want to consider some real security. You should retain the services of a *security and cryptography consultant*. More information needs to be exchanged. They need to analyze your specific needs and risks.
Also, if you want security with .NET you need to first start with a really good .NET obfuscator ([just Google it][1]). A .NET assembly is way to easy to disassemble and get at the source could and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning.
[1]: http://www.google.com/search?hl=en&q=.NET%20obfuscator&aq=f&oq= |
I'm looking for "unbreakable" watermarks, so data stored in exif or image metadata are out.
I have found some interesting stuff on the web while waiting for replies here:
http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/
There is a master thesis that's fairly exhaustive about algorithms and their caracteristics (what they do and how unbreakable they are). I haven't got any time to read it in depth, but this stuff looks serious. There are algorithms that support JPEG compression, cropping, gamma correction or down scaling in some way. It's C, but I can port it to Python or use C libraries from Python.
However, it's from 2001 and I guess 7 years are a long time in this field :( Does anybody have some similar and more recent stuff? |
Adding an XML prolog before the doctype will throw IE6 into quirks rendering mode. ([See here.][1]) In fact, any space before the doctype will throw IE6 into quirks mode. This is not the case for IE7 and above.
I would generally recommend omitting the prolog and keeping the browser in standards mode.
[1]: http://www.quirksmode.org/css/quirksmode.html |
Adding an XML prolog before the doctype will throw IE6 into quirks rendering mode. ([See here.][1]) In fact, any space before the doctype will throw IE6 into quirks mode. This is not the case for IE7 and above. You can use `document.compatMode` ([example][2]) to have the browser tell you what mode it is using to do the rendering.
The IE blog entry on MSDN is referring to changes made to IE7 that allow IE7 to stay in standards mode when using the appropriate doctype even if it is preceded by an XML prolog.
I would generally recommend omitting the prolog and keeping the browser in standards mode; I think this will make your life easier moving forward.
[1]: http://www.quirksmode.org/css/quirksmode.html
[2]: http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx |
I have read about a class in .net 3.0 called <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx"target="_blank">Dispatcher</a> that allows you to put a thread in a loop and then call the method Invoke() using a delegate to execute a method using the thread. But this solution will not work if you cannot update to .Net 3.0. Another solution would be to host the third party dll in another application on the server and use some form of <a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.aspx"target="_blank">Remoting</a> to access it. But you may still have a problem with the Remoting because it behaves similar to IIS and will also pick a random thread to execute the code . To get around this, you could put a wrapper around the dll and use it to delegate the calls to the UI thread by using the Invoke() method of the form. |
I have read about a class in .net 3.0 called <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx">Dispatcher</a> that allows you to put a thread in a loop and then call the method Invoke() using a delegate to execute a method using the thread. But this solution will not work if you cannot update to .Net 3.0. Another solution would be to host the third party dll in another application on the server and use some form of <a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.aspx">Remoting</a> to access it. But you may still have a problem with the Remoting because it behaves similar to IIS and will also pick a random thread to execute the code . To get around this, you could put a wrapper around the dll and use it to delegate the calls to the UI thread by using the Invoke() method of the form. |
Yeah, it is messy, I can't think of a way to avoid it though.
You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table)
One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables.
|
> @Danial Jennings I read through the rules there and found: "An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).".
How does trying for Enum e in the constructor fail based on the quoted rule? Is it because being of type enum does not guarantee that the enums passed in are publicly visibly? This seems right. Is there a way for force this rule at compile time?
>@ bdukes You are exactly correct. I should have thought about that more.
It looks like run time type checking is my only option to make sure I am only mapping enums to other enums. |
These look very similar to extensions in Linq already:
//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate(
startingValue,
(x, y) => /* aggregate two subsequent values */ );
//takes a function that matches the Action<T> delegate
listInstance.ForEach(
x => /* do something with x */);
|
These look very similar to extensions in Linq already:
//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate(
startingValue,
(x, y) => /* aggregate two subsequent values */ );
//takes a function that matches the Action<T> delegate
listInstance.ForEach(
x => /* do something with x */);
Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using `ConvertAll<T>` or `Select<T>`.
|
I agree with Rob Cooper. Create a class to represent your configuration, and pass that into the constructor of your form. This will also allow you to define methods on your new "config" class like "saveSettings", "LoadSettings", etc. That in turn should keep the code more maintainable in general.
As an quick-and-dirty alternative, if you are saving these to a file somewhere, just pass the name of the file, and have your form read that at run-time.
The first option really is the way to go though, IMO. |
Phil, different parts of the application call each other using WCF. By "return exceptions serialized as XML," I meant that the return value of the function wold be an exception object. Success would be indicated by null.
I don't think that's the right option.
WCF fault contracts sound good, but I don't know anything about them. Checking google right now. |
It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.
Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.
Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like "1-2-3" or something.) |
|version-control|repository|plasticscm| |
You could also use a FULL OUTER JOIN and a CASE ... END statement on the diff_type column along with the aforementioned where clause in <http://stackoverflow.com/questions/30985/querying-2-tables-with-the-same-spec-for-the-differences#31043>
That would probably achieve the same results, but in one query. |
I rather liked elements from both Stu's and samjudson's solutions and worked them together into what I think is a usable combo:
public static string
Ordinal (this int number)
{
const string TH = "th";
var s = number.ToString ();
number %= 100;
if ((number >= 11) && (number <= 13))
{
return s + TH;
}
switch (number % 10)
{
case 1:
return s + "st";
case 2:
return s + "nd";
case 3:
return s + "rd";
default:
return s + TH;
}
}
|
Following a [Google](http://www.google.co.uk/search?hl=en&safe=off&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&hs=8ER&q=linebreak+in+varchar+sql&btnG=Search&meta=)...
Taking the code from the website:
CREATE TABLE CRLF
(
col1 VARCHAR(1000)
)
INSERT CRLF SELECT 'The quick brown@'
INSERT CRLF SELECT 'fox @jumped'
INSERT CRLF SELECT '@over the '
INSERT CRLF SELECT 'log@'
SELECT col1 FROM CRLF
Returns:
col1
-----------------
The quick brown@
fox @jumped
@over the
log@
(4 row(s) affected)
UPDATE CRLF
SET col1 = REPLACE(col1, '@', CHAR(13))
Looks like it can be done by replacing a placeholder with **CHAR(13)**
Good question, never done it myself :) |
1. Require SSL on the application
2. In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way. |
1. Require SSL on the application
2. In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way.
Note: Keep port 80 open for this - or there won't be a server to listen for requests to reidrect. |
1. Require SSL on the application
2. In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way.
Note: Keep port 80 open for this - or there won't be a server to listen for requests to redirect. |
Limiting traffic to SSL version of page only |
|iis|ssl|c#| |
We have an external service that is currently accessible via the http (port 80, non-SSL) and https (port 443, SSL) addresses.
What is the best way to limit connections to only the https address? Is it something we can do via IIS or does it have to be done via code.
Additional info: Regular ASP.NET web service (.asmx) running on IIS on Windows 2003 server. Service is built with C# on .NET 3.5.
Thanks,
Matt |
What is the best way to send html/image email? |
|html|email| |
Do you attach the images?
Use absolute urls?
How do you best avoid getting flagged as spam? |
@Chris Miller - What you've stated in your answer is factually inaccurate.
Windows message-style async, as available through WSAAsyncSelect, is indeed largely a workaround for lack of a proper threading model in Win 3.x days.
.NET Begin/End, however, is **not** using extra threads. Instead, it is using overlapped I/O, using the extra argument on WSASend / WSARecv, specifically the overlapped completion routine, to specify the continuation.
This means that the .NET style harnesses the Windows OS's async I/O support to **avoid** burning a thread by blocking on a socket.
Since threads are generally speaking expensive (unless you specify a very small stack size to CreateThread), having threads blocking on sockets will stop you from scaling to 10,000s of concurrent connections.
This is why it's important that async I/O be used if you want to scale, and also why .NET is **not**, I repeat, is **not**, simply "using threads, [...] just managed by the Framework". |
Well, this may not be very graceful... but you can retrieve the *current* focused control pretty easily. So you might consider setting up a timer that asks every 1/2 second or so "Where is the current focus?"... Then you can observe changes. Example Delphi code is below; it should be pretty easy to adapt, since the real work is in the Windows API calls.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Timer1: TTimer;
Label1: TLabel;
Edit1: TEdit;
Edit2: TEdit;
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
CurrentHandle, PreviousHandle : integer;
function GetCurrentHandle : integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
PreviousHandle := 0;
CurrentHandle := 0;
end;
function TForm1.GetCurrentHandle: integer;
var
activeWinHandle: HWND;
focusedThreadID : DWORD;
begin
//return the Windows handle of the currently focused control
Result := 0;
activeWinHandle := GetForegroundWindow;
focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);
if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin
try
Result := GetFocus;
finally
AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);
end;
end; //if attached
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
//give notification if the handle changed
CurrentHandle := GetCurrentHandle;
if CurrentHandle <> PreviousHandle then begin
Label1.Caption := 'Last focus change occurred @ ' + DateTimeToStr(Now);
end;
PreviousHandle := CurrentHandle;
end;
end.
|
Well, this may not be very graceful... but you can retrieve the *current* focused control pretty easily. So you might consider setting up a timer that asks every 1/2 second or so "Where is the current focus?"... Then you can observe changes. Example Delphi code is below; it should be pretty easy to adapt, since the real work is in the Windows API calls.
<snip>
function TForm1.GetCurrentHandle: integer;
var
activeWinHandle: HWND;
focusedThreadID : DWORD;
begin
//return the Windows handle of the currently focused control
Result := 0;
activeWinHandle := GetForegroundWindow;
focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);
if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin
try
Result := GetFocus;
finally
AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);
end;
end; //if attached
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
//give notification if the handle changed
//(this code gets fired by a timer)
CurrentHandle := GetCurrentHandle;
if CurrentHandle <> PreviousHandle then begin
Label1.Caption := 'Last focus change occurred @ ' + DateTimeToStr(Now);
end;
PreviousHandle := CurrentHandle;
end;
<snip> |
SSRS 2005 allows you to have multiple datasets for a report. Each dataset can refer to a different datasource, one can come from a SQL DB another can be a ODBC source etc.
In the report designer view in Visual Studio go to the "Data" tab and add new data sources pointing to your different databases. Once you are done, when designing the report for each element you have to explicitly specify which dataset the data is coming from.
If the above does not work, you can write managed code, refer to <http://msdn.microsoft.com/en-us/msdntv/cc540036.aspx> for more helpful information and videos. |
Check out [Canoo Web Test][1]. It is open source and built on the ANT framework.
I spent some time working with it for a graduate course on Software QA and it seems to be a pretty powerful testing tool.
[1]: http://webtest.canoo.com/webtest/manual/WebTestHome.html |
I still don't understand (probably because of my poor English).
You could try:
ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)
But it won't work for millions of records.
That why I suggested to use trigger which *fills* *separate* column with *human value*.
Moreover:
- built-in T-SQL functions are really
slow and Microsoft suggest to use
.NET functions instead.
- *human value* is constant so there is no point calculating it each time
when query runs.
|
How did you configure networking when you configured the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc. |
How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc. |
@[Brad Wilson](http://beta.stackoverflow.com/questions/35317/why-does-vista-complain-about-a-dead-process-when-i-use-cygwin-ssh-and-how-do-i#35324)
What does unexpectedly mean in this context? Does it mean it core dumped or just exited non-zero?
Everything works as I expect, so I don't really care if some sub-process is dying. How do I get Vista to ignore this error? |
Signing is used to uniquely identify an assembly. More details here: http://msdn.microsoft.com/en-us/library/ms247123(VS.80).aspx
In terms of best practice, it's fine to use the same key as long as the assemblies have different names. |
You could try as alternative (from the command prompt) ...
> cygpath -m c:\some\path
c:/some/path
As you can guess, it converts backslashes to slashes. |
While using short-circuiting for the purposes of optimization is often overkill, there are certainly other compelling reasons to use it. One such example (in C++) is the following:
if( pObj != NULL && *pObj == "username" ) {
// Do something...
}
Here, short-circuiting is being relied upon to ensure that `pObj` has been allocated prior to dereferencing it. This is far more concise than having nested `if` statements. |
I've been there. I used to have a job where I wrote code, did all the infrastructure stuff, wore the DBA hat, did user support, fixed the electric stapler when it jammed, and whatever else came up that might be remotely associated with IT. It was great! I learned a little about everything.
As far as the care and feeding of your database box, I'd recommend that you do the following:
Perform regular full backups.
Perform regular transaction log backups.
Monitor your backup jobs. There's a bunch of utilities out on the market that are relatively cheap that can automate this for you. In a small shop you're often too busy
to remember to check on them daily.
Test your backups. Do a drill. Restore an old copy of your most important databases. Prove to yourself that your backups are working and that you know how to
restore them properly. You'd be suprised how many people only think about this during their first real disaster.
Store backups off-site. With all the online backup providers out there today, there's not much excuse for not having an offsite backup.
Limit sa access to your boxes.
If your database platform supports it, use only role based security. Resist the temptation to have one-off user specific security.
The basic idea here is that if you restrict who has access to the box, you'll have fewer problems. Secondly, if your backups are solid, there are few things that come up that you won't be able to deal with effectively. |
Have you tried hard-coding the values just to see if background-colors are showing on the print-preview at all? I think it is a setting in the Browser. |
Is it not recommended to do this with stylesheets? You can change the media type in the LINK statement in your HTML, so when the page is printed, it will revert to the different style? |
> Since HTML is not a regular language
HTML isn't but HTML tags are and they can be adequatly described by regular expressions. |
Thread not waking up from Thread.Sleep() |
|.net|multithreading| |
We have a Windows Service written in C#. The service spawns a thread that does this:
private void ThreadWorkerFunction()
{
while(false == _stop) // stop flag set by other thread
{
try
{
openConnection();
doStuff();
closeConnection();
}
catch (Exception ex)
{
log.Error("Something went wrong.", ex);
Thread.Sleep(TimeSpan.FromMinutes(10));
}
}
}
We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors.
This has been running fine for months, but recently we've seen a few instances where it reports "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" then never ever comes back. The service can be left running for days but nothing more will be logged.
Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back? |
We have a Windows Service written in C#. The service spawns a thread that does this:
private void ThreadWorkerFunction()
{
while(false == _stop) // stop flag set by other thread
{
try
{
openConnection();
doStuff();
closeConnection();
}
catch (Exception ex)
{
log.Error("Something went wrong.", ex);
Thread.Sleep(TimeSpan.FromMinutes(10));
}
}
}
We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors.
This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged.
Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back? |
Try this, it should work:
/<\/?([^p]|..+?)>/
Explanation: it matches either a single letter except “p” or multiple letters (at least two). |
Try this, it should work:
/<\/?([^p](\s.+?)?|..+?)>/
Explanation: it matches either a single letter except “p”, followed by an optional whitespace and more characters, or multiple letters (at least two).
/EDIT: I've added the ability to handle attributes in `p` tags. |
Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like
public delegate void IoOperation(params string[] parameters);
public void FileDeleteOperation(params string[] fileName)
{
File.Delete(fileName[0]);
}
public void FileCopyOperation(params string[] fileNames)
{
File.Copy(fileNames[0], fileNames[1]);
}
public void RetryFileIO(IoOperation operation, params string[] parameters)
{
RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
bool success = false;
while (!success)
{
try
{
operation(parameters);
success = true;
}
catch (IOException e)
{
if (fileIORetryTimer.HasExceededRetryTimeout)
{
throw;
}
fileIORetryTimer.SleepUntilNextRetry();
}
}
}
public void Foo()
{
this.RetryFileIO(FileDeleteOperation, "L:\file.to.delete" );
this.RetryFileIO(FileCopyOperation, "L:\file.to.copy.source", "L:\file.to.copy.destination" );
} |
Override them like Michael Suggests [above](http://stackoverflow.com/questions/1528/#1533) and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:
[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated. |
I've tried Aquamacs and it's very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either.
Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year. |
This has already been answered for Java, here's the C# answer:
"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:
void DoStuff()
{
System.Console.WriteLine( SomeMethod((int)5) );
System.Console.WriteLine( GetTypeName<int>() );
}
string SomeMethod(object someParameter)
{
return string.Format("Some text {0}", someParameter.ToString());
}
string GetTypeName<T>()
{
return (typeof (T)).FullName;
} |
[Xdebug][1], by Derick Rethans, is very good. I used it some time ago and found it was not so easy to install. Once you're done, you won't understand how you managed without it :-)
There is a good article on [Zend Developer Zone][2] (installing on Linux doesn't seem any easier) and even a [Firefox plugin][3], which I never used.
[1]: http://xdebug.org/
[2]: http://devzone.zend.com/article/2803-introducing-xdebug
[3]: https://addons.mozilla.org/fr/firefox/addon/3960 |
Dir.glob('**/*.rb') perhaps? |
In Ruby itself:
Dir.glob('**/*.rb') perhaps? |
Campaign Monitor is a great resources for html email:
http://www.campaignmonitor.com/resources/#building
Also http://www.email-standards.org/, but seems down right now. |
One of the biggest causes, that I have found, for email to be flagged as spam is DNS. Make sure the domain / MX records from which you are sending the email actually resolve correctly back from the server used for sending.
As for images, you could attach them, but the most common way is to host them and use absolute urls. Primarily this is a bandwidth issue - you have to figure you're going to get an open rate of 10 - 15%: if you have to attach all the assets to every email, 85% of the bandwidth you'll use will be wasted. |
hah!
the answer if here:
http://forums.asp.net/p/1067527/1548528.aspx
I figured out the solution... the fix was simple change
OnClientClick="myOnClick()"
to
OnClientClick="return myOnClick()"
Here's the fully corrected code...
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script language=javascript type="text/javascript">
function myOnClick() {
//perform some other actions...
return false;
}
</script>
<title>Untitled Page</title>
</head>
<body bgcolor="buttonface" bottommargin="0" topmargin="0">
<form id="form1" runat="server">
<div>
<asp:Button CssClass="btnLastViewedSlide" ID="btnLastViewedSlide" runat="server" Text="Last Viewed Slide" OnClientClick="return myOnClick()" />
</div>
</form>
</body>
</html>
|
I think you need to look at using a wrapper thread that handles all calls to the DLL, and deals with the serialization.
This thread is outside of the managed thread pool, so you control its lifetime. But even this would not be foolproof unless you can prevent IIS from restarting the app domain your web service is in.
You also need to worry about what happens when two web service requests come in at the same time. Is each call into the DLL standalone, or do you have to group together all the calls associated with a single web service request before allowing any other request to be serviced?
|
How to reference javadocs to dependencies in Maven's eclipse plugin when javadoc not attached to dependency |
|eclipse|maven-2|eclipse-plugin|maven-eclipse-plugin| |
I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change.
Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in? |
Facebook does it, when you write on people's walls, but only resizes vertically.
Horizontal resize strikes me as being a terrible mess, due to word-wrap, long lines, and so on, but vertical resize would be pretty safe and nice
Facebook is inhabited by every idiot on the planet, and none of the facebook-using-idiots I know have ever mentioned anything about it or been remotely confused.
I'd use this as anecdotal evidence to say 'go ahead, implement it'
Some javascript to do it, using prototype.js (cos that's what I know)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // take into account long lines
} )
$('text-area').rows = linecount + 1;
};
Event.observe('text-area', 'keydown', resizeIt ); // you could attach to keyUp or whatever if keydown doesn't work
resizeIt(); //initial on load
</script>
</body>
</html>
PS: Obviously this javascript is very naive, and you probably don't want to use it on textboxes with novels in them, but you get the general idea |
Since the bottleneck will generally be in the processing and not the reading when dealing with files I'd go with the [producer-consumer][1] pattern. To avoid locking I'd look at lock free lists. Since you are using C# you can take a look at Julian Bucknall's [Lock-Free List][2] code.
[1]: http://www.ddj.com/architect/184401751
[2]: http://www.boyet.com/Articles/LockfreeFreeList.html |
I don't have access to SQL Server to test this, but how about:
DROP TABLE IF EXISTS table1, table2, table3 CASCADE; |
Pleae explain the use of java.math.MathContext |
|java| |
Recently I tried understanding the use of **java.math.MathContext** but failed to understand properly. Is it used for rounding in java.math.BigDecimal, if yes why does not it round the decimal digits but even mentissa part.
From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online.
Please let me know if you have any idea on this.
Thanks in advance.
~Jatan |
As far as I can tell you code is correct. Assuming exampleString is an std::string that has class scope like you describe, you ought to be able to initialize it like that. Perhaps there is some other issue? Maybe a snippet of actual code would help put it in context. |
As far as I can tell your code is correct. Assuming exampleString is an std::string that has class scope like you describe, you ought to be able to initialize/assign it that way. Perhaps there is some other issue? Maybe a snippet of actual code would help put it in context. |
I was actually just sprucing up a dialog today. Here are a few things to try:
1. Ensure adequate spacing between controls - don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space.
2. Put in some new 3D and glossing images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are [GlyFX][1] and [IconExperience][2]. You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy.
3. Try a different font. Tahoma is a good one. Often times the default font is MS Sans Seirf. You can do better. Avoid Times Roman and Comic Sanserif though. Also avoid large blocks of bold - use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart.
4. Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slop. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors.
5. Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface. I actually have a video of it and might be able to post it online with a little clean-up.
6. Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from [DevExpress][3] or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden!
7. You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI.
8. Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency.
A lot of it depends on what kind of application you have, and what OS they are running on. A couple of these tips will certainly go a long way to jazzing things up.
[1]: http://www.glyfx.com/
[2]: http://www.iconexperience.com/
[3]: http://www.devexpress.com/
|
I was actually just sprucing up a dialog today. Here are a few things to try:
1. Ensure adequate spacing between controls - don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space.
2. ![GlyFX][2]Put in some new 3D and glossing images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are [GlyFX][1] and [IconExperience][3]. You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy.
3. Try a different font. Tahoma is a good one. Often times the default font is MS Sans Seirf. You can do better. Avoid Times Roman and Comic Sanserif though. Also avoid large blocks of bold - use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart.
4. Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slop. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors.
5. Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface. I actually have a video of it and might be able to post it online with a little clean-up.
6. Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from [DevExpress][4] or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden!
7. You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI.
8. Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency.
A lot of it depends on what kind of application you have, and what OS they are running on. A couple of these tips will certainly go a long way to jazzing things up.
[1]: http://www.glyfx.com/
[2]: http://www.glyfx.com/grfx/products/thumb_free_vista.gif
[3]: http://www.iconexperience.com/
[4]: http://www.devexpress.com/ |
Having never developed a plugin myself, I'm not certain how this is typically done in plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4) { // Done loading?
if(this.status == 200) { // Everything okay?
// read content from this.responseXML or this.responseText
} else { // Error occurred; handle it
alert("Error " + this.status + ":\n" + this.statusText);
}
}
};
xmlhttp.send(null);
A couple of notes notes on this code:
- You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">here</a>.
- You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
- You may want to do things when earlier readyStates are received. <a href="http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-object">This page</a> documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful. |
WCF uses SoapFaults as its native way of transmitting exceptions from either the service to the client, or the client to the service.
You can declare a custom SOAP fault using the FaultContract attribute in your contract interface:
For example:
[ServiceContract(Namespace="foobar")]
interface IContract
{
[OperationContract]
[FaultContract(typeof(CustomFault))]
void DoSomething();
}
[DataContract(Namespace="Foobar")]
class CustomFault
{
[DataMember]
public string error;
public CustomFault(string err)
{
error = err;
}
}
class myService : IContract
{
public void DoSomething()
{
throw new FaultException<CustomFault>( new CustomFault("Custom Exception!"));
}
}
|
Why do I cannot jQuery my page under Internet Explorer |
|jquery|html| |
I have very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. jQuery function simply returns empty array.
Any suggestions? |
|jquery|html|javascript|internet-explorer| |
|javascript|html|jquery|internet-explorer| |
I have very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. jQuery function simply returns empty array.
Any suggestions?
Page is too complex to post it here. Practically any selector except #id -ones retur zero element array. jQuery version is 1.2.3 |
- locals() - No.
- globals() - Yes.
`window` is a reference to the global scope, like `globals()` in python.
globals()["foo"]
is the same as:
window["foo"] |
I was actually just sprucing up a dialog today. A lot of it depends on what kind of application you have, and what OS they are running on. A couple of these tips will certainly go a long way to jazzing things up.
1. Ensure adequate spacing between controls - don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space.
2. ![GlyFX][2]Put in some new 3D and glossing images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are [GlyFX][1] and [IconExperience][3]. You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy.
3. Try a different font. Tahoma is a good one. Often times the default font is MS Sans Seirf. You can do better. Avoid Times Roman and Comic Sanserif though. Also avoid large blocks of bold - use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart.
4. Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slop. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors.
5. Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface. I actually have a video of it and might be able to post it online with a little clean-up.
6. Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from [DevExpress][4] or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden!
7. You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI.
8. Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency.
Some apps lend themselves to full blown skinning, while others don't. Generally you don't want anything flashy that gets used a lot.
[1]: http://www.glyfx.com/
[2]: http://www.glyfx.com/grfx/products/thumb_free_vista.gif
[3]: http://www.iconexperience.com/
[4]: http://www.devexpress.com/ |
VB.net has two wonderful expression called "OrElse" and "AndAlso"
OrElse will short circuit itself the first time it reaches a True evaluation and execute the code you desire.
If FirstName = "Luke" OrElse FirstName = "Darth" Then
Console.Writeline "Greetings Exalted One!"
End If
AndAlso will short circuit itself the first time it a False evaluation and not evaluate the code within the block.
If FirstName = "Luke" AndAlso LastName = "Skywalker" Then
Console.Writeline "You are the one and only."
End If
I find both of these helpful. |
The asp.net site has an article about [Managing Browser History and Back Button Support in ASP.NET AJAX][1]
[1]: http://quickstarts.asp.net/Futures/ajax/doc/history.aspx |
Many websites make use of a hidden iframe to do this, simply refresh the iframe with the new URL, which adds it to the browsing history. Then all you have to do is handle how your application reacts to those 'back button' events - you'll either need to detect the state/location of the iframe, or refresh the page using that URL. |
Maybe not exactly what you request but checkout [DeltaCopy][1] which is a windows version of [rsync][2]. You can also read about another rsync solution [here][3]
[1]: http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp
[2]: http://en.wikipedia.org/wiki/Rsync
[3]: http://hype-free.blogspot.com/2007/02/using-rsync-on-windows.html |
I'd look at either [Mercurial][1] or [Bazaar][2]. I'm told Git also works on windows, but I suspect the windows port is still a second class port at best.
You'll probably need to be able to run python scripts on your webserver to host either of them.
[1]: http://www.selenic.com/mercurial/wiki/
[2]: http://bazaar-vcs.org/ |
I don't understand what you mean by "bring in the app" and "one turn drop it". By "bring in the app" do you mean deploy? As for "One turn drop", I totally don't understand it.
As for open betas, that depends on your audience, really. Counterstrike, for example, apparently run a few closed betas before doing open betas, so here's my suggestion:
1. Set up a forum in some free forumboard, or set up a topic in a popular gaming forum.
2. Look for people (whether or not they are in those forums) that you trust, and let them in in a closed beta. This will allow you to iron out serious kinks at first.
3. If your closed group isn't reporting as much bugs any more, release it to open beta, pointing out ways on how they could give feedback to you.
This is similar to the approach StackOverflow took, but this being a game setting it up on a gaming forum will give the dual benefit of advertising your game *and* getting some interested beta testers. |
I'll try to answer with the limited amount of details you've given.
1: Wether it's open or closed is really only an issue if you have great buzz, and a large group of users hammering down your door, trying toget in on the action.
If this is the case, I think you might get more loyalty and commitment from users in a closed beta.
2: You haven't given many (any) details as to what kind of game you are talking about, so it's pretty hard to answer this one.
/Jonas |
This is my general approach to testing/launching.
How you test/launch depends mostly on:
1. What your application **is**.
2. Who your users **are**.
If you application is a technical application and is geared to the technically-minded, the word "beta" won't really scare them - but provide an opportunity to test the product before it goes 'live', and help to improve the system. This is the ideal circumstance in which to use either an open or closed beta. It's usually beneficial to start off 'closed' with a group of people you select and trust to bug-find quickly and reliably - after you're more confident that all the critical bugs are gone, open it up with an invite system (for example).
If, however, your application is 'trivial' from a technical standpoint (i.e. it's something like Twitter, or Facebook, or Flickr - nothing that is inherently geared towards technical usage), then you're going to have to be more careful in how you plan your testing. Closed testing is most definitely your first port of call, and this should last for longer than a closed beta on a more 'technical' product. The reason? Your 'average Joe' doesn't necessarily know what the word "beta" means, and others may well be scared by it, or judge your service prematurely (not understanding the concept of this 'public testing' phase). Many won't want to be used as guinea pigs. |