Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
When attempting to understand how a SQL statement is executing, it is sometimes recommended to look at the explain plan. What is the process one should go through in interpreting (making sense) of an explain plan? What should stand out as, "Oh, this is working splendidly?" versus "Oh no, that's not right."
|
I shudder whenever I see comments that full tablescans are bad and index access is good. Full table scans, index range scans, fast full index scans, nested loops, merge join, hash joins etc. are simply access mechanisms that must be understood by the analyst and combined with a knowledge of the database structure and the purpose of a query in order to reach any meaningful conclusion.
A full scan is simply the most efficient way of reading a large proportion of the blocks of a data segment (a table or a table (sub)partition), and, while it often can indicate a performance problem, that is only in the context of whether it is an efficient mechanism for achieving the goals of the query. Speaking as a data warehouse and BI guy, my number one warning flag for performance is an index based access method and a nested loop.
So, for the mechanism of how to read an explain plan the Oracle documentation is a good guide: <http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/ex_plan.htm#PFGRF009>
Have a good read through the Performance Tuning Guide also.
Also have a google for "cardinality feedback", a technique in which an explain plan can be used to compare the estimations of cardinality at various stages in a query with the actual cardinalities experienced during the execution. Wolfgang Breitling is the author of the method, I believe.
So, bottom line: understand the access mechanisms. Understand the database. Understand the intention of the query. Avoid rules of thumb.
|
This subject is too big to answer in a question like this. You should take some time to read [Oracle's Performance Tuning Guide](http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm)
|
How do you interpret a query's explain plan?
|
[
"",
"sql",
"database",
"performance",
"oracle",
"sql-execution-plan",
""
] |
I have a form like this:
```
<form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
```
When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.
I tried to use `OnBlur` and `OnEnter`, without success.
**Try 1:**
```
<form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
```
**Try 2:**
```
<form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
```
but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing.
BTW, all this tried with Firefox on Linux.
|
Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):
```
<INPUT tabindex="3" type="submit" name="mySubmit">
```
|
You could use the [onfocus](http://www.w3schools.com/jsref/jsref_onfocus.asp) event on field two, which will be called when it receives focus. At that point, field 1's value should be updated and you can perform your check then.
|
How to skip fields using javascript?
|
[
"",
"javascript",
"firefox",
"focus",
"skip",
""
] |
**Is there a way to enforce/limit the types that are passed to primitives?** *(bool, int, string, etc.)*
Now, I know you can limit the generic type parameter to a type or interface implementation via the *where* clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from *object* before someone says! :P).
So, my current thoughts are to just grit my teeth and do a big *switch* statement and throw an *ArgumentException* on failure.
---
**EDIT 1:**
Just to clarify:
The code definition should be like this:
```
public class MyClass<GenericType> ....
```
And instantiation:
```
MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
```
---
**EDIT 2**
@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.
This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as *Size* ). Interesting problem no? :)
Here it is:
```
where T: struct
```
Taken from [MSDN](http://msdn.microsoft.com/en-us/library/d5x73970.aspx).
---
I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.
What do you guys think?
The sad news is I am working in Framework 2!! :D
---
**EDIT 3**
This was so simple following on from [Jon Limjaps Pointer](https://stackoverflow.com/questions/8941/generic-type-checking#8956).. So simple I almost want to cry, but it's great because the code works like a charm!
So here is what I did (you'll laugh!):
## Code added to the generic class
```
bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
```
Then a little utility method to check the type and throw an exception,
```
private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
```
All that then needs to be done is to call *EnforcePrimitiveType()* in the classes constructors. Job done! :-)
The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like [FxCop](http://en.wikipedia.org/wiki/FxCop) (which we don't use at work).
Special thanks to Jon Limjap on this one!
|
Primitives appear to be specified in the [`TypeCode`](http://msdn.microsoft.com/en-us/library/system.typecode.aspx) enumeration:
Perhaps there is a way to find out if an object contains the `TypeCode enum` without having to cast it to an specific object or call `GetType()` or `typeof()`?
**Update** It was right under my nose. The code sample there shows this:
```
static void WriteObjectInfo(object testObject)
{
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
switch( typeCode )
{
case TypeCode.Boolean:
Console.WriteLine("Boolean: {0}", testObject);
break;
case TypeCode.Double:
Console.WriteLine("Double: {0}", testObject);
break;
default:
Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
break;
}
}
}
```
It's still an ugly switch. But it's a good place to start!
|
```
public class Class1<GenericType> where GenericType : struct
{
}
```
This one seemed to do the job..
|
Generic type checking
|
[
"",
"c#",
"generics",
"primitive",
"type-safety",
""
] |
I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.
In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.
Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.
Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?
|
To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll).
add a "using WIA;"
```
const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
CommonDialogClass wiaDiag = new CommonDialogClass();
WIA.ImageFile wiaImage = null;
wiaImage = wiaDiag.ShowAcquireImage(
WiaDeviceType.UnspecifiedDeviceType,
WiaImageIntent.GrayscaleIntent,
WiaImageBias.MaximizeQuality,
wiaFormatJPEG, true, true, false);
WIA.Vector vector = wiaImage.FileData;
```
(System.Drawing)
```
Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
i.Save(filename)
```
Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's [Coding4Fun article on WIA](http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx) does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself)
If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you.
|
Heres how to target WIA 1.0 also so you can ship your app to Windows Xp. Something I was desperately looking for!!
[How to develop using WIA 1 under Vista?](https://stackoverflow.com/questions/678844/how-to-develop-using-wia-1-under-vista)
|
Using C#/WIA version 2.0 on Vista to Scan
|
[
"",
"c#",
".net",
".net-3.5",
"wia",
"image-scanner",
""
] |
We need to add WorkFlow to our Spring managed application. Does anyone have any useful experience in using any of the myriad of OSS Work Flow solutions? Which one is best? Which one integrates with Spring best? Which ones should we avoid?
|
If you only need some simple process orchestration, Spring's own [Web Flow](http://springframework.org/webflow), despite its name can serve as a orchestration task manager. If you need to preserve state for several days then you will need to become an 'early adopter' of one of the open-source projects. You may want to look at [Eclipse's BPEL project](http://www.eclipse.org/bpel/).
My hunch is that once a clearer picture of the BPEL/BPM/Workflow space emerges you will see Spring provide an abstraction layer the same way they have for JDBC, Transactions, ORM frameworks etc...
|
Like Brian said if you're doing anything of great complexity you might look at using BPEL.
There are a number of open source BPEL engines, one that comes to mind is [Apache Orchestration Director Engine](http://ode.apache.org/)
|
What OSS project should I look at if I need to do Spring friendly WorkFlow?
|
[
"",
"java",
"spring",
"workflow",
""
] |
In Visual Studio 2008
* add a new DataGridView to a form
* Edit Columns
* Add a a new DataGridViewImageColumn
* Open the CellStyle Builder of this column (DefaultCellStyle property)
* Change the NullValue from System.Drawing.Bitmap to null
* Try to add a new Row to the DataGridView at runtime
(dataGridView1.Rows.Add();)
* You get this error: System.FormatException: Formatted
value of the cell has a wrong type.
If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row.
If you set the NullValue at runtime instead of designtime you don't get anny error.
(dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;)
Could you tell me why is that?
|
This may well be a bug in the designer; if you take a look around at the .designer.cs file (maybe doing a diff from before and after you set NullValue to null) you should be able to see the code it generates.
|
Kronoz is right.
After setting it at designtime it adds this to the .designer.cs:
dataGridViewCellStyle1.NullValue = "null";
If I modify **"null"** to **null** then it works fine. I checked the DataGridViewCellStyle.NullValue set\_NullValue(Object) and get\_NullValue with reflector and I think that a string value shouldn't raise any error here.
Anyway be careful with this and if you want to set it designtime then don't forget to modify the .design.cs.
|
Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime
|
[
"",
"c#",
"datagridview",
"null",
""
] |
I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts.
Is there a way to make the webbrowser print the background of the displayed document too?
Edit:
Since I wanted to do this programatically, I opted for this solution:
```
using Microsoft.Win32;
...
RegistryKey regKey = Registry.CurrentUser
.OpenSubKey("Software")
.OpenSubKey("Microsoft")
.OpenSubKey("Internet Explorer")
.OpenSubKey("Main");
//Get the current setting so that we can revert it after printjob
var defaultValue = regKey.GetValue("Print_Background");
regKey.SetValue("Print_Background", "yes");
//Do the printing
//Revert the registry key to the original value
regKey.SetValue("Print_Background", defaultValue);
```
Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions.
Thanks for all your feedback
|
If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done.
I consider this *very bad* practice in the first place, but if you must do it then be kind.
```
Registry.LocalMachine
```
Also, try changing `LocalUser` instead of `LocalMachine` - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine.
|
Another registry key would be :
HKEY\_CURRENT\_USER\Software\Microsoft\Internet Explorer\PageSetup\Print\_Background
HKEY\_LOCAL\_MACHINE\Software\Microsoft\Internet Explorer\PageSetup\Print\_Background
|
How to print css applied background images with WebBrowser control
|
[
"",
"c#",
".net",
"printing",
"registry",
"webbrowser-control",
""
] |
I'm trying to write a web-app that records WAV files (eg: from the user's microphone). I know Javascript alone can not do this, but I'm interested in the least proprietary method to augment my Javascript with. My targeted browsers are Firefox for PC and Mac (so no ActiveX).
I gather it can be done with Flash (but not as a WAV formated file). I gather it can be done with Java (but not without code-signing). Are these the only options?
I'd like to record the file as a WAV because because the purpose of the webapp will be to assemble a library of *good* quality short soundbites. I estimate upload will be 50 MB, which is well worth it for the quality. The app will only be used on our intranet.
UPDATE: There's now an alternate solution thanks to JetPack's upcoming Audio API: See <https://wiki.mozilla.org/Labs/Jetpack/JEP/18>
|
Flash requires you to use a media server (note: I'm still using Flash MX, but a quick Google search brings up documentation for Flash CS3 that seems to concur - note that Flash CS4 is out soon, might change then). Macromedia / Adobe aim to flog you their media server, but the Red5 open-source project might be suitible for your project:
<http://osflash.org/red5>
I think Java is going to be more suitible. I've seen an applet that might do what you want over on Moodle (an open-source virtual learning environment):
<http://64.233.183.104/search?q=cache:k27rcY8QNWoJ:moodle.org/mod/forum/discuss.php%3Fd%3D51231+moodlespeex&hl=en&ct=clnk&cd=1&gl=uk>
(membership-required site, but open to Google, hence the link goes to the Google cache page).
|
This is an old thread, but the issue remains relevant. It should be noted that there is a way to record audio to the server in Flash without a proprietary back-end. Here's an example project to get you started:
<https://code.google.com/p/wami-recorder/>
|
How does one record audio from a Javascript based webapp?
|
[
"",
"javascript",
"audio",
"web-applications",
""
] |
Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object.
Here is the scenario with simplified code:
1. `Default.aspx`
2. `MainScript.js`
```
function getObject(){
return new Array();
}
function function1(obj){
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
function function2(){
var obj=getObject();
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
```
3. `Content.aspx`
4. `ContentScript.js`
```
function serializeObject(){
var obj=window.top.getObject();
window.top.function1(obj); // <– This works fine
obj=new Array();
window.top.function1(obj); // <– this causes an Out of Stack Space error
}
```
The code for the sample pages and JavaScript is [here](http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/).
Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.
A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx).
Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.
Any ideas?
|
This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method.
Example of the clone() methode you can find here (comments in Russian):
[link text](http://snowcore.net/clone-javascript-object)
|
I converted your example to a set of static html files, and dowloaded the standalone [Microsoft Ajax Library 3.5](http://msdn.microsoft.com/en-us/asp.net/bb944808.aspx) to test with. It didn't have issue on either Firefox 3 or IE 7, but I did notice the first alert box displayed [] (an array) and the second {} (an object).
Then, I converted your new Array() code to:
```
var obj = [];
obj.push(1);
```
and after that, I got [1] and {"0", 1} is the alert boxes. I don't think the bug is with JavaScriptSerializer, but something to do with passing objects across frames.
|
ASP.Net AJAX JavaScript Serialization Error
|
[
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?
It probably does something like:
```
override OnRead(object sender, Event e) {
ShowFilesFromAmazon();
}
```
Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.
---
The [Dokan Library](http://dokan-dev.net/en/) seems to be the answer that mostly corresponds with my question, even though [System.IO.IsolatedStorage](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx) seems to be the most standardized and most Microsoft-environment adapted.
|
You can use the [Dokan library](https://dokan-dev.github.io/) to create a virtual drive. There is a .Net wrapper for interfacing with C#.
|
Depending on what type of virtual drive you wish to build, here are some new OS API recently introduced in Windows, macOS and iOS.
Some of the below API is available as managed .NET code on Windows but many are a native Windows / macOS / iOS API. Even though, I was able to consume many of the below API in .NET and Xamarin applications and build entire Virtual Drive in C# for Windows, macOS and iOS.
## For Remote Cloud Storage
**On Windows.** Windows 10 provides [Cloud Sync Engine API](https://learn.microsoft.com/en-us/windows/win32/cfapi/build-a-cloud-file-sync-engine) for creating virtual drives that publish data from a remote location. It is also known under the “Cloud Filter API” name or “Windows Cloud Provider”. Here are its major features:
* On-demand folders listing. Folder listing is made only when the first requested by the client application to the file system is made. File content is not downloaded, but all file properties including file size are available on the client via regular files API.
* On-demand file content loading. File content can be downloaded in several modes (progressive, streaming mode, allow background download, etc) and made available to OS when application makes first file content reading request.
* Offline files support. Files can be edited in the offline mode, pinned/unpinned and synced to/from the server.
* Windows shell integration. Windows File Manager shows file status (modified, in-sync, conflict) and file download progress.
* Metadata and properties support. Custom columns can be displayed in Windows File Manager as well as some binary metadata can be associated with each file and folder.
**On macOS and iOS.** MacOS Big Sur and iOS 11+ provides similar API called [File Provider API](https://developer.apple.com/documentation/fileprovider). Its features are similar to what Windows API provides:
* On-demand folders listing.
* On-demand files content loading.
* Offline files support.
* File Manager Integration. In macOS Finder and iOS Files application you can can show file status (in the cloud, local).
I am not sure currently if files/folders and can show custom columns in macOS Finder and store any metadata.
## For High-Speed Local Storage
**On Windows.** Windows provides [ProjFS API](https://learn.microsoft.com/en-us/windows/win32/projfs/projected-file-system). Its main difference from the Cloud Sync Engine API and macOS/iOS File Provider API is that it hides the fact that it is a remote storage. It does not provide any indication of the file status, download progress, etc. The documentation says it is intended for “projecting” hierarchical data in the form of file system.
|
C#: Create a virtual drive in Computer
|
[
"",
"c#",
".net",
"virtualization",
"storage",
"virtual-drive",
""
] |
I will elaborate somewhat. Jsf is kind-of extremely painful for working with from designer's perspective, somewhat in the range of trying to draw a picture while having hands tied at your back, but it is good for chewing up forms and listing lots of data. So sites we are making in my company are jsf admin pages and jsp user pages. Problem occurs when user pages have some complicated forms and stuff and jsf starts kickin' in.
Here is the question: I'm on pure jsp page. I need to access some jsf page that uses session bean. How can I initialize that bean? If I was on jsf page, I could have some commandLink which would prepare data. Only thing I can come up with is having dummy jsf page that will do the work and redirect me to needed jsf page, but that's kind of ugly, and I don't want to end up with 50 dummy pages. I would rather find some mechanism to reinitialize bean that is already in session with some wanted parameters.
Edit: some more details. In this specific situation, I have a tests that are either full or filtered. It's a same test with same logic and everything, except if test is filtered, it should eliminate some questions depending on answers. Upon a clicking a link, it should start a requested test in one of the two modes. Links are parts of main menu-tree and are visible on many sibling jsp pages. My task is to have 4 links: testA full, testA filtered, testB full, testB filtered, that all lead on same jsf page and TestFormBean should be reinitialized accordingly.
Edit: I've researched facelets a bit, and while it won't help me now, I'll definitely keep that in mind for next project.
|
To solve this one I'd probably create a JSF fragment that only includes your form, then use a `<c:import>` tag to include it in my JSF page.
That solution is probably a little fragile depending on your environment though.
EDIT: See Chris Hall's answer, `FacesContext` is not available outside the `FacesServlet`.
|
have you looked into using facelets? It lets you get rid of the whole JSF / JSP differences (it's an alternate and superior view controller).
It also supports great design-time semantics with the jsfc tag...
```
<input type="text" jsfc="#{SomeBean.property}" class="foo" />
```
gets translated internally to the correct JSF stuff, so you can work with your existing tools.
|
Mixing jsp and jsf
|
[
"",
"java",
"jsp",
"jsf",
""
] |
I want to define something like this in *php*:
```
$EL = "\n<br />\n";
```
and then use that variable as an "endline" marker all over my site, like this:
```
echo "Blah blah blah{$EL}";
```
How do I define $EL once (in only 1 file), include it on every page on my site, and *not* have to reference it using the (strangely backwards) `global $EL;` statement in every page function?
|
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
```
include 'header.php';
```
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a [define()](http://php.net/define) rather than a variable. Those work inside functions after being included.
|
Sounds like the job of a constant. See the function [define()](https://www.php.net/define).
|
How to setup site-wide variables in php?
|
[
"",
"php",
""
] |
In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses.
My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes.
How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?
|
I think developing a custom solution for running background tasks doesn't always worth, so I recommend to use the [Quartz Scheduler](http://www.quartz-scheduler.org/) in Java.
In your situation (need to run background tasks in a web application) you could use the ServletContextListener included in the distribution to [initialize the engine at the startup of your web container](http://www.quartz-scheduler.org/api/2.2.1/org/quartz/ee/servlet/QuartzInitializerListener.html).
After that you have a number of possibilities to start (trigger) your background tasks (jobs), e.g. you can use Calendars or cron-like expressions. In your situation most probably you should settle with [SimpleTrigger](http://www.quartz-scheduler.org/api/2.2.1/org/quartz/CronTrigger.html) that lets you run jobs in fixed, regular intervals.
The jobs themselves can be described easily too in Quartz, however you haven't provided any details about what you need to run, so I can't provide a suggestion in that area.
|
As mentioned, Quartz is one standard solution. If you don't care about clustering or persistence of background tasks across restarts, you can use the built in ThreadPool support (in Java 5,6). If you use a [ScheduledExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html "Scheduled Executor Service") you can put Runnables into the background thread pool that wait a specific amount of time before executing.
If you do care about clustering and/or persistence, you can use JMS queues for asynchronous execution, though you will still need some way of delaying background tasks (you can use Quartz or the ScheduledExecutorService to do this).
|
Running a regular background event in Java web app
|
[
"",
"java",
"events",
""
] |
I have a tomcat instance setup but the database connection I have configured in `context.xml` keeps dying after periods of inactivity.
When I check the logs I get the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait\_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.
Here is the configuration in context.xml:
```
<Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&useEncoding=true&characterEncoding=UTF-8" />
```
I am using `autoReconnect=true` like the error says to do, but the connection keeps dying. I have never seen this happen before.
I have also verified that all database connections are being closed properly.
|
[Tomcat Documentation](http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html)
DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:
```
* Jakarta-Commons DBCP
* Jakarta-Commons Collections
* Jakarta-Commons Pool
```
This attribute may help you out.
```
removeAbandonedTimeout="60"
```
I'm using the same connection pooling stuff and I'm setting these properties to prevent the same thing it's just not configured through tomcat.
But if the first thing doesn't work try these.
```
testWhileIdle=true
timeBetweenEvictionRunsMillis=300000
```
|
Just to clarify what is actually causing this. MySQL by default terminates open connections after 8 hours of inactivity. However the database connection pool will retain connections for longer than that.
So by setting timeBetweenEvictionRunsMillis=300000 you are instructing the connection pool to run through connections and evict and close idle ones every 5 minutes.
|
Java+Tomcat, Dying database connection?
|
[
"",
"java",
"mysql",
"database",
"tomcat",
""
] |
Now that I know `C++` I want to get into desktop application that have a UI instead of `Command Prompt` stuff, where should I start?, and what are some good **online** resources?
|
[wxWidgets](http://www.wxwidgets.org/) is a cross platform GUI library for C++ (and other languages). The main site should have enough pointers to resources to get going.
You might also want to check out [this](https://stackoverflow.com/questions/4347/where-is-a-good-place-to-start-programming-guis-for-windows) question/answer here on stack overflow if you are specifically thinking of Windows
|
If cross platform support is important then I would second the suggestion to look at Qt. It supports Windows, Linux and the Mac. For free software it is free (there is a GPL version on Unix but not for Windows) but for comercial software it is not particulary cheap. There are now several books on Programming with Qt.
It does come with a large number of extra libraries for networking, parsing XML etc. It also has integration with Visual Studio on Windows.
One downside with Qt is that there are not as many add on libraries as with some other GUI frameworks. Ot will depend on the type of applications that you wish to write whether this is important to you or not.
|
C++ UI resources
|
[
"",
"c++",
"user-interface",
"resources",
""
] |
Just what the title says, I need to change the password for an existing sql server login and I want to do it via sql script.
|
ALTER LOGIN
<http://msdn.microsoft.com/en-us/library/ms189828.aspx>
|
If the user already has the ALTER ANY LOGIN permission (i.e. the user can change any password for any user) then this works:
```
alter login mylogin with password = 'mylogin'
```
Otherwise, if you don't want to make every user in your system a superuser, add a parameter of the old password for the same command:
```
alter login mylogin with password = 'mylogin' old_password='oldpassword'
```
|
How do I script a password change for a SQL server login?
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I've frequently encountered sites that put all of their JavaScript inside a `namespace` structure along the lines of:
```
namespaces = { com : { example: { example.com's data} }
```
However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the `com` namespace directly attached to the global object, or is it attached through a namespace object?
[Edit: whoops, obviously `{com = { ... } }` wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.]
|
Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.
Here's your example, corrected:
```
var namespaces = { com: { example: { /* example.com's data */ } } }
```
This is a variable `namespaces` being assigned an object literal. The object contains one property: `com`, an object with one property: `example`, an object which presumably would contain something interesting.
So, you can type something like **namespaces.com.example.*somePropertyOrFunctionOnExample*** and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.
```
var com_example_data = { /* example.com's data */ };
```
That works just as well, without the pointless hierarchy.
**Now**, if you actually *want* to build a hierarchy, you can try something like this:
```
com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};
com_example.ops = com_example.ops || (function()
{
var launchCodes = "38925491753824"; // hidden / private
return {
activate: function() { /* ... */ },
destroyTheWorld: function() { /* ... */ }
};
})();
```
...which is, IMHO, reasonably concise.
|
Here was an interesting article by Peter Michaux on [Javascript Namespacing](http://peter.michaux.ca/article/7944). He discusses 3 different types of Javascript namespacing:
1. Prefix Namespacing
2. Single Object Namespacing
3. Nested Object Namespacing
I won't plagiarize what he said here but I think his article is very informative.
Peter even went so far as to point out that there are performance considerations with some of them. I think this topic would be interesting to talk about considering that the new ECMAScript Harmony plans have dropped the 4.0 plans for namespacing and packaging.
|
Is there a "concise" way to do namespacing in JavaScript?
|
[
"",
"javascript",
"namespaces",
""
] |
I'm working on building a development tool that is written in JavaScript.
This will not be an open source project and will be sold (hopefully) as a commercial product.
I'm looking for the best way to protect my investment. Is using an obfuscator (code mangler) enough to reasonably secure the code?
Are there other alternatives that I am not aware of?
(I'm not sure if obfuscator is the right word, it's one of the apps that takes your code and makes it very unreadable.)
|
I'm going to tell you a secret. Once you understand it, you'll feel a lot better about the fact that Javascript obfuscation is only really useful for saving bandwidth when sending scripts over the wire.
Your source-code is not worth stealing.
I know this comes as a shock to the ego, but I can say this confidently without ever having seen a line of code you've written because outside the very few realms of development where serious magic happens, it's true of all source-code.
Say, tomorrow, someone dumped a pile of DVDs on your doorstep containing the source code for Windows Vista. What would you be able to do with it? Sure, you could compile it and give away copies, but that's just one step more effort than copying the retail version. You could painstakingly find and remove the license-checking code, but that's something some bright kid has already done to the binaries. Replace the logo and graphics, pretend you wrote it yourself and market it as "Vicrosoft Mista"? You'll get caught.
You could spend an enormous amount of time reading the code, trying to understand it and truly "stealing the intellectual property" that Microsoft invested in developing the product. But you'd be disappointed. You'd find the code was a long series of mundane decisions, made one after the other. Some would be smarter than you could think of. Some would leave you shaking your head wondering what kind of monkeys they're hiring over there. Most would just make you shrug and say "yeah, that's how you do that."
In the process you'll learn a lot about writing operating systems, but that's not going to hurt Microsoft.
Replace "Vista" with "Leopard" and the above paragraphs don't change one bit. It's not Microsoft, it's *software*. Half the people on this site could probably develop a Stack Overflow clone, with or without looking at the source of this site. They just haven't. The source-code of Firefox and WebKit are out there for anyone to read. Now go write your own browser from scratch. See you in a few years.
Software development is an investment of time. It's utter hubris to imagine that what you're doing is so special that nobody could clone it without looking at your source, or even that it would make their job that much easier without an actionable (and easily detectable) amount of cut and paste.
|
I deeply disagree with most answers above.
It's true that every software can be stolen despite of obfuscation but, at least, it makes harder to **extract and reuse individual parts** of the software and that is the point.
Maybe it's cheaper and less risky to use an obfuscation than leaving the code open and fighting at court after somebody stole the best parts of our software and made dangerous concurrency.
Unobfuscated code whispers:
* **Come on, analyze me, reuse me. Maybe you could make a better software using me.**
Obfuscated code says:
* **Go away dude. It's cheaper to use your own ideas than trying to crack me.**
|
Is using an obfuscator enough to secure my JavaScript code?
|
[
"",
"javascript",
"obfuscation",
""
] |
I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:
```
@Test(groups = { "db-test" })
public class DBTestBase {
}
```
However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.
So I tried disabling the test, so at least the groups are assigned:
```
@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
```
but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.
I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas?
|
The answer is through a custom **org.testng.IMethodSelector**:
Its **includeMethod()** can exclude any method we want, like a public not-annotated method.
However, to register a custom *Java* MethodSelector, you must add it to the **XMLTest** instance managed by any TestRunner, which means you need your own **custom TestRunner**.
But, to build a custom TestRunner, you need to register a **TestRunnerFactory**, through the **-testrunfactory** option.
BUT that -testrunfactory is NEVER taken into account by **TestNG** class... so you need also to define a custom TestNG class :
* in order to override the configure(Map) method,
* so you can actually set the TestRunnerFactory
* TestRunnerFactory which will build you a custom TestRunner,
* TestRunner which will set to the XMLTest instance a custom XMLMethodSelector
* XMLMethodSelector which will build a custom IMethodSelector
* IMethodSelector which will exclude any TestNG methods of your choosing!
Ok... it's a nightmare. But it is also a code-challenge, so it must be a little challenging ;)
All the code is available at [**DZone snippets**](http://snippets.dzone.com/posts/show/6446).
As usual for a code challenge:
* one java class (and quite a few inner classes)
* copy-paste the class in a 'source/test' directory (since the package is 'test')
* run it (no arguments needed)
---
**Update from Mike Stone:**
I'm going to accept this because it sounds pretty close to what I ended up doing, but I figured I would add what I did as well.
Basically, I created a Groups annotation that behaves like the groups property of the Test (and other) annotations.
Then, I created a GroupsAnnotationTransformer, which uses IAnnotationTransformer to look at all tests and test classes being defined, then modifies the test to add the groups, which works perfectly with group exclusion and inclusion.
Modify the build to use the new annotation transformer, and it all works perfectly!
Well... the one caveat is that it doesn't add the groups to non-test methods... because at the time I did this, there was another annotation transformer that lets you transform ANYTHING, but it somehow wasn't included in the TestNG I was using for some reason... so it is a good idea to make your before/after annotated methods to alwaysRun=true... which is sufficient for me.
The end result is I can do:
```
@Groups({ "myGroup1", "myGroup2"})
public class MyTestCase {
@Test
@Groups("aMethodLevelGroup")
public void myTest() {
}
}
```
And I made the transformer work with subclassing and everything.
|
TestNG will run all the public methods from a class with a @Test annotation. Maybe you could change the methods you don't want TestNG to run to be non-public
|
Can I specify a class wide group on a TestNG test case?
|
[
"",
"java",
"testng",
""
] |
If I were to want to create a nice looking widget to stay running in the background with a small memory footprint, where would I start building the windows application. It's goal is to keep an updated list of items off of a web service. Similar to an RSS reader.
note: The data layer will be connecting through REST, which I already have a C# dll, that I assume will not affect the footprint too much.
Obviously i would like to use a nice WPF project, but the ~60,000k initial size is too big.
\*C# Forms application is about ~20,000k
\*C++ Forms ~16,000k
\*CLR or MFC much smaller, under 5
Is there a way to strip down the WPF or Forms? and if im stuck using CLR or MFC what would be the easiest way to make it pretty. (my experience with MFC is making very award forms)
*Update: Clarification* The above sizes, are the memory being used as the process is ran, not the executable.
|
re:
> Update: Clarification The above sizes,
> are the memory being used as the
> process is ran, not the executable.
Okay, when you run a tiny C# Win Forms app, the smallest amount of RAM that is reserved for it is around 2 meg, maybe 4 meg. This is just a working set that it creates. It's not actively using all of this memory, or anything like it. It just reserves that much space up front so it doesn't have to do long/slow/expensive requests for more memory later as needed.
Reserving a smaller size upfront is likely to be a false optimization.
(You can reduce the working set with a pinvoke call if it really matters. see [pinvoke for 'set process working set size'](http://www.pinvoke.net/default.aspx/kernel32.SetProcessWorkingSetSize) )
|
If you "already have a C# dll" you're intending to use then there must be .net already installed on the target machine.
In that case, a C# win forms app need not be anywhere near 20 meg. The smallest hello world type win form would be 7 kilobytes.
|
What is best for desktop widgets (small footprint and pretty graphics)?
|
[
"",
".net",
"c++",
"wpf",
".net-3.5",
""
] |
As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome.
By feature-based I mean, for example:
```
if(window.ActiveXObject) {
// internet explorer!
}
```
**Edit:** As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome...
|
```
isChrome = function() {
return Boolean(window.chrome);
}
```
|
**This answer is very outdated**, but it was very relevant back then in the stone age.
I think feature detect is more usefull than navigator.userAgent parsing, as I googled Opera ambiguosity [here](http://www.javascriptkit.com/javatutors/navigator.shtml "here"). Nobody can know if IE16 will parse the /MSIE 16.0;/ regexp - but we can be quite sure, there will be the document.all support. In real life, the features are usually synonyms for the browsers, like: *"No XMLHttpRequest? It is the f....d IE6!"*
No nonIE browser supports document.all, but some browsers like Maxthon can scramble the userAgent. (Of course script can define document.all in Firefox for some reason, but it is easilly controllable.) Therefore I suggest this solution.
**Edit** [Here](http://www.javascriptkit.com/javatutors/objdetect3.shtml "Here") I found complete resources.
**Edit 2** I have tested that document.all is also supported by Opera!
```
var is = {
ff: window.globalStorage,
ie: document.all && !window.opera,
ie6: !window.XMLHttpRequest,
ie7: document.all && window.XMLHttpRequest && !XDomainRequest && !window.opera,
ie8: document.documentMode==8,
opera: Boolean(window.opera),
chrome: Boolean(window.chrome),
safari: window.getComputedStyle && !window.globalStorage && !window.opera
}
```
Using is simple:
```
if(is.ie6) { ... }
```
|
Safe feature-based way for detecting Google Chrome with Javascript?
|
[
"",
"javascript",
"browser",
"google-chrome",
""
] |
In a multi-threaded application I'm working on, we occasionally see `ConcurrentModificationExceptions` on our Lists (which are mostly `ArrayList`, sometimes Vectors). But there are other times when I think concurrent modifications are happening because iterating through the collection appears to be missing items, but no exceptions are thrown. I know that the docs for `ConcurrentModificationException` says you can't rely on it, but how would I go about making sure I'm not concurrently modifying a List? And is wrapping every access to the collection in a synchronized block the only way to prevent it?
**Update:** Yes, I know about `Collections.synchronizedCollection`, but it doesn't guard against somebody modifying the collection while you're iterating through it. I think at least some of my problem is happening when somebody adds something to a collection while I'm iterating through it.
**Second Update** If somebody wants to combine the mention of the synchronizedCollection and cloning like Jason did with a mention of the java.util.concurrent and the apache collections frameworks like jacekfoo and Javamann did, I can accept an answer.
|
Your original question seems to be asking for an iterator that sees live updates to the underlying collection while remaining thread-safe. This is an incredibly expensive problem to solve in the general case, which is why none of the standard collection classes do it.
There are lots of ways of achieving partial solutions to the problem, and in your application, one of those may be sufficient.
Jason gives [a specific way to achieve thread safety, and to avoid throwing a ConcurrentModificationException](https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75048), but only at the expense of liveness.
Javamann mentions [two specific classes](https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75196) in the `java.util.concurrent` package that solve the same problem in a lock-free way, where scalability is critical. These only shipped with Java 5, but there have been various projects that backport the functionality of the package into earlier Java versions, including [this one](http://backport-jsr166.sourceforge.net/), though they won't have such good performance in earlier JREs.
If you are already using some of the Apache Commons libraries, then as jacekfoo [points out](https://stackoverflow.com/questions/75014/detecting-concurrent-modifications#75205), the [apache collections framework](http://commons.apache.org/collections/) contains some helpful classes.
You might also consider looking at the [Google collections framework](http://www.devx.com/Java/Article/36183).
|
Depending on your update frequency one of my favorites is the CopyOnWriteArrayList or CopyOnWriteArraySet. They create a new list/set on updates to avoid concurrent modification exception.
|
Detecting concurrent modifications?
|
[
"",
"java",
"collections",
""
] |
How to implement a website with a recommendation system similar to stackoverflow/digg/reddit? I.e., users submit content and the website needs to calculate some sort of "hotness" according to how popular the item is. The flow is as follows:
* Users submit content
* Other users view and vote on the content (assume 90% of the users only views content and 10% actively votes up or down on content)
* New content is continuously submitted
How do I implement an algorithm that calculates the "hotness" of a submitted item, preferably in real-time? Are there any best-practices or design patterns?
I would assume that the algorithm takes the following into consideration:
* When an item was submitted
* When each vote was cast
* When the item was viewed
E.g. an item that gets a constant trickle of votes would stay somewhat "hot" constantly while an item that receives a burst of votes when it is first submitted will jump to the top of the "hotness"-list but then fall down as the votes stop coming in.
(I am using a MySQL+PHP but I am interested in general design patterns).
|
You could use something similar to the [Reddit algorithm](http://redflavor.com/reddit.cf.algorithm.png) - the basic principle of which is you compute a value for a post based on the time it was posted and the score. What's neat about the Reddit algorithm is that you only need recompute the value when the score of a post changes. When you want to display your front page, you just get the top n posts from your database based on that score. As time goes on the scores will naturally increase, so you don't have to do any special processing to remove items from the front page.
|
On my own site, I assign each entry a unique integer from a monotonically increasing series (newer posts get higher numbers). Each up vote increases the number by one, and each down vote decreases it by one (you can tweak these values, of course). Then, simply sort by the number to display the 'hottest' entries.
|
How to implement a Digg-like algorithm?
|
[
"",
"sql",
"algorithm",
"recommendation-engine",
"digg",
""
] |
Suppose the following:
```
>>> s = set([1, 2, 3])
```
How do I get a value (any value) out of `s` without doing `s.pop()`? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>> elem = s.pop()
>>> s.add(elem)
```
But do you know of a better way? Ideally in constant time.
|
Two options that don't require copying the whole set:
```
for e in s:
break
# e is now an element from s
```
Or...
```
e = next(iter(s))
```
But in general, sets don't support indexing or slicing.
|
Least code would be:
```
>>> s = set([1, 2, 3])
>>> list(s)[0]
1
```
Obviously this would create a new list which contains each member of the set, so not great if your set is very large.
|
How to retrieve an element from a set without removing it?
|
[
"",
"python",
"set",
""
] |
I've got a standard Rails app with Nginx and Mongrel running at <http://mydomain>. I need to run a Wordpress blog at <http://mydomain.com/blog>. My preference would be to host the blog in Apache running on either the same server or a separate box but I don't want the user to see a different server in the URL. Is that possible and if not, what would you recommend to accomplish the goal?
|
I think joelhardi's solution is superior to the following. However, in my own application, I like to keep the blog on a separate VPS than the Rails site (separation of memory issues). To make the user see the same URL, you use the same proxy trick that you normally use for proxying to a mongrel cluster, except you proxy to port 80 (or whatever) on another box. Easy peasy. To the user it is as transparent as you proxying to mongrel -- they only "see" the NGINX responding on port 80 at your domain.
```
upstream myBlogVPS {
server 127.0.0.2:80; #fix me to point to your blog VPS
}
server {
listen 80;
#You'll have plenty of things for Rails compatibility here
#Make sure you don't accidentally step on this with the Rails config!
location /blog {
proxy_pass http://myBlogVPS;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```
You can use this trick to have Rails play along with ANY server technology you want, incidentally. Proxy directly to the appropriate server/port, and NGINX will hide it from the outside world. Additionally, since the URLs will all refer to the same domain, you can seemlessly integrate a PHP-based blog, Python based tracking system, and Rails app -- as long as you write your URLs correctly.
|
Actually, since you're using Nginx, you're already in great shape and don't need Apache.
You can run PHP through fastcgi (there are examples of how to do this [in the Nginx wiki](http://wiki.codemongers.com/NginxFcgiExample)), and use a URL-matching pattern in your Nginx configuration to direct some URLs to Rails and others to PHP.
Here's an example Nginx configuration for running a WordPress blog through PHP fastcgi (note I've also put in the Nginx equivalent of the WordPress .htaccess, so you will also have fancy URLs already working with this config):
```
server {
listen example.com:80;
server_name example.com;
charset utf-8;
error_log /www/example.com/log/error.log;
access_log /www/example.com/log/access.log main;
root /www/example.com/htdocs;
include /www/etc/nginx/fastcgi.conf;
fastcgi_index index.php;
# Send *.php to PHP FastCGI on :9001
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9001;
}
# You could put another "location" section here to match some URLs and send
# them to Rails. Or do it the opposite way and have "/blog/*" go to PHP
# first and then everything else go to Rails. Whatever regexes you feel like
# putting into "location" sections!
location / {
index index.html index.php;
# URLs that don't exist go to WordPress /index.php PHP FastCGI
if (!-e $request_filename) {
rewrite ^.* /index.php break;
fastcgi_pass 127.0.0.1:9001;
}
}
}
```
Here's the fastcgi.conf file I'm including in the above config (I put it in a separate file so all of my virtual host config files can include it in the right place, but you don't have to do this):
```
# joelhardi fastcgi.conf, see http://wiki.codemongers.com/NginxFcgiExample for source
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param REDIRECT_STATUS 200;
```
I also happen to do what the Nginx wiki suggests, and use spawn-fcgi from Lighttpd as my CGI-spawner (Lighttpd is a pretty fast compile w/o weird dependencies, so a quick and easy thing to install), but you can also use a short shell/Perl script for that.
|
What's the best way to run Wordpress on the same domain as a Rails application?
|
[
"",
"php",
"ruby-on-rails",
"apache",
"wordpress",
"nginx",
""
] |
Is there anyway to configure a WCF service with a failover endpoint if the primary endpoint dies? Kind of like being able to specify a failover server in a SQL cluster.
Specifically I am using the TCP/IP binding for speed, but on the rare occurrence that the machine is not available I would like to redirect traffic to the failover server. Not too bothered about losing messages. I'd just prefer not to write the code to handle re-routing.
|
You need to use a layer 4 [load balancer](http://en.wikipedia.org/wiki/Load_balancing_%28computing%29#Relationship_with_failover) in front of the two endpoints. Prob best to stick with a dedicated piece of hardware.
|
Without trying to sound too vague but I think Windows Network Load Balancing (NLB) should handle this for you.
|
High availability
|
[
"",
"c#",
".net",
"wcf",
"soa",
""
] |
Any suggestions? Using visual studio in C#.
Are there any specific tools to use or methods to approach this?
### Update:
Sorry, I should have been a little more specific. I am using ASP.Net 2.0 and was looking more for a tool like jUnit for Java. I took a look at NUnit and NUnitAsp and that looks very promising. And I didn't even know that Visual Studio Pro has a testing suite, so I'll look at all of these options (I've just started using Visual Studio/Asp.net/C# this summer).
|
Boy, that's a pretty general question. I'll do my best, but be prepared to see me miss by a mile.
Assumptions
1. You are using ASP.NET, not plain ASP
2. You don't really want to test your web pages, but the **logic** behind them. Unit testing the actual .ASPX pages is rather painful, but there are frameworks out there to do it. [NUnitAsp](http://nunitasp.sourceforge.net/) is one.
The first thing to do is to organize (or plan) your code so that it can be tested. The two most popular design patterns for this at the time seem to be MVP and MVC. Both separate the **logic** of the application away from the **view** so that you can test the logic without the view (web pages) getting in your way.
Either MVP or MVC will be effective. MVC has the advantage of having a Microsoft framework [almost ready to go](http://www.asp.net/mvc/).
Once you've selected a framework pattern that encourages testability, you need to use a unit testing tool. [NUnit](http://www.nunit.org/) is a good starting point. Visual Studio Professional has a [testing suite built it](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/bb385902(v=vs.90)), but NUnit + [TestDrive.NET](http://www.testdriven.net/) also works in the IDE.
That's sort of a shotgun blast of information. I hope some if it hits. The Pragmatic Bookshelf has a [good book covering the topic](https://rads.stackoverflow.com/amzn/click/com/0974514020).
|
These frameworks are useful for *integration* testing, but they can't provide unit testing, that is, testing the View isolated from persistence, business logic, whatever.
For *unit* testing Asp.Net Webforms, as well as MVC, you can use [Ivonna](http://sm-art.biz/Ivonna.aspx). For example, you can mock your database access and verify that the mocked records are displayed in the datagrid. Or you can mock the membership provider and test the logged in scenario without having to navigate to the login page and entering your credentials, as with integration testing.
|
What is the best way to do unit testing for ASP.NET 2.0 web pages?
|
[
"",
"c#",
"asp.net",
"visual-studio",
"unit-testing",
""
] |
I'm looking for a good GUI designer for swing in eclipse. My preference is for a free/open-source plugin.
|
[Window Builder Pro](https://developers.google.com/java-dev-tools/wbpro/) is a great GUI Designer for eclipse and is now offered for free by google.
|
Here is a quite good but old comparison <http://wiki.computerwoche.de/doku.php/programmierung/gui-builder_fuer_eclipse>
Window Builder Pro is now free at Google Web Toolkit
|
Best GUI designer for eclipse?
|
[
"",
"java",
"eclipse",
"swing",
"gui-designer",
""
] |
I am currently calling the following line of code:
```
java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path");
```
and I get the exception above when it executes. Any ideas as to why this is happening?
|
Your code works perfectly fine for me:
```
public static void main(String[] args) {
try {
java.net.URL connection_url = new java.net.URL("http://:/path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
```
> Instantiated new URL: <http://:/path>
Sure you have the right line of code?
|
As a side note, you should be using [URI](http://java.sun.com/javase/6/docs/api/java/net/URI.html) because Java URL class is screwed up. (The equals method I believe)
|
getting java exception: java.net.MalformedURLException: no protocol
|
[
"",
"java",
"url",
"io",
""
] |
I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...
I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.
I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.
|
What you want is a [bookmarklet](http://en.wikipedia.org/wiki/Bookmarklet) they are easy to create and should work in most major browsers.
Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field
```
javascript:window.location='http://www.google.com/search?q='+Date()
```
to get a bookmarklet that searches google for the current date.
|
It is worthy of note that you can put that in a function wrapper as well. imranamajeed nicely illustrated that for us... but apparently I'm too new to the site to up his post. :P
so for clarity:
```
javascript:(function(){
location.href = location.href + "#";
})();
```
(the carriage returns did not affect performance in chrome and IE)
|
Add a bookmark that is only javascript, not a URL
|
[
"",
"javascript",
"bookmarklet",
"bookmarks",
""
] |
My C# project - we'll call it the SuperUI - used to make use of a class from an external assembly. Now it doesn't, but the compiler won't let me build the project without the assembly reference in place. Let me elaborate.
This project used to throw and catch a custom exception class - the `SuperException` - which was derived from the standard System.Exception and lived in a separate, precompiled assembly, `SuperAssembly.DLL`, which I referenced.
Eventually, I decided this was a pointless exercise and replaced all `SuperExceptions` with a System.SuitableStandardException in each case. I removed the reference to `SuperException.DLL`, but am now met with the following on trying to compile the project:
> The type 'SuperException' is defined in an assembly that is not referenced. You must add a reference to assembly 'SuperException, Version=1.1.0.0 (...)'
The source file referenced by the error doesn't seem relevant; it's the project namespace that gets highlighted in the IDE.
Now, here's the thing:
1. All uses of `SuperException` have been eliminated from the project's code.
2. Compared to another project that compiles fine without a reference to `SuperException.DLL`, I only reference one more assembly - and `that` references nothing that my project doesn't reference itself. While it's possible that any of these dependencies could throw `SuperExceptions`, I'm only catching the base Exception class and in any case... the other project builds fine!
3. I've done Visual Studio's "Clean Solution" and cleared everything out by hand, many times.
It's not the end of the world to include this reference, I just don't see why it's necessary any more. Nrrrgg. Any pointers welcome!
|
It's likely a transitive reference, where some type method call returns an instance of SuperException boxed ("downcast") as e.g. Exception, but from inspecting the code in the transitively included code, i.e. code from your external method calls, the compiler knows that you need to be able to have information about that type at some point.
Resharper would tell you where it's the case that you need to add a reference, and you could use Lütz Roeder's aka RedGate's Reflector to scan compiled IL for a reference to this type in two ways: 1) use the search-facility, 2) open each public type you're using and for that one which requires the "ghost" assembly, it will ask you to specify its location.
This most often happends to me when I reference Castle.Windsor but not Castle.MicroKernel. :p
|
I agree with the other comments here.. There is a reference, in plain text *somewhere* !
I have had similar problems in the past where searching through the project files returned nothing, turns out it was in some other file that wasn't automatically picked up in the search.
I don't think that creating a new project is the solution here.. You need to be positive that **NONE** of the references in your dependency tree use SuperException.. *NONE*
I have never experienced this to the point where I have needed to literally wipe the project, I have always found the reference somewhere. Ensure you are searching **every** file.
### EDIT:
Just a point to add, if the location pointed to by the error seems random, that can often mean there is a mismatch between the compiled source and the source code file.. Is this a ASP.NET application? I have had it before where the compiled DLL's haven't been replaced on a rebuild in the ASP.NET temp folder causing things to get.. Interesting when debugging :)
|
Lingering assembly dependency in C# .NET
|
[
"",
"c#",
".net",
"dependencies",
""
] |
My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?
If it's not, how would you do it with POST? Just out of curiosity.
Cheers!
|
You can actually do it all with GET methods. However, you'll want to use a full challenge response protocol for the logins. (You can hash on the client side using javascript. You just need to send out a unique challenge each time.) You'll also want to use SSL to ensure that no one can see the strings as they go across.
In some senses there's no real security difference between GET and POST requests as they both go across in plaintext, in other senses and in practice... GET is are a hell of a lot easier to intercept and is all over most people's logs and your web browser's history. :)
(Or as suggested by the other posters, use a different method entirely like HTTP auth, digest auth or some higher level authentication scheme like AD, LDAP, kerberos or shib. However I kinda assumed that if you didn't have POST you wouldn't have these either.)
|
You could use HTTP Authentication, if supported.
You'd have to add SSL, as all methods, POST, GET and HTTP Auth (well, except Digest HHTP authentication) send plaintext.
GET is basically just like POST, it just has a limit on the amount of data you can send which is usually a lot smaller than POST and a semantic difference which makes GET not a good candidate from that point of view, even if technically they both can do it.
As for examples, what are you using? There are many choices in Python, like the cgi module or some framework like Django, CherryPy, and so on
|
Can I implement a web user authentication system in python without POST?
|
[
"",
"python",
"authentication",
"cgi",
""
] |
Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?
```
class Base {
public:
bool someGuaranteedResult() { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
```
Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.
|
A couple of ideas:
1. Make your function private.
2. Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though.
Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.
Good luck!
|
When you can use the `final` specifier for virtual methods (introduced with C++11), you can do it. Let me quote [my favorite doc site](http://en.cppreference.com/w/cpp/language/final):
> When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.
Adapted to your example that'd be like:
```
class Base {
public:
virtual bool someGuaranteedResult() final { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
```
When compiled:
```
$ g++ test.cc -std=c++11
test.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’
test.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’
```
When you are working with a Microsoft compiler, also have a look at the [`sealed`](https://msdn.microsoft.com/en-us/library/0w2w91tf(v=vs.140).aspx) keyword.
|
Is there a way to prevent a method from being overridden in subclasses?
|
[
"",
"c++",
"overriding",
"metrowerks",
""
] |
RPO 1.0 (Runtime Page Optimizer) is a recently (today?) released component for ASP and Sharepoint that compresses, combines and minifies (I can’t believe that is a real word) Javascript, CSS and other things.
What is interesting is that it was developed for ActionThis.com a NZ shop that saw at TechEd last year. They built a site that quickly needed to be trimmed down due to the deployment scale and this seems to be the result of some of that effort.
Anyone have any comments? Is it worthwhile evaluating this?
<http://www.getrpo.com/Product/HowItWorks>
**Update**
I downloaded this yesterday and gave it a whirl on our site. The site is large, complex and uses a lot of javascript, css, ajax, jquery etc as well as URL rewriters and so on. The installation was too easy to be true and I had to bang my head against it a few times to get it to work. The trick... entries in the correct place in the web.config and a close read through the AdvancedSetup.txt to flip settings manually. The site renders **mostly** correctly but there are a few issues which are probably due to the naming off css classed - it will require some close attention and a lot of testing to make sure that it fits, but so far it looks good and well worth the cost.
**Second Update** We are busy trying to get RPO hooked up. There are a couple of problems with character encoding and possibly with the composition of some of our scripts. I have to point out that the response and support from the vendor has been very positive and proactive
**Third Update** I went ahead and went ahead with the process of getting RPO integrated into the site that I was involved in. Although there were some hiccups, the RPO people were very helpful and put a lot of effort into improving the product and making it fit in our environment. It is definitely a no-brainer to use RPO - the cost for features means that it is simple to just go ahead and implement it. Job done. Move on to next task
|
I decided to answer this question again after evalutating it a little.
* The image combining is really amazing
* The CSS and Javascript is nicely minified
* All files are cached on the server meaning that the server isn't cained every time it makes a request
* The caching is performed at a browser level, meaning it will still work if you use an old (unsupported) browser because you'll just recieve the page un-compressed
* You can see the difference youself [Optimized](http://www.getrpo.com/?rpo=on) vs [Unoptimized](http://www.getrpo.com/?rpo=off)
The price is as follows...
* $499 until the end of september is a steal
* $199 for an annual renewal is a steal
|
Clarification on the RPO price. Launch price until end of September 2008 is $499 - and this discount is by voucher (email service@getrpo.com to get a voucher). This includes software assurrance for 12 months, after which you can choose to renew for $199 or not - the software still works.
The RPO automates 8 of Steve Souders/Yahoo's principles for High Performance Web Sites - the important thing for us was making a developer friendly tool - you can keep your resources in the format and structure that makes sense for development and the optimization happens at runtime.
I don't want to spam this forum with sales stuff, so just email me if you have any questions - ed.robinson@aptimize.net. Thanks for looking at the RPO.
Ed Robinson, Chief Executive Officer, Aptimize Ltd
|
Runtime Page Optimizer for ASP.net - Any comments?
|
[
"",
"asp.net",
"javascript",
"optimization",
""
] |
I am using `<input type="file" id="fileUpload" runat="server">` to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).
Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).
|
Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.
HTML:
```
<input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
```
Javascript:
```
var hash = {
'xls' : 1,
'xlsx' : 1,
};
function check_extension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var submitEl = document.getElementById(submitId);
if (hash[ext]) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid filename, please select another file");
submitEl.disabled = true;
return false;
}
}
```
|
It's pretty simple using regulare expression validator.
```
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Only zip file is allowed!"
ValidationExpression ="^.+(.zip|.ZIP)$"
ControlToValidate="FileUpload1"
> </asp:RegularExpressionValidator>
```
[Client-Side Validation of File Types Permissible to Upload](http://patelshailesh.com/index.php/client-side-validation-of-file-types-permissible-to-upload)
|
How do I Validate the File Type of a File Upload?
|
[
"",
"asp.net",
"javascript",
"validation",
"file",
"upload",
""
] |
I have been a VB.net developer for a few years now but I am currently applying to a few companies that use C#. I have even been told that at least one of the companies doesn't want VB.net developers.
I have been looking online trying to find real differences between the two and have asked on crackoverflow. The only major differences are a few syntax difference which are trivial to me because I am also a Java developer.
What would be a good response to an interviewer when they tell me they are looking for a C# developer - or similar questions?
|
I've had to interview people for a few C# positions and this is my general advice for VB.Net developers interviewing for a C# position:
* Make sure you are clear that you have been working VB.Net. This seems obvious but is something that apparently isn't (in my experience).
* Try to give a code sample, if possible. I've seen some horrible VB.Net (and C#) written by VB programmers who didn't seem to learn much in the transition to .Net.
* Be able to write in C# during the interview, if asked. I know there aren't many real differences between the two, but I don't want to pay you to learn the new syntax.
For your specific question: I've asked that type of question before and what I wanted to hear about was how the underlying system and framework were the same. If possible, talk about garbage collection, IDisposable, finalizers, the dangers of unsafe code blocks, stack vs heap, etc. All the kind of stuff to show that you really understand the intricacies of the .Net framework. Right or wrong, the heritage of VB brings with it an expectation of a lack of understand of lower level programming and windows in general (which, ironically enough, a c++ developer would have of a c# developer... and so on).
Lastly, how you frame your experience can make a world of difference. If you position yourself as a .Net developer, rather than VB.Net or C#, the stupid, pseudo-religious, banter may not enter the conversation. This of course requires that you actually know both VB.Net and C# at the time of the interview, but that's a good policy regardless.
The truth of the matter is that if you find that the person interviewing you writes you off simply because you've previously been developing in VB.Net, it's likely not going to be a place you want to work at anyway.
|
Some differences (that are more substantial than syntactical) that suitably catch me out sometimes:
* VB.NET does not have anonymous delegates
* Unsafe code blocks aren't in VB.NET
|
Interview question on C# and VB.net similarities/differences
|
[
"",
"c#",
"vb.net",
""
] |
I have a directory structure like the following;
> script.php
>
> inc/include1.php
> inc/include2.php
>
> objects/object1.php
> objects/object2.php
>
> soap/soap.php
Now, I use those objects in both `script.php` and `/soap/soap.php`, I could move them, but I want the directory structure like that for a specific reason. When executing `script.php` the include path is `inc/include.php` and when executing `/soap/soap.php` it's `../inc`, absolute paths work, `/mnt/webdev/[project name]/inc/include1.php...` But it's an ugly solution if I ever want to move the directory to a different location.
So is there a way to use relative paths, or a way to programmatically generate the `"/mnt/webdev/[project name]/"`?
|
This should work
```
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/inc/include1.php";
```
---
**Edit:** added imporvement by [aussieviking](https://stackoverflow.com/questions/4369/include-files-requiring-an-absolute-path#4388)
|
You can use relative paths. Try `__FILE__`. This is a PHP constant which always returns the path/filename of the script it is in. So, in `soap.php`, you could do:
```
include dirname(__FILE__).'/../inc/include.php';
```
> The full path and filename of the
> file. If used inside an include, the
> name of the included file is returned.
> Since PHP 4.0.2, `__FILE__` always
> contains an absolute path with
> symlinks resolved whereas in older
> versions it contained relative path
> under some circumstances.
> [(source)](https://www.php.net/constants.predefined)
Another solution would be to set an **include path** in your httpd.conf or an .htaccess file.
|
How to include PHP files that require an absolute path?
|
[
"",
"php",
""
] |
I would like to do the equivalent of:
```
object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
```
Following Biri s [link](http://www.codeproject.com/KB/cs/evalcscode.aspx), I got this snippet (modified to remove obsolete method `ICodeCompiler.CreateCompiler()`:
```
private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
```
|
Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.
You can use [Roslyn's new Scripting API to evaluate expressions](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md).
If you are using NuGet, just add a dependency to [Microsoft.CodeAnalysis.CSharp.Scripting](https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp.Scripting/).
To evaluate the examples you provided, it is as simple as:
```
var result = CSharpScript.EvaluateAsync("1 + 3").Result;
```
This obviously does not make use of the scripting engine's async capabilities.
You can also specify the evaluated result type as you intended:
```
var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result;
```
To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.
|
I have written an open source project, [Dynamic Expresso](https://github.com/davideicardi/DynamicExpresso/), that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into [Expression Trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) without using compilation or reflection.
You can write something like:
```
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
```
or
```
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.aMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
```
My work is based on Scott Gu article <http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> .
|
How can I evaluate a C# expression dynamically?
|
[
"",
"c#",
"reflection",
"eval",
""
] |
Java has a convenient split method:
```
String str = "The quick brown fox";
String[] results = str.split(" ");
```
Is there an easy way to do this in C++?
|
C++ standard library algorithms are pretty universally based around iterators rather than concrete containers. Unfortunately this makes it hard to provide a Java-like `split` function in the C++ standard library, even though nobody argues that this would be convenient. But what would its return type be? `std::vector<std::basic_string<…>>`? Maybe, but then we’re forced to perform (potentially redundant and costly) allocations.
Instead, C++ offers a plethora of ways to split strings based on arbitrarily complex delimiters, but none of them is encapsulated as nicely as in other languages. The numerous ways [fill whole blog posts](https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/).
At its simplest, you could iterate using [`std::string::find`](http://en.cppreference.com/w/cpp/string/basic_string/find) until you hit `std::string::npos`, and extract the contents using [`std::string::substr`](https://en.cppreference.com/w/cpp/string/basic_string/substr).
A more fluid (and idiomatic, but basic) version for splitting on whitespace would use a [`std::istringstream`](https://en.cppreference.com/w/cpp/io/basic_istringstream):
```
auto iss = std::istringstream{"The quick brown fox"};
auto str = std::string{};
while (iss >> str) {
process(str);
}
```
Using [`std::istream_iterator`s](https://en.cppreference.com/w/cpp/iterator/istream_iterator), the contents of the string stream could also be copied into a vector using its iterator range constructor.
Multiple libraries (such as [Boost.Tokenizer](https://www.boost.org/doc/libs/1_70_0/libs/tokenizer/doc/tokenizer.htm)) offer specific tokenisers.
More advanced splitting require regular expressions. C++ provides the [`std::regex_token_iterator`](https://en.cppreference.com/w/cpp/regex/regex_token_iterator) for this purpose in particular:
```
auto const str = "The quick brown fox"s;
auto const re = std::regex{R"(\s+)"};
auto const vec = std::vector<std::string>(
std::sregex_token_iterator{begin(str), end(str), re, -1},
std::sregex_token_iterator{}
);
```
|
The [Boost tokenizer](http://www.boost.org/doc/libs/1_36_0/libs/tokenizer/index.html) class can make this sort of thing quite simple:
```
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int, char**)
{
string text = "token, test string";
char_separator<char> sep(", ");
tokenizer< char_separator<char> > tokens(text, sep);
BOOST_FOREACH (const string& t, tokens) {
cout << t << "." << endl;
}
}
```
Updated for C++11:
```
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int, char**)
{
string text = "token, test string";
char_separator<char> sep(", ");
tokenizer<char_separator<char>> tokens(text, sep);
for (const auto& t : tokens) {
cout << t << "." << endl;
}
}
```
|
How do I tokenize a string in C++?
|
[
"",
"c++",
"string",
"split",
"tokenize",
""
] |
I have a set of multiple assemblies (one assembly is to be used as an API and it depends on other assemblies). I would like to merge all assemblies into one single assembly but prevent all assemblies except the API one to be visible from the outside.
I will then obfuscate this assembly with Xenocode. From what I have seen, it is impossible to internalize assembly with Xenocode.
I have seen ILMerge from Microsoft, but was unable to figure if it can do what I want.
<http://research.microsoft.com/~mbarnett/ILMerge.aspx>
|
I know Xenocode can merge assemblies into one but I am not sure if it will internalize other non-primary assemblies.
I have found the /internalize switch in ILMerge that "internalize" all assemblies except the primary one. Pretty useful!
|
I have used ILMerge from microsoft to internalize DLL's into a single assembled library. There is a useful GUI for using ILMerge called NuGenUnify. You can find it [here](http://www.genetibase.com/cforce/nugenunify.php).
|
Internalize Class and Methods in .NET Assembly
|
[
"",
"c#",
".net",
"vb.net",
"assemblies",
""
] |
As a lot of people pointed out in [this question](https://stackoverflow.com/questions/4724/learning-lisp-why), Lisp is mostly used as a learning experience. Nevertheless, it would be great if I could somehow use my Lisp algorithms and combine them with my C# programs.
In college my profs never could tell me how to use my Lisp routines in a program (no, not writing a GUI in Lisp, thank you).
So how can I?
|
Try these .Net implementations of Lisp:
* [IronScheme](https://github.com/leppie/IronScheme)
> IronScheme will aim to be a R6RS
> conforming Scheme implementation based
> on the Microsoft DLR.
* [L Sharp .NET](https://github.com/RobBlackwell/LSharp)
> L Sharp .NET is a powerful Lisp-like
> scripting language for .NET. It uses a
> Lisp dialect similar to Arc but
> tightly integrates with the .NET
> Framework which provides a rich set of
> libraries.
|
[Clojure](http://clojure.org "Clojure") is a Lisp-1 that is **compiled** on-the-fly to Java bytecode, leading to very good runtime performance. You can use Clojure, and cross-compile it to a .NET assembly using [IKVM](http://www.ikvm.net "IKVM")'s ikvmc. Of course, when used in .NET, Clojure happily generates .NET IL, leading to the same kind of compiled-code performance you can expect when using it on a JVM.
|
Using Lisp in C#
|
[
"",
"c#",
"lisp",
""
] |
Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version?
|
`_MSC_VER` and possibly `_MSC_FULL_VER` is what you need. You can also examine [visualc.hpp](https://www.boost.org/doc/libs/master/boost/config/compiler/visualc.hpp) in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
```
MSVC++ 14.30 _MSC_VER == 1933 (Visual Studio 2022 version 17.3.4)
MSVC++ 14.30 _MSC_VER == 1932 (Visual Studio 2022 version 17.2.2)
MSVC++ 14.30 _MSC_VER == 1930 (Visual Studio 2022 version 17.0.2)
MSVC++ 14.30 _MSC_VER == 1930 (Visual Studio 2022 version 17.0.1)
MSVC++ 14.28 _MSC_VER == 1929 (Visual Studio 2019 version 16.11.2)
MSVC++ 14.28 _MSC_VER == 1928 (Visual Studio 2019 version 16.9.2)
MSVC++ 14.28 _MSC_VER == 1928 (Visual Studio 2019 version 16.8.2)
MSVC++ 14.28 _MSC_VER == 1928 (Visual Studio 2019 version 16.8.1)
MSVC++ 14.27 _MSC_VER == 1927 (Visual Studio 2019 version 16.7)
MSVC++ 14.26 _MSC_VER == 1926 (Visual Studio 2019 version 16.6.2)
MSVC++ 14.25 _MSC_VER == 1925 (Visual Studio 2019 version 16.5.1)
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
```
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found [here](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering). [Starting recently](https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-c-compiler-version/), Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
`cl.exe /?` will give a hint of the used version, e.g.:
```
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
```
|
Yep \_MSC\_VER is the macro that'll get you the compiler version. The last number of releases of Visual C++ have been of the form `<compiler-major-version>.00.<build-number>`, where 00 is the minor number. So `_MSC_VER` will evaluate to `<major-version><minor-version>`.
You can use code like this:
```
#if (_MSC_VER == 1500)
// ... Do VC9/Visual Studio 2008 specific stuff
#elif (_MSC_VER == 1600)
// ... Do VC10/Visual Studio 2010 specific stuff
#elif (_MSC_VER == 1700)
// ... Do VC11/Visual Studio 2012 specific stuff
#endif
```
It appears updates between successive releases of the compiler, have not modified the `compiler-minor-version`, so the following code is not required:
```
#if (_MSC_VER >= 1500 && _MSC_VER <= 1600)
// ... Do VC9/Visual Studio 2008 specific stuff
#endif
```
Access to more detailed versioning information (such as compiler build number) can be found using other builtin pre-processor variables [here](http://msdn.microsoft.com/en-us/library/b0084kay.aspx).
|
How to Detect if I'm Compiling Code with a particular Visual Studio version?
|
[
"",
"c++",
"visual-studio",
""
] |
I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?
Code:
```
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type
string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException
```
|
```
MyObj o = null;
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });
if(ctor != null)
o = ctor.Invoke(new object[] { s });
```
|
Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters:
```
static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars)
{
var t = a.GetType(typeName);
var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray());
if (c == null) return null;
return c.Invoke(pars);
}
```
And you call it like this:
```
Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo;
```
So you pass the assembly and the name of the type as the first two parameters, and then all the constructor's parameters in order.
|
Compact Framework - how do I dynamically create type with no default constructor?
|
[
"",
"c#",
"reflection",
"compact-framework",
""
] |
I know I can programatically make the taskbar item for a particular window start flashing when something changes, but is there any way I can stop it from flashing either programatically after a certain period of time or at least is there a keyboard shortcur I can give to my users to somehow stop the flashing?
|
The [FlashWindowEx](http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx) function which controls the flashing takes a [FLASHWINFO](http://msdn.microsoft.com/en-us/library/ms679348%28VS.85%29.aspx) struct which has a uCount field to control how many times it flashes. Also, a possible value for the dwFlags field is FLASHW\_STOP to cause the flashing to stop.
EDIT: Forgot was a C# tagged question ... so [P/Invoke goodness found here](http://www.pinvoke.net/default.aspx/user32.FlashWindowEx).
|
Instead of flashing the tasbar you can consider using the NotifyIcon. This will let you put something on the system tray (something else many consider evil because of the proliferation of apps that do this). Then you can popup a ballon tip with any change that actually describes the change itself.
To use:
(1) Drag the NotifyIcon onto your form or create in your app NotifyIcon notify = new NotifyIcon();
(2) Set the icon property to the required image
(3) Control whether it is visible on the system tray using the Visible property
(4) Call ShowBalloonText to show popup text (limited to 64 characters)
Either way, you shoudl add an option to the program that allows the end user to turn this feature on/off based on their feelings about it all. I personally like the notify icon because the ballon text can say something like "Server went down"
|
Stop the taskbar flashing
|
[
"",
"c#",
"winforms",
"taskbar",
""
] |
I'm working on getting an Introduction to [Groovy](http://en.wikipedia.org/wiki/Groovy_%28programming_language%29) presentation ready for my local Java User's Group and I've pretty much got it together. What I'd like to see is what you all think I just have to cover.
Remember, this is an introductory presentation. Most of the people are experienced Java developers, but I'm pretty sure they have little to no Groovy knowledge. I won't poison the well by mentioning what I've already got down to cover as I want to see what the community has to offer.
What are the best things I can cover (in a 1 hour time frame) that will help me effectively communicate to these Java developers how useful Groovy could be to them?
p.s. I'll share my presentation here later for anyone interested.
as promised now that my presentation has been presented [here it is](http://docs.google.com/Presentation?id=dhd8kj8d_17cx6gwfch)
|
I don't know anything about groovy so in a sense I've qualified to answer this...
I would want you to:
* Tell me why I would want to use Scripting (in general) as opposed to Java-- what does it let me do quicker (as in development time), what does it make more readable. Give tantalising examples of ways I can use chunks of scripting in my mostly Java app. You want to make this relevant to Java devs moreso than tech-junkies.
* With that out of the way, why Groovy? Why not Ruby, Python or whatever (which are all runnable on the JVM).
* Don't show me syntax that Java can already do (if statements, loops etc) or if you do make it quick. It's as boring as hell to watch someone walk through language syntax 101 for 20min.
+ For syntax that has a comparible feature in Java maybe show them side by side quickly.
+ For syntax that is not in Java (closures etc) you can talk to them in a bit more detail.
* Remember those examples from the first point. Show me one, fully working (or at least looking like it is).
* At the end have question time. That is **crazy** important, and with that comes a burden on you to be a psuedo-guru :P.
I'm not sure about how the Java6 scripting support works but I'm fairly sure it can be made secure. I remember something about defining the API the script can use before it's run.
If this is the case then an example you could show would be some thick-client application (e.g. a music player) where users can write their own scripts with an API you provide them in Groovy which allows them to script their app in interesting and secure ways (e.g. creating custom columns in the playlist)
|
I'd go for:
1. Closures
2. Duck typing
3. Builders (XML builder and slurper)
4. GStrings
5. Grails
|
What is a MUST COVER in my Groovy presentation?
|
[
"",
"java",
"groovy",
""
] |
It's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?
|
A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference.
[Here's an article](http://javatechniques.com/blog/low-memory-deep-copy-technique-for-java-objects/) about how to do this efficiently.
Caveats: It's possible for classes to override serialization such that new instances are *not* created, e.g. for singletons. Also this of course doesn't work if your classes aren't Serializable.
|
A few people have mentioned using or overriding `Object.clone()`. Don't do it. `Object.clone()` has some major problems, and its use is discouraged in most cases. Please see Item 11, from "[Effective Java](http://java.sun.com/docs/books/effective/)" by Joshua Bloch for a complete answer. I believe you can safely use `Object.clone()` on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.
The schemes that rely on serialization (XML or otherwise) are kludgy.
There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. `String`s) do not need to be copied. As an aside, you should favor immutability for this reason.
|
How do you make a deep copy of an object?
|
[
"",
"java",
"class",
"clone",
""
] |
When I use the default java locale on my linux machine it comes out with the US locale settings, where do I change this so that it comes out with the correct locale?
|
I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC\_\* environment variables are set appropriately.
The locale [manpage](http://linux.die.net/man/1/locale) has full info on said environment variables.
|
With the `user.language`, `user.country` and `user.variant` properties.
Example:
`java -Duser.language=th -Duser.country=TH -Duser.variant=TH SomeClass`
|
Setting java locale settings
|
[
"",
"java",
"locale",
""
] |
How do I change font size on the DataGridView?
|
```
private void UpdateFont()
{
//Change cell font
foreach(DataGridViewColumn c in dgAssets.Columns)
{
c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
}
}
```
|
In winform datagrid, right click to view its properties. It has a property called DefaultCellStyle. Click the ellipsis on DefaultCellStyle, then it will present Cell Style Builder window which has the option to change the font size.
Its easy.
|
WinForms DataGridView font size
|
[
"",
"c#",
"winforms",
"datagridview",
""
] |
Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it?
Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).
**Clarification:** I do not mean HTML DOM scripting performed *after* the document is transformed, nor do I mean XSL transformations *initiated* by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.
|
To embed JavaScript for the aid of transformation you can use <xsl:script>, but [it is limited](http://www.topxml.com/xsl/tutorials/intro/xsl10.asp) to Microsoft's XML objects implementation. Here's an [example](https://oxampleski.googlecode.com/svn/trunk/XSL):
**scripted.xml**:
```
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="scripted.xsl"?>
<data a="v">
ding dong
</data>
```
**scripted.xsl**:
```
<?xml version="1.0" encoding="ISO-8859-1"?>
<html xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:script implements-prefix="local" language="JScript"><![CDATA[
function Title()
{
return "Scripted";
}
function Body(text)
{
return "/" + text + "/";
}
]]></xsl:script>
<head>
<title><xsl:eval>Title()</xsl:eval></title>
</head>
<body>
<xsl:for-each select="/data"><xsl:eval>Body(nodeTypedValue)</xsl:eval></xsl:for-each>
</body>
</html>
```
The result in Internet Explorer (or if you just use MSXML from COM/.NET) is:
```
<html>
<head>
<title>Scripted</titlte>
</head>
<body>
/ding dong/
</body>
</html>
```
It doesn't appear to support the usual XSL template constructs and adding the root node causes MSXML to go into some sort of standards mode where it won't work.
I'm not sure if there's any equivalent functionality in standard XSL, but I can dream.
|
I don't think you can execute JavaScript code embedded inside XML documents. Like, helios mentioned, you can preform the transformation using JavaScript.
JavaScript is embedded as CDATA in most cases, which is usually used **after** the XSL transformation has taken place. If I understand correctly, you want to have an executable <script> tag in your XML.
You could use XSL parameters and templates if you need a more control on your transformations. You can set these values in your XSLT and then pass them to exec(). Mozilla supports [setting parameters](http://developer.mozilla.org/en/The_XSLT%2f%2fJavaScript_Interface_in_Gecko/Setting_Parameters) in XSL, but I'm not sure about other browsers.
Also, cross-browser JavaScript/XSLT is a pain in the neck. [Mozilla's JavaScript/XSLT interface](http://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations) is very different than [IE's](http://www.learn-ajax-tutorial.com/Xslt.php), so you might want to rely on a browser-independent library like [jQuery's XSLT](http://www.jongma.org/webtools/jquery/xslt/).
|
JavaScript in client-side XSL processing?
|
[
"",
"javascript",
"xslt",
"browser",
""
] |
I have a three-tier application which is installed in corporate environments. With every server version update, all clients have to be updated, too. Currently, I provide an MSI package which is automatically deployed via Active Directory, however my customers (mostly with 20-300 users each) seem to hate the MSI solution because it is
* Complicated to get it running (little Active Directory knowledge);
* The update process can't be triggered by the server, when a new version is detected;
* Customers can't install multiple versions of the client (e.g. 2.3 and 2.4) at the same time to speak to different servers;
* The update process itself doesn't always work as expected (sometimes very strange behaviour healing itself after a few hours)
I've now made a few experiments with ClickOnce, but that way to unflexible for me and too hard to integrate in my automated build process. Also, it produces cryptic error messages which would surely confuse my customers.
I would have no problems to write the update logic myself, but there the problem is that the users running to self-updating applications have too restricted rights to perform an update. I've found that they are able to write to their Local Application Data directory, but I don't think this would be the typical place to install application files into.
Do you know a way to an update that "just works"?
|
You can somewhat replicate what ClickOnce does, just adjust it for your needs.
1. Create a lightweight executable that checks a network/web location for updates.
2. If there are updates, it copies them locally and replaces the "real" application files.
3. It runs the "real" application.
The location for the application files should be determined by permissions and operating system. If users only have write permission to a limited set of folders, then you don't have a choice but use one of these folders. Another option is provide an initial installation package that installs the lightweight executable and grants r/w permission on a specific folder such as "C:\Program Files\MyApp". This approach usually requires a buy-in from IT.
I hope this helps.
|
It is really hard to provide you exact answers because critical information about the client side installer is not explicit. Do you install client side files into Program Files? Then you may meet problems when users are restricted.
You don't think Local Application Data is a folder to deploy application, but Google does. Its Chrome browser installs that way on Windows, and its automatic update process is even unnoticable (which may sound horrible). So why not deploy your application into this folder for restricted users? You may find more about Chrome installer here,
<http://robmensching.com/blog/archive/2008/09/04/Dissecting-the-Google-Chrome-setup.aspx>
|
Auto-updating in Corporate Environments (C#)
|
[
"",
"c#",
".net",
"auto-update",
""
] |
Is the return value of GetHashCode() guaranteed to be consistent assuming the same string value is being used? (C#/ASP.NET)
I uploaded my code to a server today and to my surprise I had to reindex some data because my server (win2008 64-bit) was returning different values compared to my desktop computer.
|
If I'm not mistaken, GetHashCode is consistent given the same value, but it is NOT guaranteed to be consistent across different versions of the framework.
From the MSDN docs on String.GetHashCode():
> The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.
|
I had a similar problem where I filled a database table with information which was dependent on String.GetHashCode (Not the best idea) and when I upgraded the server I was working on to x64 I noticed the values I was getting from String.GetHashCode were inconsistent with what was already in the table. My solution was to use my own version of GetHashCode which returns the same value as String.GetHashCode on a x86 framework.
Here's the code, don't forget to compile with "Allow unsafe code":
```
/// <summary>
/// Similar to String.GetHashCode but returns the same as the x86 version of String.GetHashCode for x64 and x86 frameworks.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static unsafe int GetHashCode32(string s)
{
fixed (char* str = s.ToCharArray())
{
char* chPtr = str;
int num = 0x15051505;
int num2 = num;
int* numPtr = (int*)chPtr;
for (int i = s.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 0x5d588b65));
}
}
```
|
Can I depend on the values of GetHashCode() to be consistent?
|
[
"",
"c#",
"hash",
""
] |
I've been looking for a *simple* Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over `500K+` generation (my needs don't really require anything much more sophisticated).
Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like `"AEYGF7K0DM1X"`.
|
## Algorithm
To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.
## Implementation
Here's some fairly simple and very flexible code for generating random identifiers. *Read the information that follows* for important application notes.
```
public class RandomString {
/**
* Generate a random string.
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String lower = upper.toLowerCase(Locale.ROOT);
public static final String digits = "0123456789";
public static final String alphanum = upper + lower + digits;
private final Random random;
private final char[] symbols;
private final char[] buf;
public RandomString(int length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException();
if (symbols.length() < 2) throw new IllegalArgumentException();
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}
/**
* Create an alphanumeric string generator.
*/
public RandomString(int length, Random random) {
this(length, random, alphanum);
}
/**
* Create an alphanumeric strings from a secure generator.
*/
public RandomString(int length) {
this(length, new SecureRandom());
}
/**
* Create session identifiers.
*/
public RandomString() {
this(21);
}
}
```
## Usage examples
Create an insecure generator for 8-character identifiers:
```
RandomString gen = new RandomString(8, ThreadLocalRandom.current());
```
Create a secure generator for session identifiers:
```
RandomString session = new RandomString();
```
Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:
```
String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);
```
## Use as session identifiers
Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.
There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.
The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.
## Use as object identifiers
Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.
Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.
Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." [The probability of a collision,](https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation) *p*, is approximately n2/(2qx), where *n* is the number of identifiers actually generated, *q* is the number of distinct symbols in the alphabet, and *x* is the length of the identifiers. This should be a very small number, like 2‑50 or less.
Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.
## Comparison with UUIDs
According to their specification, [UUIDs](https://www.rfc-editor.org/rfc/rfc4122#section-6) are not designed to be unpredictable, and *should not* be used as session identifiers.
UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.
UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.
|
Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use `uuid.replace("-", "")`
```
import java.util.UUID;
public class randomStringGenerator {
public static void main(String[] args) {
System.out.println(generateString());
}
public static String generateString() {
String uuid = UUID.randomUUID().toString();
return "uuid = " + uuid;
}
}
```
### Output
```
uuid = 2d7428a6-b58c-4008-8575-f05549f16316
```
|
How to generate a random alpha-numeric string
|
[
"",
"java",
"string",
"random",
"alphanumeric",
""
] |
I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to [this question](https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java) only in .Net.
|
In Urlmon.dll, there's a function called `FindMimeFromData`.
From the documentation
> MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to `FindMimeFromData`.
|
I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it.
```
using System.Runtime.InteropServices;
```
...
```
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
System.UInt32 pBC,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
System.UInt32 cbSize,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
System.UInt32 dwMimeFlags,
out System.UInt32 ppwzMimeOut,
System.UInt32 dwReserverd
);
public static string getMimeFromFile(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException(filename + " not found");
byte[] buffer = new byte[256];
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
if (fs.Length >= 256)
fs.Read(buffer, 0, 256);
else
fs.Read(buffer, 0, (int)fs.Length);
}
try
{
System.UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
System.IntPtr mimeTypePtr = new IntPtr(mimetype);
string mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception e)
{
return "unknown/unknown";
}
}
```
|
Using .NET, how can you find the mime type of a file based on the file signature not the extension
|
[
"",
"c#",
"mime",
"mime-types",
""
] |
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
```
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
```
|
Mine would be this in c# 3.0 :)
```
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
```
Basically, the least amount of iterations will always be:
```
loop assemblies
loop types
see if implemented.
```
|
This worked for me. It loops though the classes and checks to see if they are derrived from myInterface
```
foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
//do stuff
}
```
|
Getting all types that implement an interface
|
[
"",
"c#",
"optimization",
"reflection",
"lambda",
"c#-3.0",
""
] |
I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox 360 and found it very good, but it's not free. I know the Intel [VTune](https://en.wikipedia.org/wiki/VTune), but it's not free either.
|
[CodeXL](https://gpuopen.com/archived/legacy-codexl/) has now superseded the End Of Line'd [AMD Code Analyst](https://web.archive.org/web/20120607044224/http://developer.amd.com/tools/CodeAnalyst/Pages/default.aspx) and both are free, but not as advanced as VTune.
There's also [Sleepy](http://www.codersnotes.com/sleepy/), which is very simple, but does the job in many cases.
Note: **All three of the tools above are unmaintained since several years.**
|
[Very Sleepy](http://www.codersnotes.com/sleepy/) is a C/C++ CPU profiler for Windows systems (free).
|
What's the best free C++ profiler for Windows?
|
[
"",
"c++",
"windows",
"profiling",
""
] |
I'm currently trying to port a SIP stack library (pjSIP) to the PSP Console (using the PSPSDK toolchain), but I'm having too much trouble with the makefiles (making the proper changes and solving linking issues).
Does anyone know a good text, book or something to get some insight on porting libraries?
The only documentation this project offers on porting seems too dedicated to major OS's.
|
Look at other libraries that were ported over to the PSP. Doing diffs between a linux version of a library, and a PSP version should show you.
Also, try to get to know how POSIX compatible the PSP is, that will tell you how big the job of porting the library over is.
|
The PSP is not UNIX and is not POSIX compliant, however the open source toolchain is composed by gcc 4.3, bintutils 1.16.1 and newlib 1.16.
Most of the C library is already present and can compile most of your code. Lots of libraries have been ported just by invoking the configure script with the following arguments:
```
LDFLAGS="-L$(psp-config --pspsdk-path)/lib -lc -lpspuser" ./configure --host psp --prefix=$(pwd)/../target/psp
```
However you might need to patch your configure and configure.ac scripts to know the host mips allegrex (the PSP cpu), to do that you search for a mips\*-*-*) line and clone it to the allegrex like:
```
mips*-*-*)
noconfigdirs="$noconfigdirs target-libgloss"
;;
mipsallegrex*-*-*)
noconfigdirs="$noconfigdirs target-libgloss"
;;
```
Then you run the make command and hope that newlib has all you need, if it doesn't then you just need to create alternatives to the functions you are missing.
|
Help on Porting a SIP library to PSP
|
[
"",
"c++",
"porting",
"sip",
"playstation-portable",
"pspsdk",
""
] |
From the *Immediate Window* in Visual Studio:
```
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
```
It seems that they should both be the same.
The old FileSystemObject.BuildPath() didn't work this way...
|
This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.
[System.IO.Path.Combine](http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx)
"If path2 contains an absolute path, this method returns path2."
[Here's the actual Combine method](http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264) from the .NET source. You can see that it calls [CombineNoChecks](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745), which then calls [IsPathRooted](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d) on path2 and returns that path if so:
```
public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
```
I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().
|
I wanted to solve this problem:
```
string sample1 = "configuration/config.xml";
string sample2 = "/configuration/config.xml";
string sample3 = "\\configuration/config.xml";
string dir1 = "c:\\temp";
string dir2 = "c:\\temp\\";
string dir3 = "c:\\temp/";
string path1 = PathCombine(dir1, sample1);
string path2 = PathCombine(dir1, sample2);
string path3 = PathCombine(dir1, sample3);
string path4 = PathCombine(dir2, sample1);
string path5 = PathCombine(dir2, sample2);
string path6 = PathCombine(dir2, sample3);
string path7 = PathCombine(dir3, sample1);
string path8 = PathCombine(dir3, sample2);
string path9 = PathCombine(dir3, sample3);
```
Of course, all paths 1-9 should contain an equivalent string in the end. Here is the PathCombine method I came up with:
```
private string PathCombine(string path1, string path2)
{
if (Path.IsPathRooted(path2))
{
path2 = path2.TrimStart(Path.DirectorySeparatorChar);
path2 = path2.TrimStart(Path.AltDirectorySeparatorChar);
}
return Path.Combine(path1, path2);
}
```
I also think that it is quite annoying that this string handling has to be done manually, and I'd be interested in the reason behind this.
|
Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?
|
[
"",
"c#",
".net",
"file",
""
] |
I am a novice programmer who is trying to teach myself to code, specifically in C#. I've taken on a project from a friend of mine and I am not sure what I need to know to get the project done. I suppose the issue is I don't know what I need to know to even get the project started.
I do have many of the basics of object oriented programming, classes, methods and what-not, but when I sit down to code-I don't know where to begin looking to accomplish even basic tasks. I don't know syntax or what the language is capable of with the tools provided. I have read some books, but they mostly seem to be about the concepts and theories about OOP within C# with minimal syntax.
I guess the question is where do I look to learn the syntax-is there some sort of repository of classes and methods that I am missing with examples of how to use the tools it contains? I am stuck in a place of not knowing where to go/look next.
Thanks for any help
|
[**Getting started with Visual C#**](http://msdn.microsoft.com/en-us/library/a72418yk(VS.80).aspx).
|
One of the things I usually recommend to Junior Developers on my projects who are looking for a better picture of how things work is to get familiar with your F10/F11 keys in Visual Studio by stepping through open source projects written in C#.
Pick something you find interesting from Codeplex or Sourceforge or Google code (there's a topic here about good code to read) and download the source code. Open it in Visual Studio and choose "Debug -> Step Into". From there, let the debugger be your guide through the code.
F11 lets you dig deeper, SHIFT+F11 steps you back a level.
It really can teach you a lot about how functioning code is structured because it leads you through the flow and provides a pretty good tour of functionality in the code.
It also works well with books and other materials because, when you see something you don't understand, you can go looking for a better explanation.
This is something I do myself quite often to familiarize myself with a given codebase, whether it's open source or a paying project with existing code.
|
How do I figure out what I need to know?
|
[
"",
"c#",
"syntax",
"repository",
""
] |
The DOM method `getChildNodes()` returns a `NodeList` of the children of the current `Node`. Whilst a `NodeList` is ordered, is the list guaranteed to be in document order?
For example, given `<a><b/><c/><d/></a>` is `a.getChildNodes()` guaranteed to return a `NodeList` with `b`, `c` and `d` *in that order*?
The [javadoc](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()) isn't clear on this.
|
In my experience, yes. The [DOM spec](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987) isn't any clearer. If you're paranoid, try something like
```
current = node.firstChild;
while(null != current) {
...
current = current.nextSibling;
}
```
|
A document-ordered node list is the behavior in other implementations of the DOM, such as Javascript's or Python's. And a randomly-ordered node list would be utterly useless. I think it's safe to depend on nodes being returned in document order.
|
Order of DOM NodeList returned by getChildNodes()
|
[
"",
"java",
"xml",
"dom",
""
] |
I've been using the YUI Components and want to begin using the Loader Utility to specify my dependencies on my page. From your experience, is the YUI Loader Utility a reliable way to load Javascript dependencies in web pages?
|
Yes, YUI Loader is reliable on all A-grade browsers. For a list of which browsers Yahoo! considers A-grade, check out the [Graded Browser Support Chart](http://developer.yahoo.com/yui/articles/gbs/).
|
Generally yes. Nothing should go wrong, and assuredly if it did, yahoo would be on the problem in no time!
|
Is the YUI Loader Utility reliable?
|
[
"",
"javascript",
"yui",
""
] |
Given the following example, why do I have to explicitly use the statement `b->A::DoSomething()` rather than just `b->DoSomething()`?
Shouldn't the compiler's overload resolution figure out which method I'm talking about?
I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)
```
class A
{
public:
int DoSomething() {return 0;};
};
class B : public A
{
public:
int DoSomething(int x) {return 1;};
};
int main()
{
B* b = new B();
b->A::DoSomething(); //Why this?
//b->DoSomething(); //Why not this? (Gives compiler error.)
delete b;
return 0;
}
```
|
The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done *afterwards*. In your case this means that the compiler sees `B::DoSomething`. It then tries to match the argument list, which fails.
One solution would be to pull down the overload from `A` into `B`'s scope:
```
class B : public A {
public:
using A::DoSomething;
// …
}
```
|
Overload resolution is one of the ugliest parts of C++
Basically the compiler finds a name match "DoSomething(int)" in the scope of B, sees the parameters don't match, and stops with an error.
It can be overcome by using the A::DoSomething in class B
```
class A
{
public:
int DoSomething() {return 0;}
};
class B : public A
{
public:
using A::DoSomething;
int DoSomething(int x) {return 1;}
};
int main(int argc, char** argv)
{
B* b = new B();
// b->A::DoSomething(); // still works, but...
b->DoSomething(); // works now too
delete b;
return 0;
}
```
|
C++ overload resolution
|
[
"",
"c++",
"function",
"overloading",
"resolution",
""
] |
I have 2 strings that I'd like to compare, and return the positions of the different characters in the second string.
For example, if I have
1. `"The brown fox jumps over the lazy dog"`
2. `"The quick brown fox jumped over the lazy dog"`
I want it to highlight "quick" and "ed". What's the best way to go about this in PHP?
|
This might do the trick:
[PHP Inline Diff](http://software.zuavra.net/inline-diff/)
[Text\_Diff](http://pear.php.net/package/Text_Diff)
|
The algorithm you're looking for is the "longest common substring problem". From there it is easy to determine the differences. See Wikipedia:
<http://en.wikipedia.org/wiki/Diff#Algorithm>
|
How do you find the difference between 2 strings in PHP?
|
[
"",
"php",
"string",
"comparison",
""
] |
I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this:
```
select
customerName,
customerId,
(
select count(*)
from Purchases
where Purchases.customerId=customerData.customerId
) as numberTransactions
from customerData
```
And what I want to do is order the table by the number of transactions, but when I use
```
order by numberTransactions
```
It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as `this`, or `self`?
|
use the field number, in this case:
```
order by 3
```
|
Sometimes you have to wrestle with SQL's syntax (expected scope of clauses)
```
SELECT *
FROM
(
select
customerName,
customerId,
(
select count(*)
from Purchases
where Purchases.customerId=customerData.customerId
) as numberTransactions
from customerData
) as sub
order by sub.numberTransactions
```
Also, a solution using JOIN is correct. Look at the query plan, SQL Server should give identical plans for both solutions.
|
How to reference a custom field in SQL
|
[
"",
"sql",
"sql-server",
""
] |
We have an Excel 2002/XP based application that interacts with SQL 2000/5 to process fairly complex actuarial calculations. The application performs its function well, but it's difficult to manage.
We're trying to create a "controller" application or service that can manage and monitor these various instances of Excel (start/stop/process commands etc) but it's a bit of an InterOp nightmare unfortunately.
Does anyone have a good (i.e. working) example of doing something like this in VB.Net or C#?
|
Don't do it!
We tried for weeks to get something like that to work and it simply does not behave as advertised. Don't even start - give up immediately!
The only options that you really have is a heavy server-side MOSS based implementation - Excel (Web) services (they call it something like that). Windows based COM Excel interop is pretty much dead and will be replaced by MOSS.
The other option is to use SpreadsheetGear. It is actually a fantastic product
1. It is lightlingly fast
2. The engine is separate from the UI so you can use it to do Excel stuff server side (with no office installed)
3. Fairly cheap
4. Has an API similar to the existing Excel COM api so moving code across is relatively easy
It all depends on the formulas that you need in your spreadsheet. Have a look at the formula list for Spreadsheet Gear and if there is a match go for it.
|
Interop works fine except that you always end up with references to Excel objects that aren't released, so Excel instances won't close. The following KB article explains why:
<http://support.microsoft.com/default.aspx/kb/317109/EN-US/>
You can avoid the problem if you have very carefully written code for a limited set of Interop scenarios. But in the general case it's very difficult to get it working reliably.
|
Does anyone have a good example of controlling multiple Excel instances from a .Net app?
|
[
"",
"c#",
".net",
"vb.net",
"excel",
""
] |
What are the differences between `htmlspecialchars()` and `htmlentities()`. When should I use one or the other?
|
From the PHP documentation for [htmlentities](https://www.php.net/htmlentities):
> This function is identical to `htmlspecialchars()` in all ways, except with `htmlentities()`, all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for [htmlspecialchars](http://us.php.net/htmlspecialchars):
> Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use `htmlentities()` instead.
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use `htmlspecialchars` whenever possible.
For example:
```
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
```
|
`htmlspecialchars` may be used:
1. When there is no need to encode all characters which have their HTML equivalents.
If you know that the page encoding match the text special symbols, why would you use `htmlentities`? `htmlspecialchars` is much straightforward, and produce less code to send to the client.
For example:
```
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
```
The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.
2. When the data will be processed not only through a browser (to avoid decoding HTML entities),
3. If the output is XML (see [the answer by Artefacto](https://stackoverflow.com/a/3614330/240613)).
|
htmlentities() vs. htmlspecialchars()
|
[
"",
"php",
""
] |
I'd like to create a spring bean that holds the value of a double. Something like:
```
<bean id="doubleValue" value="3.7"/>
```
|
Declare it like this:
```
<bean id="doubleValue" class="java.lang.Double">
<constructor-arg index="0" value="3.7"/>
</bean>
```
And use like this:
```
<bean id="someOtherBean" ...>
<property name="value" ref="doubleValue"/>
</bean>
```
|
It's also worth noting that depending on your need defining your own bean may not be the best bet for you.
```
<util:constant static-field="org.example.Constants.FOO"/>
```
is a good way to access a constant value stored in a class and default binders also work very well for conversions e.g.
```
<bean class="Foo" p:doubleValue="123.00"/>
```
I've found myself replacing many of my beans in this manner, coupled with a properties file defining my values (for reuse purposes). What used to look like this
```
<bean id="d1" class="java.lang.Double">
<constructor-arg value="3.7"/>
</bean>
<bean id="foo" class="Foo">
<property name="doubleVal" ref="d1"/>
</bean>
```
gets refactored into this:
```
<bean
id="propertyFile"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:my.properties"
/>
<bean id="foo" class="Foo" p:doubleVal="${d1}"/>
```
|
How do I create a spring bean for a Java double primitive?
|
[
"",
"java",
"spring",
"double",
""
] |
I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone.
I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian.
One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up.
I'm willing to give it another try. Can anyone help me?
|
Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs.
* <http://descriptor-tips.blogspot.com/>
* <http://descriptors.blogspot.com/>
|
Yeah, The strings in Symbian is nightmarish.. atleast when you start with..
Here are few good references to help:
* [Introducing the RBuf Descriptor](http://developer.symbian.com/main/downloads/papers/RBuf/Introduction_to_RBuf_v1.0.pdf) from [Symbian Developer](http://developer.symbian.com)
* [Comparing C strings and descriptors](http://wiki.forum.nokia.com/index.php/Comparing_C_strings_and_descriptors) from [Forum Nokia](http://www.forum.nokia.com/) discussion
* [Using Symbian OS String Descriptors](http://www.newlc.com/Using-Symbian-OS-String.html) from [NewLC](http://www.newlc.com/)
|
Tutorial on understanding strings in Symbian
|
[
"",
"c++",
"symbian",
"carbide",
""
] |
I'm currently working on a ray-tracer in C# as a hobby project. I'm trying to achieve a decent rendering speed by implementing some tricks from a c++ implementation and have run into a spot of trouble.
The objects in the scenes which the ray-tracer renders are stored in a KdTree structure and the tree's nodes are, in turn, stored in an array. The optimization I'm having problems with is while trying to fit as many tree nodes as possible into a cache line. One means of doing this is for nodes to contain a pointer to the left child node only. It is then implicit that the right child follows directly after the left one in the array.
The nodes are structs and during tree construction they are succesfully put into the array by a static memory manager class. When I begin to traverse the tree it, at first, seems to work just fine. Then at a point early in the rendering (about the same place each time), the left child pointer of the root node is suddenly pointing at a null pointer. I have come to the conclusion that the garbage collecter has moved the structs as the array lies on the heap.
I've tried several things to pin the addresses in memory but none of them seems to last for the entire application lifetime as I need. The 'fixed' keyword only seems to help during single method calls and declaring 'fixed' arrays can only be done on simple types which a node isn't. Is there a good way to do this or am I just too far down the path of stuff C# wasn't meant for.
Btw, changing to c++, while perhaps the better choice for a high performance program, is not an option.
|
Firstly, if you're using C# normally, you can't suddenly get a null reference due to the garbage collector moving stuff, because the garbage collector also updates all references, so you don't need to worry about it moving stuff around.
You can pin things in memory but this may cause more problems than it solves. For one thing, it prevents the garbage collector from compacting memory properly, and may impact performance in that way.
One thing I would say from your post is that using structs may not help performance as you hope. C# fails to inline any method calls involving structs, and even though they've fixed this in their latest runtime beta, structs frequently don't perform that well.
Personally, I would say C++ tricks like this don't generally tend to carry over too well into C#. You may have to learn to let go a bit; there can be other more subtle ways to improve performance ;)
|
What is your static memory manager actually doing? Unless it is doing something unsafe (P/Invoke, unsafe code), the behaviour you are seeing is a bug in your program, and not due to the behaviour of the CLR.
Secondly, what do you mean by 'pointer', with respect to links between structures? Do you literally mean an unsafe KdTree\* pointer? Don't do that. Instead, use an index into the array. Since I expect that all nodes for a single tree are stored in the same array, you won't need a separate reference to the array. Just a single index will do.
Finally, if you really really must use KdTree\* pointers, then your static memory manager should allocate a large block using e.g. Marshal.AllocHGlobal or another unmanaged memory source; it should both treat this large block as a KdTree array (i.e. index a KdTree\* C-style) **and** it should suballocate nodes from this array, by bumping a "free" pointer.
If you ever have to resize this array, then you'll need to update all the pointers, of course.
The basic lesson here is that unsafe pointers and managed memory do **not** mix outside of 'fixed' blocks, which of course have stack frame affinity (i.e. when the function returns, the pinned behaviour goes away). There is a way to pin arbitrary objects, like your array, using GCHandle.Alloc(yourArray, GCHandleType.Pinned), but you almost certainly don't want to go down that route.
You will get more sensible answers if you describe in more detail what you are doing.
|
Pinning pointer arrays in memory
|
[
"",
"c#",
"optimization",
"unsafe",
"raytracing",
""
] |
Given the following:
```
List<List<Option>> optionLists;
```
what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.
So we should end up with `List<Option>` where each item appears only once.
|
Ok, this will find the list of Option objects that have a Value appearing in *every* list.
```
var x = from list in optionLists
from option in list
where optionLists.All(l => l.Any(o => o.Value == option.Value))
orderby option.Value
select option;
```
It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.
|
Here's a much more efficent implementation:
```
static SortedDictionary<T,bool>.KeyCollection FindCommon<T> (List<List<T>> items)
{
SortedDictionary<T, bool>
current_common = new SortedDictionary<T, bool> (),
common = new SortedDictionary<T, bool> ();
foreach (List<T> list in items)
{
if (current_common.Count == 0)
{
foreach (T item in list)
{
common [item] = true;
}
}
else
{
foreach (T item in list)
{
if (current_common.ContainsKey(item))
common[item] = true;
else
common[item] = false;
}
}
if (common.Count == 0)
{
current_common.Clear ();
break;
}
SortedDictionary<T, bool>
swap = current_common;
current_common = common;
common = swap;
common.Clear ();
}
return current_common.Keys;
}
```
It works by creating a set of all items common to all lists processed so far and comparing each list with this set, creating a temporary set of the items common to the current list and the list of common items so far. Effectively an O(n.m) where n is the number of lists and m the number of items in the lists.
An example of using it:
```
static void Main (string [] args)
{
Random
random = new Random();
List<List<int>>
items = new List<List<int>>();
for (int i = 0 ; i < 10 ; ++i)
{
List<int>
list = new List<int> ();
items.Add (list);
for (int j = 0 ; j < 100 ; ++j)
{
list.Add (random.Next (70));
}
}
SortedDictionary<int, bool>.KeyCollection
common = FindCommon (items);
foreach (List<int> list in items)
{
list.Sort ();
}
for (int i = 0 ; i < 100 ; ++i)
{
for (int j = 0 ; j < 10 ; ++j)
{
System.Diagnostics.Trace.Write (String.Format ("{0,-4:D} ", items [j] [i]));
}
System.Diagnostics.Trace.WriteLine ("");
}
foreach (int item in common)
{
System.Diagnostics.Trace.WriteLine (String.Format ("{0,-4:D} ", item));
}
}
```
|
Fastest way to find common items across multiple lists in C#
|
[
"",
"c#",
""
] |
I have a table similar to this:
```
CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
```
I can use the parentid field to arrange data into a tree structure.
Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?
**UPDATE:** I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.
|
There are a few ways to do what you need in PostgreSQL.
* If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <http://www.postgresql.org/docs/8.3/interactive/tablefunc.html>
* Also check out the ltree contrib, which you could adapt your table to use: <http://www.postgresql.org/docs/8.3/interactive/ltree.html>
* Or you can traverse the tree yourself with a PL/PGSQL function.
Something like this:
```
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
```
|
Here is an example script using common table expression:
```
with recursive sumthis(id, val) as (
select id, value
from example
where id = :selectedid
union all
select C.id, C.value
from sumthis P
inner join example C on P.id = C.parentid
)
select sum(val) from sumthis
```
The script above creates a 'virtual' table called `sumthis` that has columns `id` and `val`. It is defined as the result of two selects merged with `union all`.
First `select` gets the root (`where id = :selectedid`).
Second `select` follows the children of the previous results iteratively until there is nothing to return.
The end result can then be processed like a normal table. In this case the val column is summed.
|
Is it possible to make a recursive SQL query?
|
[
"",
"sql",
"postgresql",
"recursive-query",
""
] |
It may not be best practice but are there ways of removing unsused classes from a third party's jar files. Something that looks at the way in which my classes are using the library and does some kind of coverage analysis, then spits out another jar with all of the untouched classes removed.
Obviously there are issues with this. Specifically, the usage scenario I put it though may not use all classes all the time.
But neglecting these problems, can it be done in principle?
|
There is a way.
The JarJar project does this AFAIR. The first goal of the JarJar project is to allow one to embed third party libraries in your own jar, changing the package structure if necessary. Doing so it can strip out the classes that are not needed.
Check it out at <http://code.google.com/p/jarjar/>.
Here is a link about shrinking jars: <http://sixlegs.com/blog/java/jarjar-keep.html>
|
There is a tool in Ant called a classfileset. You specify the list of root classes that you know you need, and then the classfileset recursively analyzes their code to find all dependencies.
Alternatively, you could develop a good test suite that exercises all of the functions that you need, then run your tests under a test coverage tool. The tool will tell you which classes (and statement in them) were actually utilized. This could give you an even smaller set of code than what you'd find with static analysis.
|
How do I strip the fluff out of a third party library?
|
[
"",
"java",
"optimization",
"size",
""
] |
Drawing a parallelgram is nicely supported with Graphics.DrawImage:
```
Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1),
new PointF(x2, y2), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
```
How, do you do 4 points (obviously the following is not supported, but this is what is wanted):
```
Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2),
new PointF(x3, y3), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
}
```
|
Closest I can find is [this information](http://vckicks.110mb.com/image-distortion.html), which is extremely laggy.
|
Normally you would do this with a 3x3 Matrix, but the Matrix class only lets you specify 6 values instead of 9. You might be able to do this in Direct X.
|
Is there any way to draw an image to use 4 points rather than 3 (perspective warp)
|
[
"",
"c#",
".net",
"gdi+",
""
] |
What are the best Java example sites? I'm looking for places that you go when you have a specific question and you want a little Java code snippet to solve it with.
|
[java2s](http://www.java2s.com/) is the best according to me. because -
1) Like mrlinx said "almost always has a sample on common stuff"
2) Stuffs are nicely organized by category, so, you can easily find out what you are looking for.
3) You can find codes for latest version of JDK
|
I like Java Almanac (now renamed www.exampledepot.com/). It has great examples and very pertinent questions, but it only goes through java 1.4, so unfortunately it's pretty out of date. It has good coverage of simple questions like "Quintessential Regular Expression Search and Replace Program" and "Reading Text from a File". Also covers some more complicated topics.
Another site I like is javapractices.com. This one answers questions at a little higher level than Java Almanac, for example "Modernize old code" or "Know the core libraries".
|
What are the best Java example sites?
|
[
"",
"java",
""
] |
I'd like to indicate to the user of a web app that a long-running task is being performed. Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle).
Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity).
And what do you call that spinning thing, anyways?
|
Google **Ajax activity indicator** to find lots of images and image generators (the "spinning" image itself is an animated GIF).
Here is [one link](http://www.ajaxload.info/) to get you started.
With the image in hand, use JQuery to toggle the visibility of the image (or perhaps its parent DIV tag). See [this link](http://skfox.com/2008/04/28/jquery-example-ajax-activity-indicator/) for some more info.
rp
|
this site will do it for you:
[ajaxload](http://www.ajaxload.info/)
and on OS X it's called the "Beachball" and I like to add "Of Death".
|
Javascript spinning wait hourglass-type thing
|
[
"",
"javascript",
"jquery",
""
] |
I just learned about how the Java Collections Framework implements data structures in linked lists. From what I understand, `Iterators` are a way of traversing through the items in a data structure such as a list. Why is this interface used? Why are the methods `hasNext()`, `next()` and `remove()` not directly coded to the data structure implementation itself?
From the Java website: [link text](http://java.sun.com/javase/6/docs/api/)
> public interface Iterator<E>
>
> An
> iterator over a collection. Iterator
> takes the place of Enumeration in the
> Java collections framework. Iterators
> differ from enumerations in two ways:
>
> * Iterators allow the caller to remove
> elements from the underlying
> collection during the iteration with
> well-defined semantics.* Method names
> have been improved.
>
> This interface is
> a member of the Java Collections
> Framework.
I tried googling around and can't seem to find a definite answer. Can someone shed some light on why Sun chose to use them? Is it because of better design? Increased security? Good OO practice?
Any help will be greatly appreciated. Thanks.
|
> Why is this interface used?
Because it supports the basic operations that would allow a client programmer to iterate over any kind of collection (note: not necessarily a `Collection` in the `Object` sense).
> Why are the methods... not directly
> coded to the data structure
> implementation itself?
They are, they're just marked Private so you can't reach into them and muck with them. More specifically:
* You can implement or subclass an `Iterator` such that it does something the standard ones don't do, without having to alter the actual object it iterates over.
* Objects that can be traversed over don't need to have their interfaces cluttered up with traversal methods, in particular any highly specialized methods.
* You can hand out `Iterators` to however many clients you wish, and each client may traverse in their own time, at their own speed.
* Java `Iterators` from the java.util package in particular will throw an exception if the storage that backs them is modified while you still have an `Iterator` out. This exception lets you know that the `Iterator` may now be returning invalid objects.
For simple programs, none of this probably seems worthwhile. The kind of complexity that makes them useful will come up on you quickly, though.
|
You ask: "Why are the methods hasNext(), next() and remove() not directly coded to the data structure implementation itself?".
The Java Collections framework chooses to define the Iterator interface as externalized to the collection itself. Normally, since every Java collection implements the `Iterable` interface, a Java program will call `iterator` to create its own iterator so that it can be used in a loop. As others have pointed out, Java 5 allows us to direct usage of the iterator, with a for-each loop.
Externalizing the iterator to its collection allows the client to control how one iterates through a collection. One use case that I can think of where this is useful is when one has an an unbounded collection such as all the web pages on the Internet to index.
In the classic GoF book, the contrast between internal and external iterators is spelled out quite clearly.
> A fundamental issue is deciding which party conrols the iteration, the iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator. Clients that use an external iterator must advance the traversal and request the next element explicitly from the iterator. In contrast, the client hands an internal iterator an operation to perform, and the iterator applies that operation to every element ....
>
> External iterators are more flexible than internal iterators. It's easy to compare two collections for equality with an external iterator, for example, but it's practically impossible with internal iterators ... But on the other hand, internal iterators are easier to use, because they define the iteration logic for you.
For an example of how internal iterators work, see Ruby's `Enumerable` API, which has internal iteration methods such as `each`. In Ruby, the idea is to pass a block of code (i.e. a closure) to an internal iterator so that a collection can take care of its own iteration.
|
What are the benefits of the Iterator interface in Java?
|
[
"",
"java",
"oop",
"collections",
"interface",
"iterator",
""
] |
In C++ we acquiring a resource in a constructor and release it in a destructor.
So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.
AFAIK java classes don't have destructors. So how does one do the resource management in Java.
For example:
```
public int foo() {
Resource f = new Resource();
DoSomething(f);
f.Release();
}
```
How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?
|
Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with:
```
public int foo() {
Resource f = new Resource();
try {
DoSomething(f);
}
finally {
f.Release();
}
}
```
|
This question dates to 2008 and therefore pertains to Java 6. Since then Java 7 has been released, which contains a new feature for Automatic Resource Management. For a more recent question that is relevant to Java 7 see this question:
[java techniques for automatic resource release? "prompt cleanup"?](https://stackoverflow.com/questions/6628611/java-techniques-for-automatic-resource-release-prompt-cleanup)
|
Painless resource management in java
|
[
"",
"java",
"resources",
""
] |
I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?
I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only.
|
I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?
If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:
```
public void sendHttpRequest(byte[] requestData, Socket connection) {
long startTime = System.nanoTime();
writeYourRequestData(connection.getOutputStream(), requestData);
byte[] responseData = readYourResponseData(connection.getInputStream());
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}
```
This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented).
|
`curl -s -w "%{time_total}\n" -o /dev/null http://server:3000`
|
How can I find the response time of a HTTP request through a Socket
|
[
"",
"java",
"http",
""
] |
I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?
|
This seems to work, though it is a bit hackish:
```
TimeSpan span;
if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
MessageBox.Show(span.ToString());
```
|
`DateTime.ParseExact` or `DateTime.TryParseExact` lets you specify the exact format of the input. After you get the `DateTime`, you can grab the `DateTime.TimeOfDay` which is a `TimeSpan`.
In the absence of `TimeSpan.TryParseExact`, I think an 'elegant' solution is out of the mix.
@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.
|
Parse string to TimeSpan
|
[
"",
"c#",
"timespan",
""
] |
I'm looking for a clear, concise and accurate answer.
Ideally as the actual answer, although links to good explanations welcome.
This also applies to VB.Net, but the keywords are different - `ByRef` and `ByVal`.
|
By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.
```
void Test1(string param)
{
param = "new value";
}
string s1 = "initial value";
Test1(s1);
// s1 == "initial value"
```
Using `out` or `ref` passes a reference to the variable specified in the call to the function. Any changes to the value of an `out` or `ref` parameter will be passed back to the caller.
Both `out` and `ref` behave identically except for one slight difference: `ref` parameters are required to be initialised before calling, while `out` parameters can be uninitialised. By extension, `ref` parameters are guaranteed to be initialised at the start of the method, while `out` parameters are treated as uninitialised.
```
void Test2(ref string param)
{
param = "new value";
}
void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}
string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"
```
**Edit**: As [dp](https://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105 "dp") points out, the difference between `out` and `ref` is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for `out` and implements `ref` (as `ByRef`) only, matching the support of the CLR.
|
One additional note about ref vs. out: The distinction between the two is enforced by the C# compiler. The CLR does not distinguish between between out and ref. This means that you cannot have two methods whose signatures differ only by an out or ref
```
void foo(int value) {}
// Only one of the following would be allowed
// valid to overload with ref
void foo(ref int value) {}
// OR with out
void foo(out int value) {}
```
|
What do ref, val and out mean on method parameters?
|
[
"",
"c#",
".net",
"vb.net",
""
] |
## Summary
Hi All,
OK, further into my adventures with custom controls...
In summary, here is that I have learned of three main "classes" of custom controls. Please feel free to correct me if any of this is wrong!
1. **UserControls** - Which inherit from *UserControl* and are contained within an *ASCX* file. These are pretty limited in what they can do, but are a quick and light way to get some UI commonality with designer support.
2. **Custom Composite Controls** - These are controls that inherit from *WebControl* where you add pre-existing controls to the control within the *CreateChildControls* method. This provides great flexibility, but lack of designer support without additional coding. They are highly portable though since they can be compiled into a DLL.
3. **Custom Rendered Controls** - Similar to Custom Composite Controls, these are added to a Web Control Library project. The rendering of the control is completely controlled by the programmer by overriding the *Render* method.
## My Thoughts..
OK, so while playing with custom composites, I found the following:
* You have little/no control over the HTML output making it difficult to "debug".
* The *CreateChildControls* (and subsequent methods) can get real busy with *Controls.Add(myControl)* everywhere.
* I found rendering tables (be it for layout or content) to be considerably awkward.
## The Question(s)..
So, I admit, I am new to this so I could be way off-base with some of my points noted above..
* Do you use Composites?
* Do you have any neat tricks to control the HTML output?
* Do you just say "to hell with it" and go ahead and create a custom rendered control?
**Its something I am keen to get really firm in my mind since I know how much *good* control development can cut overall development time.**
I look forward to your answers ^\_^
|
I say go ahead with the custom rendered control. I find that in most cases the composite can be easier done and used in a UserControl, but anything beyond that and you'd need to have a finer degree of control (pun unintended) to merit your own rendering strategy.
There maybe controls that are simple enough to merit a composite (e.g., a textbox combined with a javascript/dhtml based datepicker, for example) but beyond that one example, it looks like custom rendered controls are the way to go.
|
Here's another extension method that I use for custom rendering:
```
public static void WriteControls
(this HtmlTextWriter o, string format, params object[] args)
{
const string delimiter = "<2E01A260-BD39-47d0-8C5E-0DF814FDF9DC>";
var controls = new Dictionary<string,Control>();
for(int i =0; i < args.Length; ++i)
{
var c = args[i] as Control;
if (c==null) continue;
var guid = Guid.NewGuid().ToString();
controls[guid] = c;
args[i] = delimiter+guid+delimiter;
}
var _strings = string.Format(format, args)
.Split(new string[]{delimiter},
StringSplitOptions.None);
foreach(var s in _strings)
{
if (controls.ContainsKey(s))
controls[s].RenderControl(o);
else
o.Write(s);
}
}
```
Then, to render a custom composite in the RenderContents() method I write this:
```
protected override void RenderContents(HtmlTextWriter o)
{
o.WriteControls
(@"<table>
<tr>
<td>{0}</td>
<td>{1}</td>
</tr>
</table>"
,Text
,control1);
}
```
|
ASP.NET Custom Controls - Composites
|
[
"",
"c#",
".net",
"asp.net",
"user-controls",
"controls",
""
] |
I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.
Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.
I need to write the values out to a fixed length data file.
|
Aside from limiting the columns selected to reduce bandwidth and memory:
```
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
```
|
To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
```
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
```
|
Remove columns from DataTable in C#
|
[
"",
"c#",
"asp.net",
""
] |
How can I drop all tables whose names begin with a given string?
I think this can be done with some dynamic SQL and the `INFORMATION_SCHEMA` tables.
|
You may need to modify the query to include the owner if there's more than one in the database.
```
DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'
OPEN cmds
WHILE 1 = 1
BEGIN
FETCH cmds INTO @cmd
IF @@fetch_status != 0 BREAK
EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds
```
This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run.
I know that if I were going to do this against a production database, I'd be as careful as possible.
**Edit** Code sample fixed.
|
```
SELECT 'DROP TABLE "' + TABLE_NAME + '"'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
```
This will generate a script.
Adding clause to check existence of table before deleting:
```
SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
```
|
Drop all tables whose names begin with a certain string
|
[
"",
"sql",
"sql-server",
"dynamic-sql",
""
] |
Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the **inverse** of this:
```
foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
somethingableClass.DoSomething();
}
```
i.e. How to get/iterate through all the objects that *don't* implement a particular interface?
Presumably you'd need to start by upcasting to the highest level:
```
foreach(ParentType parentType in collectionOfRelatedObjects)
{
// TODO: iterate through everything which *doesn't* implement ISomethingable
}
```
Answer by solving the TODO: in the cleanest/simplest and/or most efficient way
|
this should do the trick:
```
collectionOfRelatedObjects.Where(o => !(o is ISomethingable))
```
|
Something like this?
```
foreach (ParentType parentType in collectionOfRelatedObjects) {
if (!(parentType is ISomethingable)) {
}
}
```
|
Best way to find out if an (upcast) instance doesn't implement a particular interface
|
[
"",
"c#",
".net",
"interface",
""
] |
I've seen examples like this:
```
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
```
and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.
|
That is perfectly acceptable, probably even the standard.
```
(public/private) static final TYPE NAME = VALUE;
```
where `TYPE` is the type, `NAME` is the name in all caps with underscores for spaces, and `VALUE` is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
```
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
```
That is legal and `ORIGIN` would then be a point at (3, 0).
|
I would highly advise against having a single constants class. It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable. Instead:
* If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.
* If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)
* If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.
|
What is the best way to implement constants in Java?
|
[
"",
"java",
"constants",
""
] |
I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.
|
A regular expression will do the trick with very little code:
```
import re
...
if re.match("^[A-Za-z0-9_-]*$", my_little_string):
# do something here
```
|
[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.
Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.
Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check\_trans is the one using the string.translate method.
Test code:
```
import string, re, timeit
pat = re.compile('[\w-]*$')
pat_inv = re.compile ('[^\w-]')
allowed_chars=string.ascii_letters + string.digits + '_-'
allowed_set = set(allowed_chars)
trans_table = string.maketrans('','')
def check_set_diff(s):
return not set(s) - allowed_set
def check_set_all(s):
return all(x in allowed_set for x in s)
def check_set_subset(s):
return set(s).issubset(allowed_set)
def check_re_match(s):
return pat.match(s)
def check_re_inverse(s): # Search for non-matching character.
return not pat_inv.search(s)
def check_trans(s):
return not s.translate(trans_table,allowed_chars)
test_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'
test_long_valid='a_very_long_string_that_is_completely_valid_' * 99
test_short_valid='short_valid_string'
test_short_invalid='/$%$%&'
test_long_invalid='/$%$%&' * 99
test_empty=''
def main():
funcs = sorted(f for f in globals() if f.startswith('check_'))
tests = sorted(f for f in globals() if f.startswith('test_'))
for test in tests:
print "Test %-15s (length = %d):" % (test, len(globals()[test]))
for func in funcs:
print " %-20s : %.3f" % (func,
timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))
print
if __name__=='__main__': main()
```
The results on my system are:
```
Test test_empty (length = 0):
check_re_inverse : 0.042
check_re_match : 0.030
check_set_all : 0.027
check_set_diff : 0.029
check_set_subset : 0.029
check_trans : 0.014
Test test_long_almost_valid (length = 5941):
check_re_inverse : 2.690
check_re_match : 3.037
check_set_all : 18.860
check_set_diff : 2.905
check_set_subset : 2.903
check_trans : 0.182
Test test_long_invalid (length = 594):
check_re_inverse : 0.017
check_re_match : 0.015
check_set_all : 0.044
check_set_diff : 0.311
check_set_subset : 0.308
check_trans : 0.034
Test test_long_valid (length = 4356):
check_re_inverse : 1.890
check_re_match : 1.010
check_set_all : 14.411
check_set_diff : 2.101
check_set_subset : 2.333
check_trans : 0.140
Test test_short_invalid (length = 6):
check_re_inverse : 0.017
check_re_match : 0.019
check_set_all : 0.044
check_set_diff : 0.032
check_set_subset : 0.037
check_trans : 0.015
Test test_short_valid (length = 18):
check_re_inverse : 0.125
check_re_match : 0.066
check_set_all : 0.104
check_set_diff : 0.051
check_set_subset : 0.046
check_trans : 0.017
```
The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test\_long\_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.
Using all(x in allowed\_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.
There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.
|
How do I verify that a string only contains letters, numbers, underscores and dashes?
|
[
"",
"python",
"regex",
"string",
""
] |
I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:
```
<html>
<head>
<title>www.mysmallwebsite.com</title>
</head>
<frameset>
<frame src="http://www.myIsv.com/myWebSite/" name="redir">
<noframes>
<p>Original location:
<a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a>
</p>
</noframes>
</frameset>
</html>
```
It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?
Edit:
This doesn't work both on IE and on Firefox (no plugins)
Thanks
|
Sessions are tied to the server **AND** the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do.
Try using apache mod rewrite to create a "passthrough redirection", the "**proxy**" flag ([P]) in the rule is the magic flag that you need
Documentation at <http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html>
|
What do you mean?
Are you saying that when you go from www.mysmallwebsite.com to www.myIsv.com/myWebSite/ then the PHP session is lost?
PHP recognizes the session with an ID (alpha-numeric hash generated on the server). The ID is passed from request to request using a cookie called PHPSESSID or something like that (you can view the cookies a websites sets with the help of your browser ... on Firefox you have Firebug + FireCookie and the wonderful Web Developer Toolbar ... with which you can view the list of cookies without a sweat).
So ... PHP is passing the session ID through the PHPSESSID cookie. But you can pass the session ID as a plain GET request parameters.
So when you place the html link to the ugly domain name, assuming that it is the same PHP server (with the same sessions initialized), you can put it like this ...
```
www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?>
```
I haven't worked with PHP for a while, but I think this will work.
|
PHP : session variable aren't usable when site is redirected
|
[
"",
"php",
"session",
"session-variables",
""
] |
I've been running Tomcat 5.5 with Java 1.4 for a while now with a huge webapp. Most of the time it runs fine, but sometimes it will just hang, with no exception generated, and no apparant way of getting it to run again other than re-starting Tomcat. The tomcat instance is allowed a gigabyte of memory on the heap, but rarely exceeds 300 MB. Has anyone else run into this issue, and is there a solution for it?
For clarification: I determined how much memory it is using via Task Manager and via Eclipse (I've also tried running it outside of Eclipse, but get the same problem eventually, though it takes a little longer). With Eclipse, I look at the memory allocated via its little (optional) memory pane and the amount allocated to javaw.exe via the task manager. I use the sysdeo? tomcat plugin for Eclipse.
|
For any jvm process, force a thread dump. In windows, this can be done with CTRL-BREAK, I believe, in the console window.
In \*nix, it is almost always "kill -3 jvm-pid".
This may show if you have threads waiting on db connection pool/thread pool, etc.
Another thing to check out is how many connections you have currently to the JVM -- either use NETSTAT or SysInternals utility such as tcpconn/tcpview (google it).
Also, try to run with the verbose:gc JVM flag. For Sun's JVM, run like "java -verbose:gc". This will show your garbage collections. If it is collecting a lot (FULL COLLECTIONS, expecially) then you probably have a memory leak. The full collections are costly, especially on large heaps like that.
How are you determining that only 300mb are being used?
|
It sounds like you're hitting a deadlock.
If you can reproduce it in a dev environment then try attaching a debugger once it's happened. Take a look at your threads and see if you have any deadlocks.
If you can't get a debugger to attach you should be able to generate a thread dump, as Dustin pointed out.
|
Why does Tomcat 5.5 (with Java 1.4, running on Windows XP 32-bit) suddenly hang?
|
[
"",
"java",
"windows",
"tomcat",
""
] |
Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:
```
ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567)
//do something
//...much later, a has been garbage-collected away.
ClassA aa = new ClassA(); //crash here.
```
At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?
---
EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.
---
EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.
---
EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.
Any help would be appreciated!
|
(this is what finally got everything to work for me)
Make sure EVERY socket that the socket in A connects to has
```
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);
```
set upon being initiated.
|
you can't rely on object being garbage collected in C# (i assume you're using c#, based on tagging) if it holds resources like being bound to the network resource like in your example, or holding some other kind of stream, a file stream would be a common example.
you have to assure to release the resources that the object is holding, so that it can be garbage collected. otherwise it won't be garbage collected, but remain living somewhere in the memory. your pseudocode example doesn't provide that you're doing the resources releasing, you just state that the object gets (should get) garbage collected.
|
Can't Re-bind a socket to an existing IP/Port Combination
|
[
"",
"c#",
".net",
"networking",
"sockets",
""
] |
How do I have two effects in jQuery run in `sequence`, not simultaneously? Take this piece of code for example:
```
$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal");
$("#projects").fadeIn("normal");
});
```
The `fadeOut` and the `fadeIn` run simultaneously, how do I make them run one after the other?
|
You can supply a callback to the effects functions that run after the effect has completed.
```
$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal", function() {
$("#projects").fadeIn("normal");
});
});
```
|
What you want is a queue.
Check out the reference page <http://api.jquery.com/queue/> for some working examples.
|
How to make jQuery effects run in sequence, not simultaneously?
|
[
"",
"javascript",
"jquery",
""
] |
What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects.
|
Not free. Not opensource. But I have found AgitarOne Agitator (<http://www.agitar.com/solutions/products/agitarone.html>) to be REALLY good for automatically generating unit tests AND looking for unwanted obscure side effects
|
It is interesting, but such **generated unit tests can actually be useful.** If you're working on a legacy application, it will be often hard to write correct, state-of-the-art unit tests.
Such generated tests (if you have a way of generating them of course) can then make sure that behavior of code stays intact during your changes, which then can help you **refactor the code and write better tests**.
Now about **generating itself**. I don't know about any magic tool, but you may want to search for JUnit functionality about including some tests in javadocs for methods. This would allow you to write some simple tests. And yes, it's actually of some value.
Second, you can just write "big" tests by hand. Of course, these wouldn't be unit tests *per se* (no isolation, potential side-effects, etc), but could be good first step. Especially if you have little time and a legacy application.
**Bonus Tip!** There is an excellent book "Working effectively with legacy code" with examples in Java, including techniques right to use in such situations. Unfortunately you would have to do some things manually, but you would have to do that at some step anyway.
|
Auto-generating Unit-Tests for legacy Java-code
|
[
"",
"java",
"unit-testing",
"legacy",
""
] |
I have a webapp that uses JNDI lookups to get a connection to the database.
The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.
Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.
```
public class DatabaseBean {
private static final Logger logger = Logger.getLogger(DatabaseBean.class);
private Connection conn;
private PreparedStatement prepStmt;
/**
* Zero argument constructor
* Setup generic databse connection in here to avoid redundancy
* The connection details are in /META-INF/context.xml
*/
public DatabaseBean() {
try {
InitialContext initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite");
conn = ds.getConnection();
}
catch (SQLException SQLEx) {
logger.fatal("There was a problem with the database connection.");
logger.fatal(SQLEx);
logger.fatal(SQLEx.getCause());
}
catch (NamingException nameEx) {
logger.fatal("There was a naming exception");
logger.fatal(nameEx);
logger.fatal(nameEx.getCause());
}
}
/**
* Execute a query. Do not use for statements (update delete insert etc).
*
* @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null.
* @see #executeUpdate() for running update, insert delete etc.
*/
public ResultSet executeQuery() {
ResultSet result = null;
try {
result = prepStmt.executeQuery();
logger.debug(prepStmt.toString());
}
catch (SQLException SQLEx) {
logger.fatal("There was an error running a query");
logger.fatal(SQLEx);
}
return result;
}
```
*SNIP*
```
public void close() {
try {
prepStmt.close();
prepStmt = null;
conn.close();
conn = null;
} catch (SQLException SQLEx) {
logger.warn("There was an error closing the database connection.");
}
}
}
```
This is inside a javabean that uses the database connection.
```
public LinkedList<ImportantNoticeBean> getImportantNotices() {
DatabaseBean noticesDBBean = new DatabaseBean();
LinkedList<ImportantNoticeBean> listOfNotices = new LinkedList<ImportantNoticeBean>();
try {
PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " +
"FROM importantnotices, users " +
"WHERE importantnotices.username = users.username " +
"AND NOW() >= date_from AND NOW() <= date_to;");
noticesDBBean.setPrepStmt(preStmt);
ResultSet result = noticesDBBean.executeQuery();
while (result.next()) {
ImportantNoticeBean noticeBean = new ImportantNoticeBean();
noticeBean.setAuthor(result.getString("pseudonym"));
noticeBean.setMessage(result.getString("message"));
noticeBean.setDateTo(result.getDate("date_to"));
noticeBean.setDateFrom(result.getDate("date_from"));
listOfNotices.add(noticeBean);
}
result.close();
} catch (SQLException SQLEx) {
logger.error("There was an error in ImportantNoticesBean.getImportantNotices()");
logger.error(SQLEx);
} finally {
noticesDBBean.close();
}
return listOfNotices;
}
<Context reloadable="true">
<Resource name="jdbc/mysite"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysite"
maxActive="10"
maxIdle="5"
maxWait="6000"
removeAbandoned="true"
logAbandoned="false"
removeAbandonedTimeout="20"
/>
</Context>
```
|
> The issue us that the connection does not close properly and is stuck in the 'sleep' mode
This was actually only half right.
The problem I ran into was actually that each app was defining a new connection to the database sever. So each time I closed all the connections App A would make a bunch of new connections as per it's WEB.xml config file and run happily. App B would do the same. The problem is that they are *independent pools* which try to grab up to the server defined limit. It is a kind of race condition I guess. So when App A has finished with the connections it sits waiting to to use them again until the timeout has passed while App B who needs the connection now is denied the resources even though App A has finished with the and should be back in the pool. Once the timeout has passed, the connection is freed up and B (or C etc) can get at it again.
e.g. if the limit is 10 (mySQL profile limit) and each app has been configured to use a max of 10 the there will be 20 attempts at connections. Obviously this is a bad situation.
The solution is to RTFM and put the [connection details in the right place](http://tomcat.apache.org/tomcat-5.5-doc/config/context.html). This does make shared posting a pain but there are ways around it (such as linking to other xml files from the context).
Just to be explicit: I put the connection details in the WEB.xml for each app and the had a fight about it.
|
You seem to be closing the connection properly - except for the case where prepStmt.close() throws a SQLException, I can't find a connection leak.
What pool implementation are you using? When you close a connection, the pool need not close the underlying MySQL connection immediately - after all that is the point of a connection pool! So from MySQL side, the connections would look alive, although your app is not using any; they might simply be held by the TC connection pool.
You might want to experiment with the settings of the connection pool.Ask it to shrink the pool when the system is idle. Or, ask it to refresh all connections periodically. Or, have a strict upper bound on the number of concurrent connections it ever gets from MySQL etc.
One way to check if your code has a connection leak is to force the ds.getConnection() to always open a new physical connection and conn.close() to release the connection (if your connection pool has settings for those). Then if you watch the connections on MySQL side, you might be able to figure out if the code really has a connection leak or not.
|
Java ConnectionPool connection not closing, stuck in 'sleep'
|
[
"",
"java",
"database",
"tomcat",
""
] |
In Javascript:
How does one find the coordinates (x, y, height, width) of every link in a webpage?
|
Using jQuery, it's as simple as:
```
$("a").each(function() {
var link = $(this);
var top = link.offset().top;
var left = link.offset().left;
var width = link.offset.width();
var height = link.offset.height();
});
```
|
without jquery:
```
var links = document.getElementsByTagName("a");
for(var i in links) {
var link = links[i];
console.log(link.offsetWidth, link.offsetHeight);
}
```
try this page for a func to get the x and y values:
<http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html>
However, if you're trying to add an image or something similar, I'd suggest using the a:after css selector.
|
Find coordinates of every link in a page
|
[
"",
"javascript",
"web",
"hyperlink",
"location",
""
] |
Most of our Eclipse projects have multiple source folders, for example:
* src/main/java
* src/test/java
When you right-click on a class and choose New JUnit Test, the default source folder for the new test is "src/main/java" (presumably the first source folder listed in the project properties).
Is there any way to change the default source folder for new JUnit tests, so that when I do the above action, the new test will be created in say the "src/test/java" folder by default?
|
I use [moreUnit](http://moreunit.sourceforge.net/), an Eclipse plugin to assist writing unit tests. Among other features, it lets you configure the default source folder of tests.
|
No.
Unless you change the plugin code, the default source folder is always the same as that containing the class you right clicked on (not necessarily the first source folder listed). I agree, it would be nice to be able to change it!
|
How to default the source folder for new JUnit tests in Eclipse?
|
[
"",
"java",
"eclipse",
"junit",
"usability",
""
] |
I'm using Flash to play an .flv movieclip on my site, but I want to have the .swf send trigger an event in my javascript when it start loading, starts playing and ends playing.
What is the best way to do that in Flash CS3 using Actionscript 3.0 ?
|
You need to use the "allowScriptAccess" flash variable in the HTML. You probably want to use "sameDomain" as the type. Note that if you go cross-domain, you also need to host a special file on the server called 'crossdomain.xml' which enables such scripting (the flash player will check for this. More info at <http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213&sliceId=2>
The call is the easy part. :-) In the Flash code, you'll use the ExternalInterface to do the call, as documented here:
<http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001655.html>
Short version: you say
> ExternalInterface.call("javascriptFunction", "argument")
|
A common way to do this is with the **ExternalInterface** class, which you can use to call JavaScript methods.
First define your JavaScript methods, for example:
```
<script language="JavaScript">
function startsPlaying()
{
// do something when the FLV starts playing
}
</script>
```
Then modify your ActionScript to call the JavaScript method at the appropriate time:
```
// inform JavaScript that the FLV has started playing
ExternalInterface.call("startsPlaying");
```
For more information, see the related Flash CS3 [documentation](http://livedocs.adobe.com/flash/9.0/main/00000342.html).
|
How can I make flash cs3, actionscript send events to javascript?
|
[
"",
"javascript",
"flash",
"actionscript",
""
] |
Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a [reactor pattern](http://en.wikipedia.org/wiki/Reactor_pattern "reactor pattern") written in [Boost.Asio](http://www.boost.org/doc/libs/release/libs/asio/index.html "Boost.Asio").
[Edit:] Running a synchronous connector in threads is not an option.
|
I know this is an old question, but consider looking at the new Boost.Mysql library: <https://anarthal.github.io/mysql/index.html>
|
<http://forums.mysql.com/read.php?45,183339,183339>
enjoy
Updated link to the original article showing how to do async mysql queries:
<http://jan.kneschke.de/projects/mysql/async-mysql-queries-with-c-api/>
|
Asynchronous Mysql connector
|
[
"",
"c++",
"mysql",
"c",
"asynchronous",
"boost-asio",
""
] |
How do I cast an `int` to an `enum` in C#?
|
From an int:
```
YourEnum foo = (YourEnum)yourInt;
```
From a string:
```
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}
```
From a number:
```
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
```
|
Just cast it:
```
MyEnum e = (MyEnum)3;
```
Check if it's in range using [`Enum.IsDefined`](http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx):
```
if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
```
|
How do I cast int to enum in C#?
|
[
"",
"c#",
"enums",
"casting",
"integer",
""
] |
I have a very large code base that contains extensive unit tests (using CppUnit). **I need to work out what percentage of the code is exercised by these tests**, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised.
Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and \*nix at least).
Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have.
Cheers,
|
### Which tool should I use?
This [article describes](http://web.archive.org/web/20090527141110/http://www.kimbly.com/blog/000331.html) another developers frustrations searching for C++ code coverage tools. The author's final solution was [Bullseye Coverage](http://www.bullseye.com/).
**[Bullseye Coverage](http://www.bullseye.com/) features:**
* [Cross Platform Support](http://www.bullseye.com/platform.html) (win32, unix, and embedded), (supports linux gcc compilers and MSVC6)
* [Easy to use](http://www.bullseye.com/usability.html) (up and running in a few hours).
* [Provides "best" metrics](http://www.bullseye.com/measurementTechnique.html): Function Coverage and Condition/Decision Coverage.
* Uses source code instrumentation.
As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing.
---
### Testing Linux vs Windows?
So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other. (Though Bullseye appears [to support both platforms](http://www.bullseye.com/platform.html)). But why aren't you doing continuous integration builds in both environments?? If you deliver to clients in both environments then you *need* to be testing in both.
For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build. Perhaps this can be easily accomplished with some virtualization software like [vmware](http://www.vmware.com/) or [virtualbox](http://www.virtualbox.org/). You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both.
|
If you can use [GNU GCC](http://gcc.gnu.org/onlinedocs/gcc/index.html) as your complier, then the [gcov](http://gcc.gnu.org/onlinedocs/gcc/Gcov.html) tool works well. It's very easy to fully automate the whole process.
|
How can I measure CppUnit test coverage (on win32 and Unix)?
|
[
"",
"c++",
"unit-testing",
"cross-platform",
"code-coverage",
"cppunit",
""
] |
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.
The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.
The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.
Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).
The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.
In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.
The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue:
* A - 1000 instances - low priority - max tasks 1
* B - 1000 instances - low priority - max tasks 1
* C - 1000 instances - low priority - max tasks 1
A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time.
It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
---
For reference, we might use the following interface:
```
namespace ThreadPool
{
class Task
{
public:
Task();
void run();
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void run(Task *inst);
void stop();
};
}
```
|
So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising :- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches).
APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite "transparent". If the work item performs an alertable wait (::SleepEx, ::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely.
|
> It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
What feature of the system's built-in thread pools make them unsuitable for your task? If you want to target XP and 2003 you can't use the new shiny Vista/2008 pools, but you can still use QueueUserWorkItem and friends.
|
Thread pool for executing arbitrary tasks with different priorities
|
[
"",
"c++",
"windows",
"multithreading",
""
] |
I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on `SQL Server 2005`.
I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the `sysadmin` role on their login - it was a single line query for the latter.
But how to find out which logins have a User Mapping to a particular (or any) database?
I can find the `sys.database_principals` and `sys.server_principals` tables. I have located the `sys.databases table`. I haven't worked out how to find out which users have rights on a database, and if so, what.
Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?
|
Here's how to do this. I ended up finding reference to a sproc in the MSDN docs. I pulled this from the sproc and wrapped it in a loop of all the databases known to the instance.
```
select DbRole = g.name, MemberName = u.name
from @NAME.sys.database_principals u, @NAME.sys.database_principals g, @NAME.sys.database_role_members m
where g.principal_id = m.role_principal_id
and u.principal_id = m.member_principal_id
and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'')
and u.name not in (''dbo'')
order by 1, 2
```
This then reports the users that have DBO who perhaps shouldn't. I've already revoked some admin access from some users that they didn't need. Thanks everyone!
|
Check out this msdn reference article on [Has\_Perms\_By\_Name](http://msdn.microsoft.com/en-us/library/ms189802.aspx). I think you're really interested in examples D, F and G
---
Another idea... I fired up SQL profiler and clicked on the ObjectExplorer->Security->Users. This resulted in (approx) the following query being issued.
```
SELECT *
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp
ON dp.grantee_principal_id = u.principal_id and dp.type = N'CO'
WHERE (u.type in ('U', 'S', 'G', 'C', 'K'))
ORDER BY [Name] ASC
```
|
How to write an SQL query to find out which logins have been granted which rights in Sql Server 2005?
|
[
"",
"sql",
"database",
""
] |
We are looking for a C++ Soap web services framework that support RPC, preferably open source.
Any recommendations?
|
WSO2 Web Services Framework for C++ (WSO2 WSF/C++), a binding of WSO2 WSF/C into C++ is a C++ extension for consuming Web Services in C++.
<http://wso2.org/projects/wsf/cpp>
Apache Axis is an open source, XML based Web service framework. It consists of a Java and a C++ implementation of the SOAP server, and various utilities and APIs for generating and deploying Web service applications.
<http://ws.apache.org/axis/>
|
<http://code.google.com/p/staff/>
Staff is Web Service Framework for C++ (service/component and client-side)/JavaScript(client-side) based on Apache Axis2/C.
Open-source, released with Apache License V2.0.
|
C++ web service framework
|
[
"",
"c++",
"xml",
"web-services",
"frameworks",
"xsd",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.