Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Here's some background on what I'm trying to do:
1. Open a serial port from a mobile device to a Bluetooth printer.
2. Send an EPL/2 form to the Bluetooth printer, so that it understands how to treat the data it is about to receive.
3. Once the form has been received, send some data to the printer which will be printe... | Flow control is the correct answer here, and it may not be present/implemented/applicable to your bluetooth connection.
Check out the Zebra specification and see if they implement, or if you can turn on, software flow control (xon, xoff) which will allow you to see when the various buffers are getting full.
Further, ... | Well I've found a way to do this based on the two suggestions already given. I need to set up my serial port object with the following:
```
serialPort.Handshake = Handshake.RequestToSendXOnXOff;
serialPort.WriteTimeout = 10000; // Could use a lower value here.
```
Then I just need to do the write call:
```
serialPor... | How do I force a serial port write method to wait for the line to clear before sending its data? | [
"",
"c#",
"windows-mobile",
"bluetooth",
"serial-port",
"zebra-printers",
""
] |
I have a Visual Studio solution with four C# projects in it. I want to step into the code of a supporting project in the solution from my main project, but when I use the "Step into" key, it just skips over the call into that other project. I've set breakpoints in the supporting project, and they're ignored, and I can'... | One thing to check for is that your supporting project assembly has not been installed in the GAC. Open a command prompt and run the following to make sure...
gacutil /l *assemblyName* | Not sure if this is it, but "Tools>Options>Debugging>General:Enable Just My Code" is a possibility. (I prefer to always leave this unchecked.) | Enable and disable "Step into" debugging on certain project in a Visual Studio solution | [
"",
"c#",
"visual-studio",
"debugging",
"step-into",
""
] |
I'm using NuSOAP on PHP 5.2.6 and I'm seeing that the max message size is only 1000 bytes (which makes it tough to do anything meaningful). Is this set in the endpoint's WSDL or is this something I can configure in NuSOAP? | Regarding the FUD about a "1000 bytes limit"... I looked up the nusoap\_client sourcecode and found that the limit is only effective for **debug output**.
This means all data is processed and passed on to the webservice (regardless of its size), but only the first 1000 bytes (or more precisely: characters) are shown i... | On a production box we use the PHP 5.2.5 built-in Soap-functions as server and NuSoap on PHP 4 and have successfully transferred messages larger than 1 MB.
I don't think that there is a limitation in either product, but you should check your settings in php.ini for
```
max_input_time (defaults to 60)
```
This... | How is the max size of a SOAP message determined? | [
"",
"php",
"soap",
"wsdl",
"nusoap",
""
] |
I'm trying to use `System.DirectoryServices` in a web site project and I'm getting this error:
> The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?)
My project has a reference to `System.DirectoryServices` in `web.config`:
```
<add assembly... | Is the web-server (IIS or whatever) configured to run the folder as an application (i.e. shows as a cog), and is it using the correct version of ASP.NET? If it is running as 1.1, bits of it might work - but it would fail to find that 2.0 assembly in the 1.1 GAC. | 1. Right click on References under your solution.
2. Select Add Reference.
The reference can be found under the Framework Assemblies list.
Select *System.DirectoryServices* and click Add. | System.DirectoryServices is not recognised in the namespace 'System' | [
"",
"c#",
".net",
"directoryservices",
""
] |
I have to read CSV files line by line which can be 10 to 20 Meg. `file()` is useless and I have to find the quickest way.
I have tried with `fgets()`, which runs fine, but I don't know if it reads a small block each time I call it, or if it caches a bigger one and optimize file I/O.
Do I have to try the `fread()` way,... | You ought to be using [fgetcsv()](http://www.php.net/fgetcsv) if possible.
Otherwise, there is always fgets(). | stream\_get\_line is apparently more efficient than fgets for large files. If you specify a sensible maximum length for the read I don't see any reason why PHP would have to 'read ahead' to read a line in, as you seem to be worrying.
If you want to use CSVs then fgetcsv will return results in a slightly more sensible ... | The best way to read large files in PHP? | [
"",
"php",
"large-files",
""
] |
I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND c... | I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it.
```
public class RangeValidatorEx : B... | A CustomValidator should work. I'm not sure what you mean by "pass the 2 ranges values from the server-side". You could validate it on the server-side using a validation method like this:
```
void ValidateRange(object sender, ServerValidateEventArgs e)
{
int input;
bool parseOk = int.TryParse(e.Value, out inpu... | Asp.Net : Extended range validation | [
"",
"c#",
"asp.net",
"validation",
""
] |
I have a large c# solution file (~100 projects), and I am trying to improve build times. I think that "Copy Local" is wasteful in many cases for us, but I am wondering about best practices.
In our .sln, we have application A depending on assembly B which depends on assembly C. In our case, there are dozens of "B" and ... | In a previous project I worked with one big solution with project references and bumped into a performance problem as well. The solution was three fold:
1. Always set the Copy Local property to false and enforce this via a custom msbuild step
2. Set the output directory for each project to the same directory (preferab... | I'll suggest you to read Patric Smacchia's articles on that subject :
* [Partitioning Your Code Base Through .NET Assemblies and Visual Studio Projects](http://www.simple-talk.com/dotnet/.net-framework/partitioning-your-code-base-through-.net-assemblies-and-visual-studio-projects/) --> *Should every Visual Studio proj... | What is the best practice for "Copy Local" and with project references? | [
"",
"c#",
".net",
"visual-studio",
"msbuild",
""
] |
I have seen C# code that uses the `@` to tell the compiler the string has newlines in it and that it should be all in one line.
Is there something like that for C/C++?
Like if I want to put something like:
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
8586156078... | C and C++ have automatic concatenation of adjacent quoted strings. This means that
```
const char *a = "a" "b";
```
and
```
const char *b = "ab";
```
will make `a` and `b` point at identical data. You can of course extend this, but it becomes troublesome when the strings contain quotes. Your example seems not to, s... | C and C++ didn't have anything like C# verbatim string literals at the time this answer was first written. The closest you could do is:
```
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"1254069874715852... | Long strings with newlines | [
"",
"c++",
"string",
""
] |
I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT.
I have tried the following for the match part of the expression:
```
(?i)(?<word>[a-z0-9]+)(?<!and|not|or)
```
and
```
(?i)(?<word>[a-z0-9]+)(?!and|not|or)
```
but neither work. The replacement e... | This is a little dirty, but it works:
```
(?<!\b(?:and| or|not))\b(?!(?:and|or|not)\b)
```
In plain English, this matches any word boundary not preceded by and not followed by "and", "or", or "not". It matches whole words only, e.g. the position after the word "sand" would not be a match just because it is preceded b... | John,
The regex in your question is almost correct. The only problem is that you put the lookahead at the end of the regex instead of at the start. Also, you need to add word boundaries to force the regex to match whole words. Otherwise, it will match "nd" in "and", "r" in "or", etc, because "nd" and "r" are not in yo... | Regex to match all words except a given list | [
"",
"c#",
".net",
"regex",
""
] |
I've long had a desire for an STLish container that I could place into a shared memory segment or a memory mapped file.
I've considered the use of a custom allocator and placement new to place a regular STL container into a shared memory segment. (like this ddj [article](http://www.ddj.com/cpp/184401639;jsessionid=XH5... | The best starting point for this is probably the boost Interprocess libraries. They have a good example of a map in shared memory here:
[interprocess map](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/quick_guide.html#interprocess.quick_guide.qg_interprocess_map)
You will probably also want to read the se... | I only know of proprietary versions. [Bloomberg](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1850.pdf) and [EA](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html) have both published about their STL versions, but havent released ( to my knowledge ) the fruits of their labor. | Anyone have a good shared memory container for C++? | [
"",
"c++",
"stl",
"shared-memory",
""
] |
Which SQL statement is faster?
```
SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price
FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50
WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date
ORDER BY c1.ID DESC
OR
SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price,... | What is faster is not having 50 tables to start with. Joining 50 tables might be ok, but it's a highly counter-intuitive design and probably not the most maintainable solution.
Can you not store your data in rows (or columns) of a single (or fewer) tables rather than 50 tables??! | WHERE would usually be better but the best way is **case by case** and throw this into profiler, or simpler yet **display execution plan**. Folk often have very strong opinions on which approach is fastest/best in theory but there is no replacement for actually tuning according to the data you actually deal with as the... | Which SQL statement is faster? | [
"",
"sql",
"database",
"performance",
"logging",
""
] |
I am currently building a small website where the content of the main div is being filled through an Ajax call. I basically have a php script that returns the content like this:
(simplified php script...)
```
if(isset($_POST["id_tuto"])){
PrintHtml($_POST["id_tuto"]);
}
function PrintHtml($id)
{
switch($id)
{
... | You could do it like so:
```
<?php
function PrintHtml($id) {
switch($id) {
case [...]:
?>
<h1>Tut page 1</h1>
<p>this is html content.</p>
<?php
break;
[...]
}
}
?>
```
Or perhaps:
```
<?php
function PrintHtml($id) {
switch($id) {
case [...]:
inclu... | You just do it the way you'd normally generate an HTML page, except it is not wrapped in HTML HEAD or BODY tags. It's just the HTML fragment that will be added to your page.
Everything you "echo" becomes part of the output. You can do it is pieces or all on one go, it doesn't matter because it call gets sent to the br... | What's the best way to include html through an ajax echo command? | [
"",
"php",
"html",
"ajax",
""
] |
> **Possible Duplicate:**
> [What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?](https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null)
I need to wite a query that will retrieve the records from Table A , provided that t... | ```
SELECT *
FROM A
WHERE ID NOT IN
(SELECT ID FROM B)
``` | ```
select a.*
from
tableA a
left join tableB b
ON a.id = b.id
where
b.id is null
``` | Retrive Records Form One Table as long as they do not exist in Another table T-SQL | [
"",
"sql",
"sql-server",
""
] |
```
<form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<a onclick="test(event, '1'); " href="#" >Click Here</a>
<script>
function test(event, id){
document.getEle... | ```
<form id="frm_1" name="frm_1" target="_self" method="POST" action="local_page.php" >
<input type="hidden" name="vital_param" value="<?= $something ?>">
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<button type="submit" onclick="test(event, '1'); ... | As far as I know, it's not possible to submit two forms at once. Since you're using PHP however, why not take a look at the [cURL](https://www.php.net/manual/en/book.curl.php) library? It lets you send POST and GET requests and parse the results in PHP.
To answer the question in the title, if you simply want to open t... | How to open a new tab and change the current page | [
"",
"javascript",
""
] |
want to pass boost::bind to a method expecting a plain function pointer (same signature).
```
typedef void TriggerProc_type(Variable*,void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)> triggerProc ...
InitVariable(triggerProc);
error C2664: 'InitVariable' : cannot convert para... | Has anyone noticed that the [accepted answer](https://stackoverflow.com/a/282433/20003) only works with trivial cases? The only way that function<>::target() will return an object that can be bound to a C callback, is if it was constructed with an object that can be bound to a C callback. If that's the case, then you c... | I think you want to use the target() member function of boost::function (isn't that a mouthful...)
```
#include <boost/function.hpp>
#include <iostream>
int f(int x)
{
return x + x;
}
typedef int (*pointer_to_func)(int);
int
main()
{
boost::function<int(int x)> g(f);
if(*g.target<pointer_to_func>() == f) {
... | demote boost::function to a plain function pointer | [
"",
"c++",
"boost",
"functor",
""
] |
I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
```
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
```
I would like to know if ... | Here's your example in the "one" line.
```
this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
```
---
*Update*: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's som... | Simply supplying the HTML of elements you want to add to a jQuery constructor `$()` will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's `append()` method.
For example:
```
var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);
```
You could then... | jQuery document.createElement equivalent? | [
"",
"javascript",
"jquery",
"html",
"dom",
"dhtml",
""
] |
Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperatel... | Okay, I'd misunderstood the question before.
What you want is [System.Buffer.BlockCopy](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx) or [System.Array.Copy](http://msdn.microsoft.com/en-us/library/z50k9bft.aspx).
The LINQ ways will be hideously inefficient. If you're able to reuse the buffer y... | I'm not sure how efficient this is but...
```
int[] myInts = new int[100];
//Code to populate original arrray
for (int i = 0; i < myInts.Length; i += 10)
{
int[] newarray = myInts.Skip(i).Take(10).ToArray();
//Do stuff with new array
}
``` | Getting array subsets efficiently | [
"",
"c#",
"arrays",
"cuda",
"cuda.net",
""
] |
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format
```
Sun, 06 Nov 1994 08:49:37 GMT
```
Using `strftime` does not work, since the strings are locale-dependant. Do I have to build the string by hand? | You can use wsgiref.handlers.format\_date\_time from the stdlib which does not rely on locale settings
```
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
now = datetime.now()
stamp = mktime(now.timetuple())
print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:... | You can use the formatdate() function from the Python standard email module:
```
from email.utils import formatdate
print formatdate(timeval=None, localtime=False, usegmt=True)
```
Gives the current time in the desired format:
```
Wed, 22 Oct 2008 10:32:33 GMT
```
In fact, this function does it "by hand" without us... | RFC 1123 Date Representation in Python? | [
"",
"python",
"http",
"datetime",
""
] |
I am wondering what the best way is using php to obtain a list of all the rows in the database, and when clicking on a row show the information in more detail, such as a related image etc.
Should I use frames to do this? Are there good examples of this somewhere?
Edit:
I need much simpler instructions, as I am not a... | Contrary to other's recommendations, I would not recommend a framework or abstraction level. It will insulate you from understanding how php works and requires that you learn php and the framework structure/process at the same time. An abstraction layer is good practice in a commercial environment, but from the vibe of... | I use tables and JavaScript to do this.
Data in a SQL database is, by nature, tabular. So I just select the data and create a table. Then, to drill down (when I need do), I provide a JavaScript "more" functionality and use CSS to hide/display the additional data. | use php to show mysql data | [
"",
"php",
"mysql",
""
] |
I'm writing a MUD engine and I've just started on the game object model, which needs to be extensible.
I need help mainly because what I've done feels messy, but I can't think of a another solution that works better.
I have a class called `MudObject`, and another class called `Container`, A container can contain mult... | What you're asking for is reasonable, and is the [Composite Design Pattern](http://home.earthlink.net/~huston2/dp/composite.html) | I think you are overcomplicating. If MudObjects can contain other MudObjects, the single base class you need should be along these lines:
```
public abstract class MudObject
{
MudObject containedBy; //technically Parent
List<MudObject> Contains; //children
}
```
This is similar to the way WinForms and ASP... | Advice with Class Hierarchy for Game Items | [
"",
"c#",
"oop",
"hierarchy",
"mud",
""
] |
I have this as Main
```
int[] M ={ 10, 2, 30, 4, 50, 6, 7, 80 };
MyMath.Reverse(M);
for (int i = 0; i < M.Length; i++)
Console.WriteLine(M[i].ToString() + ", ");
```
---
After I created the class MyMath I made the Reverse method
```
public int Reverse(Array M)
{
int len = M.Length;
for (int i = ... | Working from your
```
public static int Reverse(Array M)
{
return Reverse(M);
}
```
You have 2 problems.
1. Reverse(M) looks like the same function that you're in, so you're calling your new function, which calls itself, which calls itself, etc., resulting in the stack overflow. Change to `return Array.Reverse(M... | To fix your problem, change your method to:
```
// the built-in returns void, so that needed to be changed...
public static void Reverse(Array M)
{
Array.Reverse(M); // you forgot to reference the Array class in yours
}
```
There, no Stack Overflow problems. | Reverse Method for an Array of int | [
"",
"c#",
"arrays",
""
] |
I've some experiences on build application with Asp.Net, but now MVC frameworks become more popular. I would like to try building new multilingual web application using with Asp.Net MVC or Castle MonoRail but I don't know which one is good for me. I don't like the web form view engine, but I like routing feature in Asp... | Speaking as an advocate of monorail, I've got to say you should probably go for ASP.NET MVC. To be honest, the simple fact that ASP.NET MVC is going to become the default architecture within three years should probably swing it. This equation was different a year ago, simply because the default architecture had serious... | MonoRail and ASP.NET MVC are fundamentally very similar, you should be well off using either one of them. MonoRail has existed much longer and has therefore more higher level features.
The main strength of ASP.NET MVC is it's routeing engine, to be fair MonoRail has pretty much an equivalent routing engine, and with s... | Asp.Net MVC vs Castle MonoRail | [
"",
"c#",
"asp.net-mvc",
"castle-monorail",
""
] |
i wonder if there is something similar to Sql Profiler for Sql Server Compact Edition?
i use SqlCE as backend for a desktop application and it would be really great to have something like sql profiler for this embedded database.
or at least something simliar to the NHibernate show\_sql feature...
any ideas?
thanks
j. | The only tested solution I know of that could solve this problem is [Altiris Profiler](https://stackoverflow.com/questions/206743/is-there-any-way-i-can-get-net-stack-traces-in-sql-profiler-or-a-similar-tool) which is a tool I designed at my previous job, but is closed source and not-for-sale.
The way you would hook i... | I don't think that would work - CE seems like a totally different beast.
You can enable some logging that might help you:
<http://msdn.microsoft.com/en-us/library/ms171949(SQL.90).aspx>
I tried to do this and managed to set the database up and connect from SSMS - you have to specify the alternate connection type of ... | Profiler for Sql CE | [
"",
"sql",
"sql-server-ce",
"profiler",
""
] |
I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.
I got something like:
```
[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}
```
and I make an ajax-call using prototype.js as:
```
var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'M... | WCF and ASMX webservices tend to be a bit choosey about the request body, when you specify args the request is usually encoded as a form post i.e. foo=4&bar=test instead you need to specify the javascript literal:-
```
new Ajax.Request(baseurl + 'MyMethod', {
method: 'POST',
postBody: '{"foo":4, "ba... | If you want to use POST, you need to specify the parameters to be wrapped in the request in WebInvoke attribute unless the parameters contains on object (e.g. message contract). This makes sense since there is no way to serialize the parameters without wrapped in either json or xml.
Unwrapped which is not XML indeed a... | Receive parameter from request body in WCF/ADO.NET Data Service | [
"",
".net",
"javascript",
"ajax",
"wcf",
"ado.net",
""
] |
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
```
Original: "This is really awesome."
"Dumb" truncate: "This is real..."
"Smart" truncate: "This is really..."
```
I'm looking for a way to accomplish the "smart" truncate from a... | I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller.
```
def smart_truncate(content, length=100, suffix='...'):
if len(content) <= length:
return content
else:
return ' '.join(content[:length+1].split(' ')[0:-1]) + suf... | Here's a slightly better version of the last line in Adam's solution:
```
return content[:length].rsplit(' ', 1)[0]+suffix
```
(This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.) | Truncate a string without ending in the middle of a word | [
"",
"python",
"truncate",
""
] |
I need to pass an array from JavaScript to a page method in C#. I have tried using a parameter in the C# method of IList and also a string[] array. Both ways throw an exception "cannot convert an object of type system.string to xxx", where xxx is the parameter type in the C# method. I am passing the object from jQuery ... | Hmm, two things:
1. JSON arrays have square brackets around them
2. JSON numbers aren't quoted.
Try this instead:
```
{"testNumbers": [5555555555,3333333333,4444444444]}
``` | You need to use one of the .NET JSON Deserializers:
<http://msdn.microsoft.com/en-us/library/bb299886.aspx> | Best way to pass an array from JavaScript to C#? | [
"",
"c#",
"asp.net",
"jquery",
"web-services",
""
] |
**Java** is the key here. I need to be able to delete files but users expect to be able to "undelete" from the recycle bin. As far as I can tell this isn't possible. Anyone know otherwise? | For various reasons Windows [has no concept of a folder that simply corresponds to the Recycle Bin](http://blogs.msdn.com/oldnewthing/archive/2008/09/18/8956382.aspx).
The correct way is to use JNI to invoke the Windows `SHFileOperation` API, setting the `FO_DELETE` flag in the `SHFILEOPSTRUCT` structure.
* [SHFileOp... | Ten years later, with Java 9, finally there is a builtin way to move files to the Trash Bin
[`java.awt.Desktop.moveToTrash(java.io.File)`](https://docs.oracle.com/javase/9/docs/api/java/awt/Desktop.html#moveToTrash-java.io.File-):
> ### `public boolean moveToTrash(File file)`
>
> Moves the specified file to the trash... | Is it possible with Java to delete to the Recycle Bin? | [
"",
"java",
"recycle-bin",
""
] |
I have to copy quite a lot of files from one folder to another. Currently I am doing it in this way:
```
string[] files = Directory.GetFiles(rootFolder, "*.xml");
foreach (string file in files)
{
string otherFile = Path.Combine(otherFolder, Path.GetFileName(file));
File.Copy(file, otherFile);
}
```
Is that th... | I can't think of a more efficient way than File.Copy, it goes directly to the OS.
On the other hand if it takes that long, I would strongly suggest to show a progress dialog - like [SHFileOperation](http://msdn.microsoft.com/en-us/library/bb762164(VS.85).aspx) does it for you. At least your users will know what is hap... | You could use the operating system to move the files. This is what tools like WinMerge do. You click the "copy" button in your app and it pops up the Windows progress box as if you had used Explorer to arrange the copy. [This thread](http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public... | Effective copying multiple files | [
"",
"c#",
".net",
"file",
"copy",
""
] |
I recently started using Linux as my primary OS. What are the tools that I will need to set up a complete programming environment in Linux for C and C++? | Standard stuff:
* The compiler tools, gcc, gdb, etc.
* Some sort of editor/IDE (emacs, vim, eclipse)
* Profiling tools
* Source Control (SubVersion, git, etc)
* Language specific tools, like easy\_install for python (you said C/C++, but the same goes for everything)
* A web server maybe? Apache, Lighttpd, nginx
* Any ... | Among others you should also have gprof and valgrind ( or something in it's class ). | Setting up a Programming Environment in Linux | [
"",
"c++",
"c",
"linux",
"ide",
"development-environment",
""
] |
I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft.
Is there a way to capture this event and shut down gracefully? | You can use WMI (Windows Management Instrumentation) to receive notification on USB events.
I did exactly that two years ago, monitoring for plugging and unplugging of a specific usb device.
Unfortunately, the code stays with my former employer, but I found one example at [bytes.com](http://bytes.com/topic/net/answer... | Yes, there is a way to capture the event. Unfortunately, there can be a long delay between the time the device is removed and the time the program receives any notification.
The approach is to trap com port events such as ErrorReceived and to catch the WM\_DEVICECHANGE message.
Not sure why your program is crashing; ... | How to capture a serial port that disappears because the usb cable gets unplugged | [
"",
"c#",
"winforms",
"serial-port",
""
] |
I'm developing an object-oriented PHP website right now and am trying to determine the best way to abstract database functionality from the rest of the system. Right now, I've got a DB class that manages all the connections and queries that the system uses (it's pretty much an interface to MDB2). However, when using th... | Having the SQL pulled out into separate functions is a decent start. Some other things you can do:
* Create separate classes for database access code. This will help make sure you don't have SQL functions scattered around in all of your PHP files.
* Load the SQL from external files. This completely separates your SQL ... | You might want to look into implementing the [ActiveRecord Pattern](http://en.wikipedia.org/wiki/Active_record_pattern). Using a design pattern such as this provides some consistency in how you work with data from your tables. There can be some downsides to these sorts of approaches, mainly performance for certain type... | Separating code from DB functionality | [
"",
"php",
"database",
""
] |
The code looks like below:
```
namespace Test
{
public interface IMyClass
{
List<IMyClass> GetList();
}
public class MyClass : IMyClass
{
public List<IMyClass> GetList()
{
return new List<IMyClass>();
}
}
}
```
When I Run Code Analysis i get the fol... | To answer the "why" part of the question as to why not [`List<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1), The reasons are future-proofing and API simplicity.
**Future-proofing**
[`List<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) is not... | I would personally declare it to return an interface rather than a concrete collection. If you really want list access, use [`IList<T>`](http://msdn.microsoft.com/en-us/library/5y536ey6.aspx). Otherwise, consider [`ICollection<T>`](http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) and [`IEnumerable<T>`](http://msd... | Collection<T> versus List<T> what should you use on your interfaces? | [
"",
"c#",
".net",
"collections",
"code-analysis",
""
] |
Can source code examples be kept in a SQL database **while retaining all formatting** (tabs, newlines, etc.)? If so what data type would be used? | Yes, use a `TEXT` type (or `MEDIUMTEXT` or `LONGTEXT` - you get the idea) | A BLOB type (varbinary) would definitely work, although databases shouldn't mangle text that's stored as varchar either. | Can source code examples be kept in a SQL database while retaining all formatting? If so | [
"",
"sql",
"language-agnostic",
"database-design",
"code-snippets",
""
] |
I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?
I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython? | "[Python and COM](http://www.boddie.org.uk/python/COM.html)" contains an example. OLE is related to COM and ActiveX so you should look for those terms.
"[Python Programming on Win32](http://oreilly.com/catalog/9781565926219/)" is a useful book. There is also a "[Python Win32](http://mail.python.org/pipermail/python-wi... | You need the [win32com](http://python.net/crew/mhammond/win32/Downloads.html) package. Some examples:
```
from win32com.client.dynamic import Dispatch
# Excel
excel = Dispatch('Excel.Application')
# Vim
vim = Dispatch('Vim.Application')
```
And then call whatever you like on them. | How to script an OLE component using Python | [
"",
"python",
"windows",
"scripting",
"activex",
"ole",
""
] |
Is there a way to write log4j logging events to a log file that is also being written to by other applications. The other applications could be non-java applications. What are the drawbacks? Locking issues? Formatting? | Log4j has a SocketAppender, which will send events to a service, which you can implement yourself or use the simple implementation bundled with Log4j.
It also supports syslogd and the Windows event log, which may be useful in trying to unify your log output with events from non-Java applications.
If performance is an... | Your best bet might be to let each application log separately, then put a scheduled job in place to 'zipper' the files together based on time. If you need really up-to-date access to the full log, you could have this run every hour. | Log4j Logging to a Shared Log File | [
"",
"java",
"log4j",
""
] |
OK, I have just been reading and trying for the last hour to import a CSV file from access into MySQL, but I can not get it to do it correctly, no matter what I try.
My table is like so:
```
+-----------------+-------------
| Field | Type
+-----------------+-------------
| ARTICLE_NO | varchar(20)
| AR... | The error can be caused by corrupt data in your DB, by the query to retrieve it from the DB, or in the way you output it. You need to narrow it down to one of those causes.
1. Have a direct look at the table you are selecting from. I suggest [phpMyAdmin](http://www.phpmyadmin.net/) for this.
2. Directly print the resu... | Your fields are terminated by ";" not "\"". Change
```
FIELDS TERMINATED BY '\"'
```
to
```
FIELDS TERMINATED BY ';'
```
You could add this as well:
```
OPTIONALLY ENCLOSED BY '"'
```
which I think is what you were trying to do with the TERMINATED BY clause. | How to import CSV in mysql? | [
"",
"php",
"mysql",
"html",
"csv",
""
] |
What is the best way to implement connection pooling in hsqldb, without compromising on the speed? | Hibernate gets connections from a `DataSource`, uses them and closes them. You need a connection pool or it will be very inefficient, consuming a lot of resources both on your app and on the DBMS, regardless of the database server you use.
You should try out *commons-dbcp* from Apache-Jakarta, it's very efficient and ... | You are comparing apples and oranges:
1. If you want orm compare the performance of different orm tools against the same db.
2. If you want connection pooling compare different connection pooling libraries against the same db.
Performing ORM incurs extra effort so it will never be as fast as direct JDBC access. That ... | Connection pooling in hsqldb | [
"",
"java",
"database",
"connection-pooling",
"hsqldb",
""
] |
My website has been giving me intermittent errors when trying to perform *any* Ajax activities. The message I get is
```
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Wri... | There is an excellent blog entry by Eilon Lipton. It contains of lot of tips on how to avoid this error:
**[Sys.WebForms.PageRequestManagerParserErrorException - what it is and how to avoid it](http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-... | Probably there is an error occuring on post back. In this case, you can view the details about the error by adding a PostBackTrigger to your updatepanel and referencing the button which causes the problem:
```
<asp:updatepanel ID="updatepanel1" runat="server">
<Triggers>
<asp:PostBackTrigger Co... | ASP.NET Ajax Error: Sys.WebForms.PageRequestManagerParserErrorException | [
"",
"javascript",
"asp.net",
".net",
"exception",
"ajax.net",
""
] |
I need to highlight, case insensitively, given keywords in a JavaScript string.
For example:
* `highlight("foobar Foo bar FOO", "foo")` should return `"<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>"`
I need the code to work for any keyword, and therefore using a hardcoded regular expression like `/foo/i` is not a sufficie... | You *can* use regular expressions if you prepare the search string. In PHP e.g. there is a function preg\_quote, which replaces all regex-chars in a string with their escaped versions.
Here is such a function for javascript ([source](https://locutus.io/php/pcre/preg_quote/)):
```
function preg_quote (str, delimiter) ... | ```
function highlightWords( line, word )
{
var regex = new RegExp( '(' + word + ')', 'gi' );
return line.replace( regex, "<b>$1</b>" );
}
``` | Case insensitive string replacement in JavaScript? | [
"",
"javascript",
"string",
"replace",
"case-insensitive",
""
] |
It's rare that I hear someone using [Inversion of Control (Ioc)](http://martinfowler.com/articles/injection.html) principle with .Net. I have some friends that work with Java that use a lot more Ioc with Spring and PicoContainer.
I understand the principle of removing dependencies from your code... but I have a doubt ... | Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC. You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applicati... | I use [StructureMap](http://www.google.com/search?q=structuremap&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) for dependency injection and have only recently started using it with [iBATIS.NET](http://ibatis.apache.org/dotnetdownloads.cgi) to inject our domain object mappers at runtime (and **... | Inversion of Control with .net | [
"",
"c#",
".net",
"dependency-injection",
"inversion-of-control",
""
] |
This is a C# console application. I have a function that does something like this:
```
static void foo()
{
Application powerpointApp;
Presentation presentation = null;
powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
}
```
That's all it does. When it is called there is... | It could be the certificate revocation list - the time-out on this is 15 seconds.
Is there anything in the event log? Can you check if any network connections are happening during the time-out?
[I blogged some details about certificate revocation delay](http://blogs.conchango.com/anthonysteele/archive/2007/02/07/Delay... | 15 seconds sounds like a timeout to me. Are you signing your assemblies? We had a problem where the framework wants to check the certificate revocation list when loading, but fails after 15 secs.
HTH
Tim | .Net - interop assemblies taking 15 seconds to load when being referenced in a function | [
"",
"c#",
".net",
"com-interop",
""
] |
Can anyone explain why following code won't compile? At least on g++ 4.2.4.
And more interesting, why it will compile when I cast MEMBER to int?
```
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined r... | You need to actually define the static member somewhere (after the class definition). Try this:
```
class Foo { /* ... */ };
const int Foo::MEMBER;
int main() { /* ... */ }
```
That should get rid of the undefined reference. | The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the `push_back` signature:
```
void push_back(const T&)
```
It's expecting a reference to an object of type `T`. Under the old system of initialization, such a member exists. For example, th... | Undefined reference to static class member | [
"",
"c++",
"g++",
"linker-errors",
"static-members",
""
] |
I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following:
```
StreamReader arrComputer = new StreamReader(FileDialog.filename)();
```
I got this exception:
```
The type or ... | You need to import the `System.IO` namespace. Put this at the top of your .cs file:
```
using System.IO;
```
Either that, or explicitly qualify the type name:
```
System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename);
``` | You'll need:
```
using System.IO;
```
At the top of the .cs file.
If you're reading text content I recommend you use a TextReader which is bizarrely a base class of StreamReader.
try:
```
using(TextReader reader = new StreamReader(/* your args */))
{
}
```
The using block just makes sure it's disposed of properly. | How to use StreamReader in C# (newbie) | [
"",
"c#",
".net",
"stream",
""
] |
I have an SQL database with multiple tables, and I am working on creating a searching feature. Other than having multiple queries for the different tables, is there a different way to go about said searching function?
---
I should probably add that a lot of my content is database driven to make upkeep easier. Lucene ... | Different approaches to consider:
1) Multiple queries pre-baked, like you described.
2) Dynamic sql that you put together on the fly based on user-entered criteria.
3) If text is involved, based on SQL Server full text search or Lucene.
In my open source app BugTracker.NET, I do both 2 and 3 (using Lucene.NET).
I ... | Since you have tagged the question with Asp.net I suppose you want to search your webpages. In that case you can use Indexing Server to perform freetext searches easily that search the generated html and any keywords you have set up.
As Corey Trager suggested, using Lucene.NET is also an option. It has a good reputati... | Best way to create a search function ASP.NET and SQL server | [
"",
"asp.net",
"sql",
"search",
""
] |
I made a class that derives from Component:
```
public class MyComponent: System.ComponentModel.Component
{
}
```
I saw that Visual Studio put this code in for me:
```
protected override void Dispose(bool disposing)
{
try
{
if (disposing && (components != null))
{
components.Dis... | Change:
```
if (disposing && (components != null))
{
components.Dispose();
}
```
to be:
```
if (disposing && (components != null))
{
_dataset.Dispose();
components.Dispose();
}
``` | Check any disposable member objects and dispose them if they are not null. | Implementing Dispose() with class derived from System.ComponentModel.Component | [
"",
"c#",
"dispose",
""
] |
I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus.
I did read through [this question](https://stackoverflow.com/questions/177799/what-is-a-good-pdf-report-generator-tool-for-python), but I rea... | For one of my projects, I have tested and/or implemented probably six or seven different methods of going from an image to a PDF in the last six months. Ultimately I ended up coming back to [ReportLab](http://www.reportlab.org/downloads.html) (which I had initially avoided for reasons similar to those you described) be... | I think going through Latex is the easiest way, and not overkill at all. Generating a working PDF file is quite a difficult activity, whereas generating a Tex source is much easier. Any other typesetting change would probably work as well, such as going through reStructuredText or troff. | Can anyone recommend a decent FOSS PDF generator for Python? | [
"",
"python",
"pdf-generation",
""
] |
I see many different Java terms floating around. I need to install the JDK 1.6. It was my understanding that Java 6 == Java 1.6. However, when I install Java SE 6, I get a JVM that reports as version 11.0! Who can solve the madness? | When you type "java -version", you see three version numbers - the java version (on mine, that's "`1.6.0_07`"), the Java SE Runtime Environment version ("build `1.6.0_07-b06`"), and the HotSpot version (on mine, that's "`build 10.0-b23, mixed mode"`). I suspect the "11.0" you are seeing is the HotSpot version.
Update:... | * JDK - Java Development Kit
* JRE - Java Runtime Environment
* Java SE - Java Standard Edition
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools... | Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean? | [
"",
"java",
""
] |
I have an archiving process that basically deletes archived records after a set number of days. Is it better to write a scheduled SQL job or a windows service to accomplish the deletion? The database is mssql2005.
## Update:
To speak to some of the answers below, this question is regarding an in house application and... | It depends on what you want to accomplish.
Do you want to store the deleted archives somewhere? Log the changes? An SQL Job should perform better since it is run directly in the database, but it is easier to give a service acces to resources outside the database. So it depends on what you want to do,,, | I would think a scheduled SQL job would be a safer solution since if the database is migrated to a new machine, someone doing the migration might forget that there is a windows service involved and forget to start/install it on the new server. | Windows Service or SQL Job? | [
"",
"sql",
"windows",
"sql-server-2005",
"windows-services",
""
] |
I am developing an application for PocketPC. When the application starts the custom function SetScreenOrientation(270) is called which rotates the screen. When the application closes the function SetScreenOrientation(0) is called which restores the screen orientation.
This way the screen orientation isn't restored if ... | The correct message is [WM\_SIZE](http://msdn.microsoft.com/en-us/library/aa453907.aspx), but Daemin's answer points to the wrong WM\_SIZE help topic. Check the wParam. Be careful as your window may be maximized but hidden. | Going from my Windows CE experience you should handle either the [WM\_SIZE](http://msdn.microsoft.com/en-us/library/ms915712.aspx) or [WM\_WINDOWPOSCHANGED](http://msdn.microsoft.com/en-us/library/ms942858.aspx) messages. If you're working on PocketPC I would suggest you take a look at the WM\_WINDOWPOSCHANGED message ... | Event Handler for Minimize and Maximize Window | [
"",
"c++",
"windows-mobile",
"pocketpc",
""
] |
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:
* an integer
* an 'average' number
and returns a float.
In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constan... | It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:
```
def poisson_probability(actual, mean):
# naive: math.exp(-mean) * mean**actual / factorial(actual)
# iterative, to keep the components from getting too large or small:... | `scipy` has what you want
```
>>> scipy.stats.distributions
<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>
>>> scipy.stats.distributions.poisson.pmf(6, 2.6)
array(0.031867055625524499)
```
It's worth noting that it's pretty easy to calculate by han... | Calculate poisson probability percentage | [
"",
"python",
"statistics",
"poisson",
""
] |
Is there really that much of a difference between the performance of `Vector` and `ArrayList`? Is it good practice to use ArrayLists at all times when thread safety isn't an issue? | Vector originates back from the pre-Collections API days, and have been retrofitted since to be a part of it. From what I've read, the reason it is not deprecated is because the core API depends on it.
ArrayList was written from scratch as a part of the Collections API and as such should be used unless you need to sup... | If thread safety is not an issue, `ArrayList` will be faster as it does not have to synchronize. Although, you should always declare your variable as a `List` so that the implementation can be changed later as needed.
I prefer to handle my synchronization explicitly because a lot of operations require multiple calls. ... | ArrayList vs. Vectors in Java if thread safety isn't a concern | [
"",
"java",
"performance",
"collections",
""
] |
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.
Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — ... | **Data Storage**:
* Specify the `utf8mb4` character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use `utf8mb4` encoding if a `utf8mb4_*` collation is specified (without any explicit character set).
... | I'd like to add one thing to [chazomaticus' excellent answer](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through#279279):
Don't forget the META tag either (like this, or [the HTML4 or XHTML version of it](http://www.w3.org/International/questions/qa-html-encoding-declarations#quicklookup)):
```
<met... | UTF-8 all the way through | [
"",
"php",
"mysql",
"apache",
"utf-8",
""
] |
Is there a standard Java library that handles common file operations such as moving/copying files/folders? | Here's how to do this with `java.nio` operations:
```
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(... | Not yet, but the [New NIO (JSR 203)](http://jcp.org/en/jsr/detail?id=203) will have support for these common operations.
In the meantime, there are a few things to keep in mind.
[File.renameTo](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#renameTo(java.io.File)) generally works only on the same file syst... | Move / Copy File Operations in Java | [
"",
"java",
"file",
"copy",
"move",
""
] |
Does anyone know of a Java library that provides a useful abstraction for analyzing and manipulating arbitrary relational database schemata? I'm thinking of something that could do things like
```
LibraryClass dbLib = ...;
DbSchema schema = dbLib.getSchema("my_schema");
List<DbTable> tables = schema.getTables();
```
... | [DdlUtils](http://db.apache.org/ddlutils/) has what you're looking for. You can read/write schemas to/from XML (in Torque format) or a live database, or even define the database schema in pure Java. Better yet, read the on-line doco, it's quite good. | JDBC itself has such an abstraction. Look at java.sql.DatabaseMetaData. However, this is an optional part of the standard and it depends on the JDBC driver you are using wether it is implemented or not. | Is there a database modelling library for Java? | [
"",
"java",
"database",
"rdbms",
"modeling",
""
] |
Which are the most advanced frameworks and tools there are available for python for practicing Behavior Driven Development? Especially finding similar tools as rspec and mocha for ruby would be great. | [Ian Bicking](http://blog.ianbicking.org/behavior-driven-programming.html) recommends using [doctest](http://docs.python.org/library/doctest.html?highlight=doctest#module-doctest) for behavior driven design:
I personally tend to use [nose](https://web.archive.org/web/20110610084952/http://somethingaboutorange.com/mrl/... | Lettuce means to be a cucumber-like tool for python: <http://lettuce.it/>
You can grab the source at github.com/gabrielfalcao/lettuce | Practicing BDD with python | [
"",
"python",
"testing",
"bdd",
""
] |
I would like to use JavaScript to manipulate hidden input fields in a JSF/Facelets page. When the page loads, I need to set a hidden field to the color depth of the client.
From my Facelet:
```
<body onload="setColorDepth(document.getElementById(?????);">
<h:form>
<h:inputHidden value="#{login.colorDepth}" id="col... | You'll want to set the ID of the form so you'll know what it is. Then you'll be able to construct the actual element ID.
```
<body onload="setColorDepth(document.getElementById('myForm:colorDepth');">
<h:form id="myForm">
<h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>
```
If you don't want... | You can use the control's *clientId* as returned by [UIComponent.getClientId(FacesContext)](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/component/UIComponent.html#getClientId(javax.faces.context.FacesContext)). See [here](https://stackoverflow.com/questions/265175/how-does-jsf-generate-the-na... | Using JavaScript with JSF and Facelets | [
"",
"javascript",
"jsf",
"facelets",
""
] |
I have a string that is HTML encoded:
```
'''<img class="size-medium wp-image-113"\
style="margin-left: 15px;" title="su1"\
src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"\
alt="" width="300" height="194" />'''
```
I want ... | Given the Django use case, there are two answers to this. Here is its `django.utils.html.escape` function, for reference:
```
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '&l
t;').replace('>', ... | With the standard library:
* HTML Escape
```
try:
from html import escape # python 3.x
except ImportError:
from cgi import escape # python 2.x
print(escape("<"))
```
* HTML Unescape
```
try:
from html import unescape # python 3.4+
except ImportError:
try:
from ht... | How do I perform HTML decoding/encoding using Python/Django? | [
"",
"python",
"django",
"html-encode",
""
] |
I am developing a map control in WPF with C#. I am using a canvas control e.g. 400 x 200 which is assigned a map area of e.g. 2,000m x 1,000m.
The scale of the map would be: **canvas\_size\_in\_meters / real\_size\_in\_meters**.
I want to find the canvas\_size\_in\_meters.
The canvas.ActualWidth gives the Width in D... | > How do I measure the size of a WPF control in inches EXACTLY and regardless of screen resolution and DPI setting ?
This isn't actually possible, because for it to work, WPF would have to know the resolution (in terms of DPI) of your monitor. Sounds nice in theory, but in practice windows doesn't know this informatio... | There is way to compute current pixel size in mm or inches. As mentioned in the earlier posts, it is not a fixed value and would vary depending on the current resolution and monitor size.
First get the current resolution. Assume it is 1280x1024
Now get the monitor width in mm using GetDeviceCaps function. Its a standa... | C# WPF resolution independancy? | [
"",
"c#",
"wpf",
"gis",
"resolution",
"dpi",
""
] |
A site I am working on that is built using PHP is sometimes showing a completely blank page.
There are no error messages on the client or on the server.
The same page may display sometimes but not others.
All pages are working fine in IE7, Firefox 3, Safari and Opera.
All pages are XHTML with this meta element:
```
<m... | This is a content-type problem from IE.
It does not know how to handle application/xhtml+xml.
Although you write xhtml+xml, IE only knows text+html.
It will be the future before all agents know xhtml+xml
change your meta tag with content type to content="text/html; | Sounds like [bug #153 "Self Closing Script Tag"](http://webbugtrack.blogspot.com/2007/08/bug-153-self-closing-script-tag-issues.html) bug in IE, **which is well known to cause blank pages**.
Due to IE's bug, you can **NEVER** code the following and expect it to work in IE.
```
<script src="...." />
```
(if the tag i... | Blank page in IE6 | [
"",
"php",
"internet-explorer",
"http",
"internet-explorer-6",
"http-headers",
""
] |
When I serialize;
```
public class SpeedDial
{
public string Value { get; set; }
public string TextTR { get; set; }
public string TextEN { get; set; }
public string IconId { get; set; }
}
```
It results:
```
<SpeedDial>
<Value>110</Value>
<TextTR>Yangın</TextTR>
<TextEN>Fire</TextEN>
... | Three approaches leap to mind:
1: create a property to use for the serialization, and hide the others with `[XmlIgnore]`
2: implement `IXmlSerializable` and do it yourself
3: create a separate DTO just for the serialization
Here's an example that re-factors the "text" portion into objects that `XmlSerializer` will li... | I won't do it if I were you, because you make your serializer dependent of your business objects. For lowercase you could use the xml-customattributes. | How to combine multiple properties into one tag via overriding object serialization | [
"",
"c#",
"xml-serialization",
""
] |
Is it possible to retrieve variable set in `onreadystatechange` function from outside the function?
--edit--
Regarding execution of functions:
If its possible i would like to execute ajaxFunction() with one click
and then popup() with next click, or
somehow wait for ajax function to end and then call for alert... | The following code assumes that the ajax-request is synchronous:
```
function popup(){
ajaxFunction();
alert(MyVariable);
}
```
But since synchronous requests are blocking the browser you should in almost all cases use asynchronous calls (If I remember correctly onreadystatechange should not be called on sync... | some's comments are correct... this has nothing to do with variable scoping, and everything to do with the fact that the inner function (the 'onreadystatechange' function) setting the value of MyVariable will not have been executed by the time that the alert() happens... so the alert will *always* be empty.
The inner ... | In AJAX how to retrive variable from inside of onreadystatechange = function () | [
"",
"javascript",
"ajax",
""
] |
I've been using the [Java Pet Store](http://java.sun.com/developer/releases/petstore/) and [.Net Pet Store](http://blogs.vertigosoftware.com/petshop/default.aspx) examples [for years](http://www.onjava.com/pub/a/onjava/2001/11/28/catfight.html) when comparing Java EE and .Net performance in an eBusiness type setting.
I... | There is never really a definitive measure for comparing the performance of platforms. For example, a comparison of the *same* J2EE platform could be impacted by minor configuration changes. It would seem that the platform is less of a factor in performance today than it once was, whilst design and architecture will ha... | The pet store project in your link is .Net 2.0 which was released three years ago, in November 2005. Since then, there have been two additional releases (3.0 and 3.5), with many enhancements which could improve performance.
I guess it depends on whether you want to compare "mature" web app's, or those written with the... | Is there a better way to compare general performance of .Net and Java in an eCommerce setting than the "pet store"? | [
"",
"java",
".net",
"performance",
"jakarta-ee",
""
] |
I am looking at embedding Lua in a C++ application I am developing. My intention is to use Lua to script what ordered operation(s) to perform for some given input, ie.
receive a new work item in c++ program, pass details to Lua backend, Lua calls back into c++ to carry out necessary work, returns finished results.
The... | If I recall correctly, light userdata is actually just a pointer. They all share the same metatable. They are mostly used to pass around addresses of C data.
Full userdata is probably closer of what you need if you must access it from the Lua side. Their metatable would allow you to access it like it was a regular Lu... | I have not done this myself (it was years since I used Lua, and I've never used in an embedded fashion), but I think you should look into [metatables](http://www.lua.org/manual/5.1/manual.html#2.8) and the userdata type. The manual says this about userdata values:
> This type corresponds to a block of raw memory and h... | How to pass large struct back and forth between between C++ and Lua | [
"",
"c++",
"lua",
""
] |
I have seen many apps that take instrument classes and take `-javaagent` as a param when loading also put a `-noverify` to the command line.
The Java doc says that `-noverify` turns off class verification.
However why would anyone want to turn off verification even if they are instrumenting classes? | Start-up time, I'd say. Verification that classes are correct takes some time when the class is loaded. Since classes might be loaded in a lazy fashion (not on app start, but when being used for the first time), this might cause unexpected and undesired runtime delays.
Actually the class does not need to be checked in... | When it is used in conjunction with `-javaagent`, it is most likely **not** for performance reasons, but because the agent intentionally creates "invalid" bytecode.
It should be noted that invalid bytecode might still execute fine, because some of the verification rules are quite strict. For instance, `this` must not ... | Use of -noverify when launching java apps | [
"",
"java",
"command-line-arguments",
""
] |
I have a query that works on Postgresql 7.4 but not on Postgresql 8.3 with same database.
Query:
```
SELECT * FROM login_session WHERE (now()-modified) > timeout;
```
Gets the following error:
```
ERROR: operator does not exist: interval > integer
LINE 1: ...ELECT * FROM login_session WHERE (now()-modified) > time... | ```
create or replace function int2interval (x integer) returns interval as $$ select $1*'1 sec'::interval $$ language sql;
create cast (integer as interval) with function int2interval (integer) as implicit;
```
ought to do it. | There are a lot of changes between 7.4 and 8.3. Some of the most drastic were the removal of some automatic casts.
I suppose the "timeout" is in seconds? If so you could change the query to:
```
SELECT
*
FROM
login_session
WHERE
(CURRENT_TIMESTAMP - modified) > (timeout * '1 sec'::interval);
``` | Operator does not exist: interval > integer | [
"",
"sql",
"postgresql",
""
] |
Given the following simple example:
```
List<string> list = new List<string>() { "One", "Two", "Three", "three", "Four", "Five" };
CaseInsensitiveComparer ignoreCaseComparer = new CaseInsensitiveComparer();
var distinctList = list.Distinct(ignoreCaseComparer as IEqualityComparer<string>).ToList();
```
I... | `StringComparer` does what you need:
```
List<string> list = new List<string>() {
"One", "Two", "Three", "three", "Four", "Five" };
var distinctList = list.Distinct(
StringComparer.CurrentCultureIgnoreCase).ToList();
```
(or invariant / ordinal / etc depending on the data you are comparing) | [See Marc Gravells answer if you want the most concise approach]
After some investigation and good feedback from Bradley Grainger I've implemented the following IEqualityComparer. It suports a case insensitive Distinct() statement (just pass an instance of this to the Distinct operator) :
> ```
> class IgnoreCaseComp... | LINQ Distinct operator, ignore case? | [
"",
"c#",
"linq",
"string",
"comparison",
"distinct",
""
] |
I'm betting that someone has already solved this and maybe I'm using the wrong search terms for google to tell me the answer, but here is my situation.
I have a script that I want to run, but I want it to run only when scheduled and only one at a time. (can't run the script simultaneously)
Now the sticky part is that... | add a column `exec_status` to `myhappytable` (maybe also `time_started` and `time_finished`, see pseudocode)
run the following cron script every x minutes
pseudocode of cron script:
```
[create/check pid lock (optional, but see "A potential pitfall" below)]
get number of rows from myhappytable where (exec_status == ... | You can use the at(1) command inside your script to schedule its next run. Before it exits, it can check myhappyschedule for the next run time. You don't need cron at all, really. | cron script to act as a queue OR a queue for cron? | [
"",
"sql",
"queue",
"cron",
""
] |
I am looking to parse INSERT and UPDATE MySQL SQL queries in PHP to determine what changes where made from what original data. Now this would be pretty easy to create, but I want to see if there are any existing libraries in PHP to do this.
Basically what I have is a table with all of the above queries that have been ... | <http://pear.php.net/package/SQL_Parser>
<http://sourceforge.net/projects/txtsql>
<http://code.google.com/p/php-sql-parser>
For Perl there's more variety | A little bit off the question, but maybe a suggestion worth thinking about:
Since MySQL 5.0, the support for triggers is quite good. If you want to keep a record of what changes have been made to a database, instead of storing the sql statements, you could also define insert/update triggers and define another table in... | PHP MySQL SQL parser (INSERT and UPDATE) | [
"",
"php",
"mysql",
"changelog",
""
] |
I'm using Eclipse for Java development. All my sources compile fine and the resulting application compiles fine. However, I keep getting an "red-x" error notification in the Package Explorer.
All my sources in this source directory (too long for the snapshot) compile fine, none of the show the "red-x" error icon.
Any... | yeah, this happens sometimes for no apparent reason. You can go to the "Problems"-Tab (right next to console output) and see the error message, so maybe you can narrow it down that way. | This happens often when I use Maven, and I had always ignored it until I found this question. You need to update the project in this case (figured this out by looking in the Problems pane)
From the project context menu: Maven -> Update Project and select the available maven codebases
Alternatively you can use (Alt + ... | In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors? | [
"",
"java",
"eclipse",
""
] |
I know I can loop over the string or build a regex or invert the set (ASCII isn't that big after all) and search for the first instance of that, but Yuck.
What I'm looking for is a nice one liner.
fewer features is better, LINQ is out (for me, don't ask, it's a *long* story)
---
The solution I'm going with (unless ... | This works:
```
public static char FindFirstNotAny(this string value, params char[] charset)
{
return value.TrimStart(charset)[0];
}
``` | If you don't have access to LINQ, I think you may just have to write a static method with a loop (which is probably more efficient than LINQ anyway. Remember the compiler will inline small methods when possible.
The simplest non-LINQ I can come up with is below. I recommend adding braces so scope and the blocks are cl... | How to find the index of the first char in a string that is not in a list | [
"",
"c#",
"string",
"search",
""
] |
I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?
This works: (of course it does)
```
std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);
```
This doesn't work: (what should I do instead?)
```
std::list<... | `l.insert(reverse.base(), 10);` will insert '10' at the end, given your definition of the 'reverse' iterator. Actually, `l.rbegin().base() == l.end()`. | Essentially, you don't. See 19.2.5 in TCPPPL.
The `reverse_iterator` has a member called `base()` which will return a "regular" iterator. So the following code would work in your example:
```
l.insert(reverse.base(), 10);
```
Be careful though because the `base()` method returns the element one after the orginal `re... | How do you insert with a reverse_iterator | [
"",
"c++",
"stl",
""
] |
I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.
One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this faci... | I don't think there's anything out of the box. You can use boost::make\_transform.
```
template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair)
{
return a_pair.second;
}
void run_map_value()
{
map<int,string> a_map;
a_map[0] = "zero";
a_map[1] = "one";
a_map[2] = "two";
copy( b... | Replacing the previous answer, in case anybody else finds this like I did. As of boost 1.43, there are some commonly used range adaptors provided. In this case, you want boost::adaptors::map\_values. The relevant example:
<http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_v... | iterator adapter to iterate just the values in a map? | [
"",
"c++",
"maps",
"iterator",
"adapter",
""
] |
How do I launch an app and capture the output via stdout and maybe stderr?
I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using mak... | In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then:
```
program arg1 arg2 >/tmp/log.file 2>&1
```
This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation (~~hieroglyph~~) '`2>&1`' at the end sends stderr (file descriptor 2) to the sam... | You need to fill up the STARTUP\_INFO structure, which has hStdInput, hStdOutput and hStdError. Remember to inherit handles when you CreateProcess.
```
/* Assume you open a file handle or pipe called myoutput */
STARTUP_INFO si_startinfo;
ZeroMemory(&si_startinfo, sizeof(STARTUP_INFO));
si_startinfo.cb = sizeof(STARTU... | launch app, capture stdout and stderr in c++ | [
"",
"c++",
"process",
"stdout",
"capture",
"launch",
""
] |
I've just come across a property setter that catches exceptions (all Exceptions; I know that's bad, but it's not relevant here), and *only* logs them. First of all, I think it should through them again as well; why wait for a crash and a log study when you can know something is wrong right away?
However, my main quest... | Exceptions should be thrown whenever the method or class member is unable to complete whatever task it is designed to accomplish.
So for a property setter, if the setter is unable to set the property, then it should throw an exception.
As to whether you should catch it and rethrow it, the answer is yes, but only if y... | It depends on the specific task at hand. If you are writing a library class that will be used as a component in other programs and the contract of the method of the class says that it should only accept valid dates then throwing the Exception is fine.
If you are accepting user input and then waiting for an exception i... | Exception vs Validation | [
"",
"c#",
".net",
""
] |
Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower?
I am trying to submit this to [SPOJ](http://www.spoj.pl/) and it tells me that my time limit exceeded...
```
#include <iostream>
#include <sstream>
usin... | This is one step (skipping even numbers) above the naive algorithm. I would suggest the [Sieve Of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) as a more efficient algorithm. From the above link:
> The complexity of the algorithm is
> O((nlogn)(loglogn)) with a memory
> requirement of O(n). The seg... | You're searching a *lot* more numbers than you have to - at most you only need to go to `<= (sqrt(num))`. | Is this prime generator inefficient C++? | [
"",
"c++",
"performance",
"primes",
""
] |
I'm writing a wrapper class for a command line executable. This exe accepts input from `stdin` until I hit `Ctrl+C` in the command prompt shell, in which case it prints output to `stdout` based on the input. I want to simulate that `Ctrl+C` press in C# code, sending the kill command to a .NET `Process` object. I've tri... | I've actually just figured out the answer. Thank you both for your answers, but it turns out that all i had to do was this:
```
p.StandardInput.Close()
```
which causes the program I've spawned to finish reading from stdin and output what i need. | Despite the fact that using `GenerateConsoleCtrlEvent()` for sending `Ctrl`+`C` signal is the right answer, it needs significant clarification to get it to work in different .NET application types.
If your .NET application doesn't use its own console (Windows Forms/WPF/Windows Service/ASP.NET), the basic flow is:
1. ... | How do I send ctrl+c to a process in c#? | [
"",
"c#",
"command-line",
".net-2.0",
"process",
""
] |
Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller.
I bind some `onclick` events to a button, but I find that they sometimes execute in an order I did not expect.
Is there ... | I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.
If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:
\*\* *UPDATED inline with jQuery changes (thanks... | If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
```
$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff... | How to order events bound with jQuery | [
"",
"javascript",
"jquery",
"events",
""
] |
How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to be in UTC. | Use `timegm()` instead of `mktime()`
Worth noting as pointed out by @chux - Reinstate Monica below is that `time_t timegm(struct tm *timeptr)` is considered adding to the C23 standard (and thus by inclusion into the C++ standard). | for those on windows, the below function is available:
```
_mkgmtime
```
link for more info: <https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/mkgmtime-mkgmtime32-mkgmtime64> | Easy way to convert a struct tm (expressed in UTC) to time_t type | [
"",
"c++",
"c",
""
] |
I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database.
I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user.
What is the best way of doing it? My preferred solution is a constraint that is put on the ... | It's pretty easy with a correlated sub-query:
```
SELECT `img`.`id` , `img`.`userid`
FROM `img`
WHERE 3 > (
SELECT count( * )
FROM `img` AS `img1`
WHERE `img`.`userid` = `img1`.`userid`
AND `img`.`id` > `img1`.`id` )
ORDER BY `img`.`id` DESC
LIMIT 10
```
The query assumes that larger `id` means added later
Correlate... | This is difficult because MySQL does not support the LIMIT clause on sub-queries. If it did, this would be rather trivial... But alas, here is my naïve approach:
```
SELECT
i.UserId,
i.ImageId
FROM
UserSuppliedImages i
WHERE
/* second valid ImageId */
ImageId = (
SELECT MAX(ImageId)
FROM UserSupplied... | How to select maximum 3 items per users in MySQL? | [
"",
"mysql",
"sql",
"database",
""
] |
I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project. Is there a way to put my web forms into a separate class library? If so, how is it done?
Thanks in advance. | At first thought, I don't think this is possible, due to the way ASPX is non-precompiled..
However, you can create classes that inherit from `Page` and place them into a DLL to re-use code-behind functionality. This can of course include control instantiate logic if required, but there is no designer to work with (if ... | My question is, why do you want to do this?
If it's purely organisational then your "simple folders" should really be enough, so maybe you need to re-think your project structure.
If it is for compilation purposes, like it takes ages to recompile the site every time you change something, maybe you could split the sit... | Is there a way to put aspx files into a class library in Visual Studio 2008 .NET 3.5? | [
"",
"c#",
".net",
"asp.net",
".net-3.5",
""
] |
I have a program in which I've lost the C++ source code. Are there any good C++ decompilers out there?
I've already ran across [Boomerang](http://boomerang.sourceforge.net/). | You can use [IDA Pro](http://www.hex-rays.com/idapro/) by [Hex-Rays](http://www.hex-rays.com/). You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a **lot** of manual labor reversing the code.
If you didn't strip the binaries there is some hope as IDA Pro c... | information is discarded in the compiling process. Even if a decompiler could produce the logical equivalent code with classes and everything (it probably can't), the self-documenting part is gone in optimized release code. No variable names, no routine names, no class names - just addresses. | Is there a C++ decompiler? | [
"",
"c++",
"reverse-engineering",
"decompiling",
""
] |
I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application. | * There's [pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) that compiles python like source to python extension modules
* [rpython](https://rpython.readthedocs.io/en/latest/) which allows you to compile python with some restrictions to various backends like C, LLVM, .Net etc.
* There's also [shed-skin... | You can use something like py2exe to compile your python script into an exe, or Freeze for a linux binary.
see: [How can I create a directly-executable cross-platform GUI app using Python?](https://stackoverflow.com/questions/2933/an-executable-python-app#2937) | Is it possible to compile Python natively (beyond pyc byte code)? | [
"",
"python",
"module",
"compilation",
""
] |
This is a problem that only occurs on application update (only tested through Admin Console, not CLI). Also, this is only happening on our development environment, which is identical to our prod env. On uninstall/install, everything is compiled properly. However, this is a large application and it takes long enough to ... | # Solution:
**Problem was**: WAS had debugging enabled. This generated .smap files (source mappings) instead of .class files. Once we discovered this, we disabled the debugging service under the Admin Console (Application Servers > server1 > Debugging Processes > uncheck 'Start service'). I don't know why this created... | One suggestion:
Have you checked that your environment has a JAVA\_HOME pointing to a JDK and not just a JRE. The JRE doesn't have javac, so there won't be any way to compile .java files created at runtime by the JSP compiler into .classes?
EDIT: Also, perhaps this [link](http://publib.boulder.ibm.com/infocenter/wasi... | WebSphere App Server Not Compiling JSP/Tag Libs | [
"",
"java",
"jsp",
"websphere",
"jsp-tags",
""
] |
I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.
What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception? | Well if some other Thread calls thread.interupt(), while the thread is sleeping, you'll get the Exception. And yes, you can probably just put try..catch arround the sleep() and ignore it ;) | It happens when something calls [interrupt()](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#interrupt()) on the thread. [This article by Brian Goetz](http://www.ibm.com/developerworks/java/library/j-jtp05236.html) explains the interruption mechanism and how you should handle InterruptedExceptions:
> "The... | What kind of behaviour causes an interrupted exception? | [
"",
"java",
"multithreading",
"exception",
""
] |
Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc?
Eventhough I am an emacs guy, I find it much easier to create GUI with VS. | For GUI only, I find VisualWx (<http://visualwx.altervista.org/>) to be very good for designing wxPython apps under Windows.
For GUI + database, dabo (<http://dabodev.com/>) is probably a good answer. | The short answer is "no". There is not a swiss-army-knife like IDE that is both a full-featured Python code-editor and a full-featured WYSIWYG GUI editor. However, there are several stand-alone tools that make creating a GUI easier and there are a myriad of code editors, so if you can handle having two windows open, th... | With what kind of IDE (if any) you build python GUI projects? | [
"",
"python",
"user-interface",
"ide",
""
] |
I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says *Google* in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.
I want to use this to provid... | ```
<style type='text/css'>
input #ghost { color: #CCC; }
input #normal { color: #OOO; }
</style>
<script type='text/javascript'>
function addTextHint(elem, hintText)
{
if (elem.value == '')
{
elem.value = hintText;
elem.style.className = 'g... | This technique is so commonly used that it's now explicitly supported in the HTML spec through the placeholder attribute of the input tag:
[HTML placeholder Attribute](http://www.w3schools.com/tags/att_input_placeholder.asp)
[It's already supported in most browsers](http://caniuse.com/input-placeholder) and for old... | Show 'ghosted' example text in a field, and then clear it onblur | [
"",
"javascript",
"jquery",
"html",
"forms",
"field",
""
] |
I'm mostly a .Net person at the moment, but I've been playing with Java some lately-- exploring what's out there.
Now I'm looking for the Java equivalent for WPF. I know I could find an OpenGL library or two out there, but that's not really as rich or simple as the WPF system. | I think a combination of JavaFX, Swing, Java2D, and Java's browser-based JRE comprise the solutions that WPF provides:
* JavaFX applications (actually, any Java app) can run in the browser or on a desktop
* JavaFX provides high-end video support
* JavaFX provides for scripted animations and visual special effects
* Sw... | I've programmed Aqua, Macintosh Quick Draw, Windows GDI and GDI+, Qt, and .NET Winforms and WPF is by far the most sophisticated API I've used. Although it has a pretty capable feature set that's better than preceding technologies such as swing, it's no match for WPF. It solves some major problems that have plagued gra... | What is Java's answer to WPF? | [
"",
"java",
".net",
"wpf",
""
] |
How can I access options that I set in a jQuery Datepicker?
```
$("#testDatePicker").datepicker({
minDate: new Date(2005, 0, 26),
showOn: 'button',
buttonImage: 'js/themes/default/images/calendar.gif',
buttonImageOnly: true
});
var minDate = $("#testDatePicker").?????;
``` | What about storing the options in a named var instead of an anonymous object?
```
var dpOptions = {minDate: new Date(2005, 0, 26), ...};
$('#testDatePicker').datepicker(dpOptions);
.
.
.
var minDate = dpOptions.minDate;
``` | If you don't have enough with @mausch solution the settings are stored here:
```
$.data($('#testDatePicker')[0], 'datepicker').settings
``` | Accessing options in jQuery Datapicker | [
"",
"javascript",
"jquery",
""
] |
What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.
```
// -- myFile.txt --
Mary had a little $pet.
// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it ... | If it's from a trusted source you can use (dramatic pause) [eval()](http://www.php.net/eval) (gasps of horror from the audience).
```
$text = 'this is a $test'; // single quotes to simulate getting it from a file
$test = 'banana';
$text = eval('return "' . addslashes($text) . '";');
echo $text; // this is a banana
``` | Regex would be easy enough. And it would not care about things that `eval()` would consider a syntax error.
Here's the pattern to find PHP style variable names.
```
\$\w+
```
I would probably take this general pattern and use a PHP array to look up each match I've found (using (`preg_replace_callback()`). That way t... | Best way to substitute variables in plain text using PHP | [
"",
"php",
"variables",
"substitution",
""
] |
Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:
```
<element1>
<element2>
someData
</element2>
</element1>
```
instead of:
```
<element1><element2>someData</element2></element1>
```
If this is not possible in woodstox, is there any other li... | Via the JDK: `transformer.setOutputProperty(OutputKeys.INDENT, "yes");`. | There is com.sun.xml.txw2.output.IndentingXMLStreamWriter
```
XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
``` | StAX XML formatting in Java | [
"",
"java",
"xml",
"formatting",
"stax",
"woodstox",
""
] |
When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.
```
try {
URL url = new URL("http://foo.bar");
URLConnection... | It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can... | If you cast to an HttpURLConnection, there is a [disconnect()](http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#disconnect()) method. If the connection is idle, it will probably disconnect immediately. No guarantees. | In Java when does a URL connection close? | [
"",
"java",
"exception",
"url",
"connection",
""
] |
How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?
I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the a... | This one is tested:
```
<style type="text/css">
.AddedClass
{
background-color: #88FF99;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var re = /^(https?:\/\/[^\/]+).*$/;
var currentHref = window.location.href.replace(re, '$1');
var reLocal = new RegExp('^' + currentHref.replace(/\./... | I think something like this could be a starting point:
```
var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
if (links[i].href.substring(0, 5) == 'https')
{
links[i].setAttribute('title', 'abc');
links[i].setAttribute('class... | Editing all external links with javascript | [
"",
"javascript",
"html",
"href",
""
] |
I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return n... | You shouldn't need to wrap the APDU further. The API layer should take care of that.
It looks like the 0x6D00 response just means that the application did not support the INS.
Just troubleshooting now, but you did start out by selecting the MasterCard application, right?
I.e. something like this:
```
void selectApp... | here is some working example:
```
CardChannel channel = card.getBasicChannel();
byte[] selectMaestro={(byte)0x00, (byte)0xA4,(byte)0x04,(byte)0x00 ,(byte)0x07 ,(byte)0xA0 ,(byte)0x00 ,(byte)0x00 ,(byte)0x00 ,(byte)0x04 ,(byte)0x30 ,(byte)0x60 ,(byte)0x00};
byte[] getProcessingOptions={(byte)0x80,(byte)0xA8,(byte)... | How do I read the PAN from an EMV SmartCard from Java | [
"",
"java",
"smartcard",
"apdu",
"emv",
""
] |
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)? | Yes, it is possible:
```
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
```
To chain to a particular superclass constructor instead of one in the same class, use `super` instead of `this`. Note that **you can only chain to one cons... | Using `this(args)`. The preferred pattern is to work from the smallest constructor to the largest.
```
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, ... | How do I call one constructor from another in Java? | [
"",
"java",
"constructor",
""
] |
I'm working for the first time with Forms Authentication, I'm using an example from the web to learn, I included in my web.config
```
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH" loginUrl="Login.aspx" protection="All" path="/"/>
</authentication>
<authorization>
<deny users... | Drop the spaces in
```
"accountants, seekers, copiers, typers"
``` | Try it without the spaces after the commas:
"accountants,seekers,copiers,typers"
The Split will be creating strings like "accountants", " seekers", " copiers", " typers", | IsInRole problem | [
"",
"c#",
"asp.net",
""
] |
I have used an update command to update the whole table in an Sql Server 2000 database by mistake. I was actually meaning to update just one row. Now all the 2000 rows contain the update. Is there a way to roll back this change? | Unless you started your update with an explicit transaction, no.
However, you might be able to use [Log Rescue](http://www.red-gate.com/products/SQL_Log_Rescue/index.htm) . I'm not sure though if this can help you in this case.
A better option might be to restore a backup to a new database and merge the old and new t... | No, not unless you have a backup to revert to.
I've done that mistake once. Now I start every manual operation with BEGIN TRAN.
The worst that can happen then is that you forget to COMMIT TRAN and keep a lock on the table. | Rolling back and update command in Sql Server 2000 | [
"",
"sql",
"sql-server",
"sql-server-2000",
"rollback",
""
] |
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that? | Start pdb like this:
`M-x` `pdb`
Then, start the Django development server:
```
python manage.py runserver --noreload
```
Once you have the (Pdb) prompt, you need to do this:
```
import sys
sys.path.append('/path/to/directory/containing/views.py')
```
Once you've done this, you should be able to set breakpoints n... | This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function:
`import pdb; pdb.set_trace()`
Now when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the full... | Django debugging with Emacs | [
"",
"python",
"django",
"debugging",
"emacs",
""
] |
I'm trying to parse a html page and extract 2 values from a table row.
The html for the table row is as follows: -
```
<tr>
<td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1">Max Temperature (ºC)</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align... | Try
```
<tr>\s*
<td[^>]*>.*?</td>\s*
<td[^>]*>\s*(?<value>\d+)\s*</td>\s*
<td[^>]*>\s*(?<time>\d{2}:\d{2}:\d{2})\s*</td>\s*
</tr>\s*
``` | Parsing HTML reliably using regexp is known to be notoriously difficult.
I think I would be looking for a HTML parsing library, or a "screen scraping" library ;)
If the HTML comes from an unreliable source, you have to be extra careful to handle malicious HTML syntax well. Bad HTML handling is a major source of secur... | regex for html parsing (in c#) | [
"",
"c#",
"html",
"regex",
"parsing",
""
] |
According to MSDN
> The return value specifies the result
> of the message processing; it depends
> on the message sent.
I know it is defined as
```
typedef LONG_PTR LRESULT;
```
Meaning it will be 8 bytes on 64bit machine but it doesn't!
Does anyone know if it is safe to assume that only the lower 4 bytes are use... | No it's not safe, because the return value is defined by the message being sent and the handler.
If you control the handler and the message then it'd be possible, it's not safe in the general case.
James | No it is not safe in general. Do not assume the downcast. Also, useful is to compile your code with /RTCc which ensures inadvertent casts are asserted at runtime. | SendMessage API in 64 bit | [
"",
"c++",
"c",
"winapi",
""
] |
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..
```
const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
return ss.str().c_str();
}
```
could the c string be destroyed when ss... | The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.
Next, y... | Over the years C boiled this down to 2 standard methods:
* Caller passes in buffer.
There are three versions of this.
Version 1: Pass a buffer and a length.
Version 2: Documentation specifies an expected min buffer size.
Version 3: Pre-Flight. Function returns the min buffer required. caller calls twic... | Return dynamically allocated memory from C++ to C | [
"",
"c++",
"c",
"memory-management",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.