Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I'm looking for (arguably) the correct way to return data from a `XmlHttpRequest`. Options I see are:
* **Plain HTML**. Let the request format the data and return it in a usable format.
*Advantage*: easy to consume by the calling page.
*Disadvantage*: Very rigid, stuck with a fixed layout.
* **XML**. Let the request return XML, format it using XSLT on the calling page.
*Advantage*: the requested service is easily consumed by other sources.
*Disadvantage*: Is browser support for XSLT good enough?
* **JSON**. Let the request return JSON, consume it using javascript, render HTML accordingly.
*Advantage*: easier to 'OO-ify' the javascript making the request.
*Disadvantage*: Probably not as easy to use as the previous two options.
I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons.
While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
|
If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works.
If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app.
Like [@John Topley](https://stackoverflow.com/users/1450/john-topley) said: it depends.
|
I'd agree with John Topley - it depends on the application. There's a good article on quirksmode that discusses the advantages and disadvantages of each format that you might want to read: <http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html>
|
XmlHttpRequest return values
|
[
"",
"javascript",
"ajax",
""
] |
I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
|
I would suggest something like:-
```
bool nonEmptyDataSet = dataSet != null &&
(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
```
**Edits:** I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any().
In line with Keith's suggestion, here is an extension method version of this approach:-
```
public static class ExtensionMethods {
public static bool IsEmpty(this DataSet dataSet) {
return dataSet == null ||
!(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}
}
```
Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
|
What's wrong with
(aDataSet.Tables.Count == 0)
?
|
In C#, what is the best way to test if a dataset is empty?
|
[
"",
"c#",
".net",
""
] |
I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.
|
Using the netsh interface
Usage set interface [name = ] IfName
[ [admin = ] ENABLED|DISABLED
[connect = ] CONNECTED|DISCONNECTED
[newname = ] NewName ]
Try including everything inside the outer brackets:
netsh interface set interface name="thename" admin=disabled connect=DISCONNECTED newname="thename"
See also this MS KB page: <http://support.microsoft.com/kb/262265/>
You could follow either of their suggestions.
For disabling the adapter, you will need to determine a way to reference the hardware device. If there will not be multiple adapters with the same name on the computer, you could possibly go off of the Description for the interface (or PCI ID works well). After that, using devcon (disable|enable). Devcon is an add-on console interface for the Device Manager.
|
So far I've found the following Python solution:
```
>>> import wmi; c=wmi.WMI()
>>> o=c.query("select * from Win32_NetworkAdapter where NetConnectionID='wifi'")[0]
>>> o.EnableDevice(1)
(-2147217407,)
```
which is translated, AFAIU, to the generic WMI error 0x80041001. Could be permissions.
|
How to programmatically enable/disable network interfaces? (Windows XP)
|
[
"",
"python",
"networking",
"windows-xp",
""
] |
I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.
|
I found a possible answer here: <http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63>
From the article:
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
```
**Edit:**
But my trusty compiler says, `XslTransform` is obsolete: Use `XslCompiledTransform` instead:
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
```
|
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate [XslCompiledTransform.Transform overload](http://msdn.microsoft.com/en-us/library/ms163431.aspx):
```
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
```
*(Sorry for posing this as an answer, but the `code block` support in comments is rather limited.)*
In VB.NET, you don't even need a variable:
```
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
```
|
How to apply an XSLT Stylesheet in C#
|
[
"",
"c#",
"xml",
"xslt",
""
] |
How do you tell if a function in JavaScript is defined?
I want to do something like this
```
function something_cool(text, callback) {
alert(text);
if( callback != null ) callback();
}
```
But it gets me a
> callback is not a function
error when callback is not defined.
|
```
typeof callback === "function"
```
|
All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):
```
function isFunction(possibleFunction) {
return typeof(possibleFunction) === typeof(Function);
}
```
Personally, I try to reduce the number of strings hanging around in my code...
---
Also, while I am aware that `typeof` is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.
|
How to tell if a JavaScript function is defined
|
[
"",
"javascript",
"reflection",
""
] |
Does anyone have, or know of, a binary patch generation algorithm implementation in C#?
Basically, compare two files (designated *old* and *new*), and produce a patch file that can be used to upgrade the *old* file to have the same contents as the *new* file.
The implementation would have to be relatively fast, and work with huge files. It should exhibit O(n) or O(logn) runtimes.
My own algorithms tend to either be lousy (fast but produce huge patches) or slow (produce small patches but have O(n^2) runtime).
Any advice, or pointers for implementation would be nice.
Specifically, the implementation will be used to keep servers in sync for various large datafiles that we have one master server for. When the master server datafiles change, we need to update several off-site servers as well.
The most naive algorithm I have made, which only works for files that can be kept in memory, is as follows:
1. Grab the first four bytes from the *old* file, call this the *key*
2. Add those bytes to a dictionary, where *key -> position*, where *position* is the position where I grabbed those 4 bytes, 0 to begin with
3. Skip the first of these four bytes, grab another 4 (3 overlap, 1 one), and add to the dictionary the same way
4. Repeat steps 1-3 for all 4-byte blocks in the *old* file
5. From the start of the *new* file, grab 4 bytes, and attempt to look it up in the dictionary
6. If found, find the longest match if there are several, by comparing bytes from the two files
7. Encode a reference to that location in the *old* file, and skip the matched block in the *new* file
8. If not found, encode 1 byte from the *new* file, and skip it
9. Repeat steps 5-8 for the rest of the *new* file
This is somewhat like compression, without windowing, so it will use a lot of memory. It is, however, fairly fast, and produces quite small patches, as long as I try to make the codes output minimal.
A more memory-efficient algorithm uses windowing, but produces much bigger patch files.
There are more nuances to the above algorithm that I skipped in this post, but I can post more details if necessary. I do, however, feel that I need a different algorithm altogether, so improving on the above algorithm is probably not going to get me far enough.
---
**Edit #1**: Here is a more detailed description of the above algorithm.
First, combine the two files, so that you have one big file. Remember the cut-point between the two files.
Secondly, do that *grab 4 bytes and add their position to the dictionary* step for everything in the whole file.
Thirdly, from where the *new* file starts, do the loop with attempting to locate an existing combination of 4 bytes, and find the longest match. Make sure we only consider positions from the old file, or from *earlier in the new file than we're currently at*. This ensures that we can reuse material in both the old and the new file during patch application.
---
**Edit #2**: [Source code to the above algorithm](http://code.google.com/p/lvknet/source/browse/trunk/LVK/IO/Patching/Binary/BinaryPatch.cs)
You might get a warning about the certificate having some problems. I don't know how to resolve that so for the time being just accept the certificate.
The source uses lots of other types from the rest of my library so that file isn't all it takes, but that's the algorithm implementation.
---
@lomaxx, I have tried to find a good documentation for the algorithm used in subversion, called xdelta, but unless you already know how the algorithm works, the documents I've found fail to tell me what I need to know.
Or perhaps I'm just dense... :)
I took a quick peek on the algorithm from that site you gave, and it is unfortunately not usable. A comment from the binary diff file says:
> Finding an optimal set of differences requires quadratic time relative to the input size, so it becomes unusable very quickly.
My needs aren't optimal though, so I'm looking for a more practical solution.
Thanks for the answer though, added a bookmark to his utilities if I ever need them.
**Edit #1**: Note, I will look at his code to see if I can find some ideas, and I'll also send him an email later with questions, but I've read that book he references and though the solution is good for finding optimal solutions, it is impractical in use due to the time requirements.
**Edit #2**: I'll definitely hunt down the python xdelta implementation.
|
Sorry I couldn't be more help. I would definately keep looking at xdelta because I have used it a number of times to produce quality diffs on 600MB+ ISO files we have generated for distributing our products and it performs very well.
|
[bsdiff](http://www.daemonology.net/bsdiff/) was designed to create very small patches for binary files. As stated on its page, it requires `max(17*n,9*n+m)+O(1)` bytes of memory and runs in `O((n+m) log n)` time (where `n` is the size of the old file and `m` is the size of the new file).
The original implementation is in C, but a C# port is described [here](http://code.logos.com/blog/2010/12/binary_patching_with_bsdiff.html) and available [here](https://github.com/LogosBible/bsdiff.net).
|
Binary patch-generation in C#
|
[
"",
"c#",
"file",
"patch",
""
] |
I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "[GetBestInterface](http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx)" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.
I've found some examples via Google, like [this one](http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/) or [this one](http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651), but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...
There is also a way of doing this using IP Helper, using the [ParseNetworkString](http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx), but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.
So, anyone knows of a standard way to do this in .NET?
|
MSDN [says](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) method.
You can convert IP address to numeric value using following code:
```
var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [3] << 24;
ip += (uint)ipBytes [2] << 16;
ip += (uint)ipBytes [1] <<8;
ip += (uint)ipBytes [0];
```
**EDIT:**
As other commenters noticed above-mentioned code is for IPv4 addresses only.
IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.
|
Shouldn't it be:
```
var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [0] << 24;
ip += (uint)ipBytes [1] << 16;
ip += (uint)ipBytes [2] <<8;
ip += (uint)ipBytes [3];
```
?
|
How do you parse an IP address string to a uint value in C#?
|
[
"",
"c#",
".net",
"winapi",
"networking",
"iphelper",
""
] |
Is it possible to use gcov for coverage testing of multi-threaded applications?
I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.
|
We've certainly used gcov to get coverage information on our multi-threaded application.
You want to compile with gcc 4.3 which can do coverage on dynamic code.
You compile with the `-fprofile-arcs -ftest-coverage` options, and the code will generate .gcda files which gcov can then process.
We do a separate build of our product, and collect coverage on that, running unit tests and regression tests.
Finally we use lcov to generate HTML results pages.
|
Gcov works fine for multi-threaded apps. The instrumentation architecture is properly serialized so you will get coverage data of good fidelity.
I would suggest using gcov in conjunction with [lcov](http://ltp.sourceforge.net/coverage/lcov.php). This will give you great reports scoped from full project down to individual source files.
lcov also gives you a nicely color coded HTML version of your source so you can quickly evaluate your coverage lapses.
|
GCOV for multi-threaded apps
|
[
"",
"c++",
"testing",
"code-coverage",
""
] |
In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html)?
The use-case I have is I want to create a ZIP file in memory, and [ZipFile](https://docs.python.org/library/zipfile.html) requires a file-like object.
|
You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data:
```
from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
```
StringIO will throw TypeError:
```
from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")
```
|
As long as you don't try to put any unicode data into your `StringIO` and you are careful NOT to use `cStringIO` you should be fine.
According to the [StringIO](https://docs.python.org/library/stringio.html) documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, `StringIO` does something special when someone does a `f.write(u"asdf")` (which ZipFile does not do, to my knowledge). Anyway;
```
import zipfile
import StringIO
s = StringIO.StringIO()
z = zipfile.ZipFile(s, "w")
z.write("test.txt")
z.close()
f = file("x.zip", "w")
f.write(s.getvalue())
s.close()
f.close()
```
works just as expected, and there's no difference between the file in the resulting archive and the original file.
If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)
|
Binary buffer in Python
|
[
"",
"python",
"binary",
"io",
"buffer",
""
] |
Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?
|
I prefer the [GD library](http://www.php.net/gd) - check out [the Examples](http://www.php.net/manual/en/image.examples.php), and this example:
```
<?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(120, 20)
or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
```
Outputs:
[](https://i.stack.imgur.com/kBN75.png)
(source: [php.net](http://uk2.php.net/manual/en/figures/image.imagecreatetruecolor.png))
See [imagecreatetruecolor](http://www.php.net/manual/en/function.imagecreatetruecolor.php).
|
Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably [ImageMagick](http://www.imagemagick.org/script/index.php) which is actually not PHP specific but comes with appropriate bindings.
See also in the [PHP documentation](http://php.net/imagick).
|
How to create images in PHP
|
[
"",
"php",
"image",
""
] |
I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up.
I would just *love* to just dump this kind of functions, they seem totally superfluous. **Is it still necessary these days to write 'ä' instead of 'ä'?** At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding.
**Update:** To be more precise: Are named entities necessary for *anything else than displaying HTML tags* (as in "<" for "<")
### Update 2:
@Konrad: Are you saying that, no, named entities are not needed?
@Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)
|
Named entities in "real" XHTML (i.e. with `application/xhtml+xml`, rather than the more frequently-used `text/html` compatibility mode) are discouraged. Aside from the five defined in XML itself (`<`, `>`, `&`, `"`, `'`), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character.
As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities.
|
If using XHTML, it's actually recommended not to use named entities ([citation needed]). Some browsers (Firefox …), when parsing this as XML (which they normally don't), don't read the DTD files and thus are unable to handle the entities.
As it's best practice anyway to use UTF-8 as encoding if there are no compelling reasons to do otherwise, this only means that the creator of the documents needs a decent editor that can not only handle the documents but also provides a good way of entering the divers glyphs. OS X doesn't really have this problem because most needed glyphs can be reached via “alt” keys but Windows doesn't have this feature.
---
> @Konrad: Are you saying that, no, named entities are not needed?
Precisely. Unless, of course, there are silly restrictions, e.g. legacy database drivers that choke on UTF-8 etc.
|
Are named entities in HTML still necessary in the age of Unicode aware browsers?
|
[
"",
"php",
"html",
"unicode",
"internationalization",
""
] |
I have a solution with many projects. One project contain few custom components. One of these components is used to display a title on an image. We can change the color of the background and many other things.
The problem is IF I decide to change the default color of the background of the component or change the position of the text, thoses change won't reflect in all other projects of the solution where the component is used. I have compilent the project of the component and all other projects Reference the component by the Project.
For the moment, what I have to do is to take off the component from the other project one by one and to add it back, then all is fine. Do you have a quick way to do it?
**UPDATE**
I have added a CheckBox inside that component and it seems that the checkbox is everywhere! Fine! But when a property has a some tag that let the component to change (example like the Background color) it doesn't change the "default" value but instead put the old value as a changed value in the property. So, I see the old value setted like if I add manually changed the color in the Properties panel when I haven't...
**UPDATE 2**
[alt text http://img517.imageshack.us/img517/9112/oldonenewoneei0.png](http://img517.imageshack.us/img517/9112/oldonenewoneei0.png)
**Update 3:**
This problem is still here. Just to let people know that I am still curious to find a way.
I have tried few of your suggestions.
1. If I clean all the solution and build only the project that has the Custom control then I build the solution. Nothing change (To test it, I have change the color of the component to Yellow. Nothing change : **fail**.
2. If I remove the reference and add it back to the project and then rebuild the solution. I can see the old color in the designer : **fail**.
I have updated the question with more information and an image (above) for those who want to try to help me.
As you can see, the old "compile" of the component show the Yellow background but when I insert a new component (from the Left Tool bar in Visual Studio) I can have the new component with the supposed WHITE background...
|
This is most likely due to **[references](http://msdn.microsoft.com/en-us/library/z6609kte.aspx)**.
Your other projects probably **[copy in a reference](http://msdn.microsoft.com/en-us/library/ms169644.aspx)** to your component project. You'll have to rebuild these other projects for them to re-copy in the referenced component project, if it has changed. It is only updated at build time.
You can somewhat get around this by having them part of the same solution. In that case, you can set up your **[project dependencies](http://msdn.microsoft.com/en-us/library/cb8t5a6t.aspx)** correctly and it should handle things for you mostly automatically. But having everything in the same solution isn't always the right thing to do.
If you already have them part of the same solution or it's not a references problem, it might be due to **[component serialization](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibility.aspx)**. We've run into this quirk a lot when doing custom control development.
|
My guess is that the designer is smart and remembers the settings for the component as you have it in the designer and thus sees it as the default.
|
C# component do not refresh when source code updated
|
[
"",
"c#",
".net",
"custom-component",
""
] |
I have two arrays of animals (for example).
```
$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
```
How can I merge the two arrays into one by the ID?
|
This does what Erik suggested (id no. as array key) and merges vlaues in `$array2` to `$results`.
```
$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
```
|
@Andy
> <http://se.php.net/array_merge>
That was my first thought but it doesn't quite work - however [array\_merge\_recursive](http://www.php.net/manual/en/function.array-merge-recursive.php) might work - too lazy to check right now.
|
How can I merge PHP arrays?
|
[
"",
"php",
"arrays",
""
] |
I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).
The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.
What is the best practice to switch between the views?
From start to running?
Between the running views?
Ideas:
* Use one form and hide and show controls
* Use one start form and then a form with a TabControl
* Use six separate forms
|
Creating a bunch of overlaid panels is a design-time nightmare.
I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:
```
tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;
tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
```
|
What I do is to have a Panel where your different views will sit on the main form.
then create user controls for your different views.
Then when I want to switch between a'view' you dock it to Panel on the main form.. code looks a little like this.
i preffer this because you can then reuse your views, like if you want to open up a view in a tab you can dock your user controls inside tab pages.. or even inherit from
tabpage instead of usercontrol to make things a bit more generic
```
public partial class MainForm : Form
{
public enum FormViews
{
A, B
}
private MyViewA viewA; //user control with view a on it
private MyViewB viewB; //user control with view b on it
private FormViews _formView;
public FormViews FormView
{
get
{
return _formView;
}
set
{
_formView = value;
OnFormViewChanged(_formView);
}
}
protected virtual void OnFormViewChanged(FormViews view)
{
//contentPanel is just a System.Windows.Forms.Panel docked to fill the form
switch (view)
{
case FormViews.A:
if (viewA != null) viewA = new MyViewA();
//extension method, you could use a static function.
this.contentPanel.DockControl(viewA);
break;
case FormViews.B:
if (viewB != null) viewB = new MyViewB();
this.contentPanel.DockControl(viewB);
break;
}
}
public MainForm()
{
InitializeComponent();
FormView = FormViews.A; //simply change views like this
}
}
public static class PanelExtensions
{
public static void DockControl(this Panel thisControl, Control controlToDock)
{
thisControl.Controls.Clear();
thisControl.Controls.Add(controlToDock);
controlToDock.Dock = DockStyle.Fill;
}
}
```
|
Building C# .NET windows application with multiple views
|
[
"",
"c#",
".net",
"windows",
""
] |
I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.
Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?
|
Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this:
```
<img usemap="#logo" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png">
<map name="logo">
<area shape="rect" href="" coords="52,42,121,65" title="Stack">
<area shape="rect" href="" coords="122,42,245,65" title="Overflow">
</map>
```
The Stack Overflow logo refers to the [image map](http://www.w3.org/TR/html4/struct/objects.html#edef-MAP), which defines a rectangle for each of the two words using an `area` tag. Each `area` tag's `title` element specifies the text that browsers generally show as a tooltip. The `shape` attribute can also specify a circle or polygon.
|
The [`title`](http://www.w3.org/TR/html4/struct/global.html#h-7.4.3) attribute is the simplest solution and guaranteed to work, *and* degrade gracefully for useragents that don't support it correctly.
|
Tooltips on an image
|
[
"",
"javascript",
"html",
""
] |
There are similar question, but not regarding C# libraries I can use in my source code.
Thank you all for your help.
I've already saw lucene, but I need something more easy to search for similar strings and without the overhead of the indexing part.
The answer I marked has got two very easy algorithms, and one uses LINQ too, so it's perfect.
|
Levenshtein distance implementation:
* [Using LINQ](http://www.dotnetperls.com/levenshtein) (not really, see comments)
* [Not using LINQ](http://web.archive.org/web/20110720094521/http://www.merriampark.com/ldcsharp.htm)
I have a .NET 1.1 project in which I use the latter. It's simplistic, but works perfectly for what I need. From what I remember it needed a bit of tweaking, but nothing that wasn't obvious.
|
you can also look at the very impressive library titled Sam's String Metrics <https://github.com/StefH/SimMetrics.Net> . this includes a host of algorithms.
* Hamming distance
* Levenshtein distance
* Needleman-Wunch distance or Sellers Algorithm
* Smith-Waterman distance
* Gotoh Distance or Smith-Waterman-Gotoh distance
* Block distance or L1 distance or City block distance
* Monge Elkan distance
* Jaro distance metric
* Jaro Winkler
* SoundEx distance metric
* Matching Coefficient
* Dice’s Coefficient
* Jaccard Similarity or Jaccard Coefficient or Tanimoto coefficient
* Overlap Coefficient
* Euclidean distance or L2 distance
* Cosine similarity
* Variational distance
* Hellinger distance or Bhattacharyya distance
* Information Radius (Jensen-Shannon divergence)
* Harmonic Mean
* Skew divergence
* Confusion Probability
* Tau
* Fellegi and Sunters (SFS) metric
* TFIDF or TF/IDF
* FastA
* BlastP
* Maximal matches
* q-gram
* Ukkonen Algorithms
|
Are there any Fuzzy Search or String Similarity Functions libraries written for C#?
|
[
"",
"c#",
".net",
"string",
"comparison",
""
] |
I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.
|
I would recomend [PHP Simple HTML DOM Parser](https://sourceforge.net/projects/simplehtmldom/) after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements.
|
If the page you're scraping is valid X(HT)ML, then any of [PHP's built-in XML parsers](http://www.php.net/manual/en/refs.xml.php) will do.
I haven't had much success with PHP libraries for scraping. If you're adventurous though, you can try [simplehtmldom](https://sourceforge.net/projects/simplehtmldom/). I'd recommend [Hpricot](http://code.whytheluckystiff.net/hpricot/) for Ruby or [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) for Python, which are both *excellent* parsers for HTML.
|
HTML Scraping in Php
|
[
"",
"php",
"html",
"screen-scraping",
""
] |
It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.
Do any C++ compilers do this optimization? Why? Why not?
How do I go about telling the compiler to do it?
* For MSVC: `/O2` or `/Ox`
* For GCC: `-O2` or `-O3`
How about checking if the compiler has done this in a certain case?
* For MSVC, enable PDB output to be able to trace the code, then inspect the code
* For GCC..?
I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)
It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that `-O2` is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)
---
After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.
If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.
|
**All current mainstream compilers perform tail call optimisation** fairly well (and have done for more than a decade), [even for mutually recursive calls](https://godbolt.org/g/TjqTHV) such as:
```
int bar(int, int);
int foo(int n, int acc) {
return (n == 0) ? acc : bar(n - 1, acc + 2);
}
int bar(int n, int acc) {
return (n == 0) ? acc : foo(n - 1, acc + 1);
}
```
Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:
* For MSVC, use `/O2` or `/Ox`.
* For GCC, Clang and ICC, use `-O3`
An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output.
As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a [diploma thesis](http://www.complang.tuwien.ac.at/schani/diplarb.ps) by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading.
|
As well as the obvious (compilers don't do this sort of optimization unless you ask for it), there is a complexity about tail-call optimization in C++: destructors.
Given something like:
```
int fn(int j, int i)
{
if (i <= 0) return j;
Funky cls(j,i);
return fn(j, i-1);
}
```
The compiler can't (in general) tail-call optimize this because it needs
to call the destructor of `cls` *after* the recursive call returns.
Sometimes the compiler can see that the destructor has no externally visible side effects (so it can be done early), but often it can't.
A particularly common form of this is where `Funky` is actually a `std::vector` or similar.
|
Which, if any, C++ compilers do tail-recursion optimization?
|
[
"",
"c++",
"optimization",
"tail-recursion",
""
] |
I see 2 main ways to set events in JavaScript:
1. Add an event directly inside the tag like this:
`<a href="" onclick="doFoo()">do foo</a>`
2. Set them by JavaScript like this:
`<a id="bar" href="">do bar</a>`
and add an event in a `<script>` section inside the `<head>` section or in an external JavaScript file, like that if you're using **prototypeJS**:
```
Event.observe(window, 'load', function() {
$('bar').observe('click', doBar);
}
```
I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).
The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.
Which method is the best?
A killer answer will be fully appreciated!
|
In my experience, there are two major points to this:
1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.
2) The second kind, i.e. `Event.observe()` has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.
|
> I think the first method is easier to read and maintain
I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.
Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:
```
$$('#itemlist table th > a').invoke('observe', 'click', performSort);
```
This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.
|
What is the best way to add an event in JavaScript?
|
[
"",
"javascript",
"html",
"events",
"event-binding",
""
] |
I would like to extract the date a jpg file was created. Java has the lastModified method for the File object, but appears to provide no support for extracting the created date from the file. I believe the information is stored within the file as the date I see when I hover the mouse pointer over the file in Win XP is different than what I can get by using JNI with "dir /TC" on the file in DOS.
|
The information is stored within the image in a format called [EXIF](http://en.wikipedia.org/wiki/Exchangeable_image_file_format) or [link text](http://www.exif.org). There several libraries out there capable of reading this format, like [this one](http://www.drewnoakes.com/code/exif/)
|
The date is stored in the [EXIF](http://en.wikipedia.org/wiki/Exif) data in the jpeg. There's a [java library](http://www.drewnoakes.com/code/exif/) and a [viewer in java](http://sourceforge.net/projects/jexifviewer/) that might be helpful.
|
How to get date picture created in java
|
[
"",
"java",
"date",
""
] |
My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually.
We require a solution that will enable us to:
```
- Compile the application
- Version the application with the SVN version number
- Backup the existing site
- Deploy to a web farm
```
All our apps are source controlled using SVN and our .Net apps use CruiseControl.
We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible.
Are there any other deployment tools out there that would help us?
|
Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy.
This article has some great information:
[Integrating MSBuild with CruiseControl.NET](http://dougrohm.com/blog/post/2006/01/29/Integrating-MSBuild-with-CruiseControlNET.aspx)
Here's roughly how our solution works:
* Developers build the 'debug' version of the app and run unit tests, then check in to SVN.
* CruiseControl sees the updates and calls our build script...
+ Runs any new migrations on the build database
+ Replaces the config files with the build server config
+ Builds the 'debug' configuration of the app
+ Runs all unit and integration tests
+ Builds the 'deploy' configuration of the app
- Versions the DLLs with the current major/minor version and SVN revision, e.g. 1.2.0.423
- Moves this new build to a 'release' folder on our build server
- Removes unneeded files
+ Updates IIS on the build server if required
Then when we have verified everything is ready to go up to live/staging we run another script to:
* Run migrations on live/staging server
* MSDeploy: archive current live/staging site
* MSDeploy: sync site from build to live/staging
It wasn't pretty getting to this stage, but it's mostly working like a charm now :D
I'm going to try and keep this answer updated as we make changes to our process, as there seem to be several similar questions on SA now.
|
I have used [Visual Build Pro](http://www.kinook.com/VisBuildPro/) for years, It's quite slick and easy to use and has many standard operations (like the ones you mentioned) built in.
|
Automate Deployment for Web Applications?
|
[
"",
".net",
"php",
"deployment",
"web-applications",
""
] |
What is the proper way for an MFC application to cleanly close itself?
|
Programatically Terminate an MFC Application
```
void ExitMFCApp()
{
// same as double-clicking on main window close box
ASSERT(AfxGetMainWnd() != NULL);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
```
<http://support.microsoft.com/kb/117320>
|
```
AfxGetMainWnd()->PostMessage(WM_CLOSE);
```
|
How can an MFC application terminate itself?
|
[
"",
"c++",
"visual-c++",
"mfc",
""
] |
I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?
Here's one way I thought of but it doesn't seem right:
**Edit:** I'm using C++.
```
class Gui {
public:
void update_all();
void draw_all() const;
int add_button(Button *button); // Returns button id
void remove_button(int button_id);
private:
Button *buttons[10];
int num_buttons;
}
```
This code has a few problems, but I just wanted to give you an idea of what I want.
|
This question is very similar to one I was going to post, only mine is for Sony PSP programming.
I've been toying with something for a while, I've consulted some books and [VTMs](http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1), and so far this is a rough idea of a simple ui systems.
```
class uiElement()
{
...
virtual void Update() = 0;
virtual void Draw() = 0;
...
}
class uiButton() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
class uiTextbox() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
... // Other ui Elements
class uiWindow()
{
...
void Update();
void Draw();
void AddElement(uiElement *Element);
void RemoveElement(uiElement *Element);
std::list <uiElement*> Elements;
...
}
void uiWindow::Update()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Update();
...
}
void uiWindow::Draw()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Draw();
...
}
```
The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions.
I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu.
Hope this helps.
thing2k
|
For anyone who's interested, here's my open source, BSD-licenced GUI toolkit for the DS:
<http://www.sourceforge.net/projects/woopsi>
thing2k's answer is pretty good, but I'd seriously recommend having code to contain child UI elements in the base uiElement class. This is the pattern I've followed in Woopsi.
If you *don't* support this in the base class, you'll run into major problems when you try to implement anything more complex than a textbox and a button. For example:
* Tab bars can be modelled as multiple buttons grouped together into a single parent UI element that enforces mutual exclusiveness of selection;
* Radio button groups (ditto);
* Scroll bars can be represented as a slider/gutter element and up/down buttons;
* Scrolling lists can be represented as a container and multiple option UI elements.
Also, it's worth remembering that the DS has a 66MHz CPU and 4MB of RAM, which is used both to store your program and execute it (DS ROMs are loaded into RAM before they are run). You should really be treating it as an embedded system, which means the STL is out. I removed the STL from Woopsi and managed to save 0.5MB. Not a lot by desktop standards, but that's 1/8th of the DS' total available memory consumed by STL junk.
I've detailed the entire process of writing the UI on my blog:
<http://ant.simianzombie.com/blog>
It includes descriptions of the two algorithms I came up with for redrawing the screen, which is the trickiest part of creating a GUI (one just splits rectangles up and remembers visible regions; the other uses BSP trees, which is much more efficient and easier to understand), tips for optimisation, etc.
|
How do I make a GUI?
|
[
"",
"c++",
"user-interface",
""
] |
I'm downloading a web page (tag soup HTML) with XMLHttpRequest and I want to take the output and turn it into a DOM object that I can then run XPATH queries on. How do I convert from a string into DOM object?
It appears that the general solution is to create a hidden iframe and throw the contents of the string into that. There has been [talk](http://starkravingfinkle.org/blog/2007/03/how-to-parse-html-in-mozilla/) of updating [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) to support text/html but as of Firefox 3.0.1 you still get an `NS_ERROR_NOT_IMPLEMENTED` if you try.
Is there any option besides using the hidden iframe trick? And if not, what is the best way to do the iframe trick so that your code works outside the context of any currently open tabs (so that closing tabs won't screw up the code, etc)?
[This](http://mxr.mozilla.org/mozilla/source/browser/components/microsummaries/src/nsMicrosummaryService.js#2090) is an example of why I'm looking for a solution other than the iframe hack, if I have to write *all* that code to have a robust solution, then I'd rather keep looking for something else.
|
Ajaxian actually had a [post on inserting / retrieving html from an iframe](http://ajaxian.com/archives/introducing-html-into-an-iframe-and-getting-it-back) today. You can probably use the js snippet they have posted there.
As for handling closing of a browser / tab, you can attach to the onbeforeunload (<http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx>) event and do whatever you need to do.
|
**Try this:**
```
var request = new XMLHttpRequest();
request.overrideMimeType( 'text/xml' );
request.onreadystatechange = process;
request.open ( 'GET', url );
request.send( null );
function process() {
if ( request.readyState == 4 && request.status == 200 ) {
var xml = request.responseXML;
}
}
```
Notice the **overrideMimeType** and **responseXML**.
The `readyState == 4` is 'completed'.
|
How can I turn a string of HTML into a DOM object in a Firefox extension?
|
[
"",
"javascript",
"firefox",
"dom",
""
] |
Is Boost the only way for VS2005 users experience TR2? Also is there a idiot proof way of downloading only the TR2 related packages?
I was looking at the boost installer provided by BoostPro Consulting. If I select the options for all the threading options with all the packages for MSVC8 it requires 1.1GB. While I am not short of space, it seems ridiculous that a **library** needs over a gigabyte of space and it takes BPC a long time to catch up with the current release.
What packages do I need? I'm really only interested in those that comprise std::tr2 and can find that out by comparing those on offer to those in from the TR2 report and selecting those from the list but even then it isn't clear what is needed and the fact that it is a version behind annoys me.
I know from previous encounters with Boost (1.33.1) that self compiling is a miserable experience: A lot of time wasted to get it started and then a hoard of errors passes across your screen faster than you can read, so what you are left with is an uneasy feeling that something is broken but you don't quite know what.
I've never had these problems with any Apache library but that is another rant...
|
I believe you're actually referring to [TR1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1745.pdf), rather than TR2. The call for proposals for TR2 is open, but don't expect to see much movement until the new C++ standard is out. Also, although boost is a provider of an implementation of TR1, dinkumware and the GNU FSF are other providers - on VC2005 boost is probably the easiest way to access this functionality.
The libraries from boost which are likely to be of most importance are
* reference
* smart pointer
* bind
* type traits
* array
* regular expressions
The documentation for building boost has been gradually improving for the last few releases, the current [getting started guide](http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html) is quite detailed. smart pointer and bind, should work from header files, and IMO, these are the most useful elements of TR1.
|
Part of the beauty of Boost is that all code is in header files. They have to for template reasons. So probably downloading the code and including it in your project will work. There are some libraries in Boost that do need compiling, but as long as you don't need those...
|
C++ std::tr2 for VS2005
|
[
"",
"c++",
"boost",
"visual-studio-2005",
"c++-tr2",
""
] |
For example, in Java there is [Functional Java](http://functionaljava.org/) and [Higher-Order Java](http://www.cs.chalmers.se/~bringert/hoj/). Both essentially give a small API for manipulating higher-order, curried functions, and perhaps a few new data types (tuples, immutable lists).
|
have you looked into [F#](https://www.microsoft.com/en-us/research/project/f-at-microsoft-research/?from=http://research.microsoft.com/fsharp/fsharp.aspx)?
Also a neat blog post would be [here](https://web.archive.org/web/20210121191830/http://geekswithblogs.net/akraus1/articles/79880.aspx) that talks about how to use the new generic / lambda expressions built into c# 3.0.
If you just add using System.Linq to the top of your source file there are a LOT of nice new functions added to working with collections such as folding / filtering / etc.
|
LanguageExt looks **very** promising for making functional style programming in C# easier.
<https://github.com/louthy/language-ext>
|
Is there a Functional Programming library for .NET?
|
[
"",
"c#",
".net",
"functional-programming",
""
] |
My company is currently using Sage MAS as their ERP system. While integrating our shopping cart is not going to be impossible, it uses COM and has it's own challenges.
I was wondering if there was a more developer friendly ERP out there. I have looked into Microsoft Dynamics but getting information on ERP systems that isn't a bunch of business jargon is next to impossible.
I will be using C# 3.whatever and .NET MVC.
|
MS Dyanamics is very cool app. V3 was fully Web Serviced V4 i assume even more- all actions are exposed as webservices, there is a big license hit on MS CRM due to "internet" licensing.
We use CRMv3 in a totally .NET SOA here and its great.
You should have no problems doing the integration - security aside =>
|
When you talk about Microsoft Dynamics, it sounds a bit like you are talking about a specific product. However there are close to 10 different systems in the Dynamics line-up from Microsoft and at least 6 of them are different ERP system, all with different functionalities and extendabilities. The new verions of Microsoft Dynamics AX as well as Microsoft Dynamics NAV, have Web service support out of the box.
I hope this helps.
|
Developer Friendly ERP
|
[
"",
"c#",
"erp",
""
] |
Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.
```
<?php
abstract class ParentClass {
public static function whoAmI () {
// NOT correct, always gives 'ParentClass'
$class = __CLASS__;
// NOT correct, always gives 'ParentClass'.
// Also very round-about and likely slow.
$trace = debug_backtrace();
$class = $trace[0]['class'];
return $class;
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
// Shows 'ParentClass'
// Want to show 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";
// Shows 'ParentClass'
// Want to show 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
```
|
Now that PHP 5.3 is widely available in the wild, I wanted to put together a summary answer to this question to reflect newly available techniques.
As mentioned in the other answers, PHP 5.3 has introduced [Late Static Binding](http://php.benscom.com/manual/en/language.oop5.late-static-bindings.php) via a new [`static`](http://php.benscom.com/manual/en/language.oop5.static.php) keyword. As well, a new [`get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) function is also available that can only be used within a class method (instance or static).
For the purpose of determining the class as was asked in this question, the `get_called_class()` function is appropriate:
```
<?php
abstract class ParentClass {
public static function whoAmI () {
return get_called_class();
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
// Shows 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";
// Shows 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
```
The [user contributed notes for `get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) include a few sample implementations that should work in PHP 5.2 as well by making use of `debug_backtrace()`.
|
I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Static Binding feature.
<http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html>
|
Is there any way to detect the target class in static methods?
|
[
"",
"php",
"oop",
"php-5.3",
"php-5.2",
""
] |
I've used the PHP MVC framework Symfony to build an on-demand web app.
It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as [this one](http://robrosenbaum.com/php/howto-disable-session-timeout-in-symfony/) did not help me.
I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future.
Has anyone been there and solved it? I would be most grateful for a hint or two!
|
I looked into it, and my coworker agrees that a heartbeat page call should work, you just have to make sure that the action invoked does reset the session timer (things like ajax field completion don't do this on their own).
|
The company I work for has been using Symfony and the workaround that we've used is to trigger a warning with javascript before the user gets logged out. I suspect that there is a a way to make 'heartbeat' ajax calls to the server to trigger the timer to reset, but that may be a lot of trouble. I think that there may not be a full fix that's suitable for you though, except maybe re-writing the session handler.
Sorry I couldn't be more specific, if I get the chance, I'll ask our Symfony devs if they know of a better solution.
|
How to prevent session timeout in Symfony 1.0?
|
[
"",
"php",
"symfony1",
""
] |
For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.
|
This should work (or something close):
```
select table_name
from all_constraints
where constraint_type='R'
and r_constraint_name in
(select constraint_name
from all_constraints
where constraint_type in ('P','U')
and table_name='<your table here>');
```
|
The following statement should give the children and all of their descendents. I have tested it on an Oracle 10 database.
```
SELECT level, main.table_name parent,
link.table_name child
FROM user_constraints main, user_constraints link
WHERE main.constraint_type IN ('P', 'U')
AND link.r_constraint_name = main.constraint_name
START WITH main.table_name LIKE UPPER('&&table_name')
CONNECT BY main.table_name = PRIOR link.table_name
ORDER BY level, main.table_name, link.table_name
```
|
Query a Table's Foreign Key relationships
|
[
"",
"sql",
"database",
"oracle",
"oracle10g",
""
] |
What would be the best way to implement a simple crash / error reporting mechanism?
Details: my app is **cross-platform (mac/windows/linux) and written in Python**, so I just need something that will send me a small amount of text, e.g. just a timestamp and a traceback (which I already generate and show in my error dialog).
It would be fine if it could simply email it, but I can't think of a way to do this without including a username and password for the smtp server in the application...
Should I implement a simple web service on the server side and have my app send it an HTTP request with the info? Any better ideas?
|
The web service is the best way, but there are some caveats:
1. You should always ask the user if it is ok to send error feedback information.
2. You should be prepared to fail gracefully if there are network errors. Don't let a failure to report a crash impede recovery!
3. You should avoid including user identifying or sensitive information unless the user knows (see #1) and you should either use SSL or otherwise protect it. Some jurisdictions impose burdens on you that you might not want to deal with, so it's best to simply not save such information.
4. Like any web service, make sure your service is not exploitable by miscreants.
|
> I can't think of a way to do this without including a username and password for the smtp server in the application...
You only need a username and password for authenticating yourself to a smarthost. You don't need it to send mail directly, you need it to send mail through a relay, e.g. your ISP's mail server. It's perfectly possible to send email without authentication - that's why spam is so hard to stop.
Having said that, some ISPs block outbound traffic on port 25, so the most robust alternative is an HTTP POST, which is unlikely to be blocked by anything. Be sure to pick a URL that you won't feel restricted by later on, or better yet, have the application periodically check for updates, so if you decide to change domains or something, you can push an update in advance.
Security isn't really an issue. You can fairly easily discard junk data, so all that really concerns you is whether or not somebody would go to the trouble of constructing fake tracebacks to mess with you, and that's a very unlikely situation.
As for the payload, [PyCrash](http://pycrash.sourceforge.net/) can help you with that.
|
How to best implement simple crash / error reporting?
|
[
"",
"python",
"cross-platform",
"error-reporting",
""
] |
I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s).
The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing?
```
SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)
```
or
```
SELECT email FROM tClient WHERE timezoneID = 1
UNION ALL SELECT email FROM tClient WHERE timezoneID = 4
UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9
```
*Edit: **timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName.***
*Also, I went with `WHERE IN` since I didn't feel like opening up the analyzer.*
*Edit 2: **Query processes 200k rows in under 100 ms, so at this point I'm done.***
|
# Hey! These queries are not equivalent.
Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster.
Always use UNION ALL, unless you know why you want to use UNION.
If you are not sure what is difference see [this](https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all-in-oracle) SO question.
*Note: that yell belongs to [previous version](https://stackoverflow.com/revisions/viewmarkup/31874) of question.*
|
For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary.
I would likely go with the first using the IN clause since that carries the most semantics of what you want. The timezoneID seems like a primary key on some timezone table, so it should be a foreign key on email and indexed. Depending on the DB optimizer, I would think it should do an index scan on the foreign key index.
|
What's optimal? UNION vs WHERE IN (str1, str2, str3)
|
[
"",
"sql",
"optimization",
""
] |
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)
Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.
A Python solution would be ideal, but doesn't appear to be available.
|
I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).
```
import os
def doc_to_text_catdoc(filename):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
# similar doc_to_text_antiword()
```
The -w switch to catdoc turns off line wrapping, BTW.
|
(Same answer as [extracting text from MS word files in python](https://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python))
Use the native Python docx module which I made this week. Here's how to extract all the text from a doc:
```
document = opendocx('Hello world.docx')
# This location is where most document content lives
docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0]
# Extract all text
print getdocumenttext(document)
```
See [Python DocX site](https://python-docx.readthedocs.org/en/latest/)
100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs.
|
Best way to extract text from a Word doc without using COM/automation?
|
[
"",
"python",
"ms-word",
""
] |
I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.
I know I can use a cursor, but that seems inelegant.
MS-SQL 2000,BTW
|
```
update MyTable Set RandomFld = CONVERT(varchar(10), NEWID())
```
|
You might be able to adapt something [like this](http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/249/creating-random-sql-server-test-data.aspx) to load a test dataset of values, depending on what you are looking for
|
How to update a field with random data?
|
[
"",
"sql",
"sql-server",
""
] |
We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate?
Thanks
Tom
|
Can you pass a Java system property for each job? If so, you can parameterize like this:
```
java -Dmy_var=somevalue my.job.Classname
```
And then in your log4j.properties:
```
log4j.appender.A.File=${my_var}/A.log
```
You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job.
|
If the job names are known ahead of time, you could include the job name when you do the getLogger() call. You then can bind different appenders to different loggers, with separate file names (or other destinations).
If you cannot know the job name ahead of time, you could configure the logger at runtime instead of using a configuration file:
```
FileAppender appender = new FileAppender();
appender.setFileName(...);
appender.setLayout(...);
Logger logger = Logger.getLogger("com.company.job."+jobName);
logger.addAppender(appender);
```
|
log4j log file names?
|
[
"",
"java",
"logging",
"log4j",
""
] |
How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?
For example how can I convert:
> How do I generate a Friendly URL in C#?
Into
> how-do-i-generate-a-friendly-url-in-C
|
There are several things that could be improved in Jeff's solution, though.
```
if (String.IsNullOrEmpty(title)) return "";
```
IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.
```
// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one
```
Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.
```
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
```
Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.
Off the top of my head, without any testing whatsoever, this would be an equivalent solution:
```
// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;
```
Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.
|
Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..
```
if (String.IsNullOrEmpty(title)) return "";
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
title = title.Substring(0, title.Length - 1);
return title;
```
|
How do I generate a Friendly URL in C#?
|
[
"",
"c#",
"friendly-url",
""
] |
Is there any way to force a listview control to treat all clicks as though they were done through the Control key?
I need to replicate the functionality of using the control key (selecting an item sets and unsets its selection status) in order to allow the user to easily select multiple items at the same time.
Thank you in advance.
|
It's not the standard behaviour of the ListView control, even when MultiSelect is set to true.
If you wanted to create your own custom control you would need to do the following:
1. Derive a control from ListView
2. add a handler to the "Selected" event.
3. In the "OnSelected", maintain your own list of selected items.
4. If the newly selected item is not in your list, add it. If it is, remove it.
5. In code, select all of the items in your list.
Should be simple enough to implement and feel like multi-select without using the control key!
|
Here is the complete solution that I used to solve this problem using WndProc. Basically, it does a hit test when the mouse is clicked.. then if MutliSelect is on, it will automatically toggle the item on/off [.Selected] and not worry about maintaining any other lists or messing with the ListView functionality.
I haven't tested this in all scenarios, ... it worked for me. YMMV.
```
public class MultiSelectNoCTRLKeyListView : ListView {
public MultiSelectNoCTRLKeyListView() {
}
public const int WM_LBUTTONDOWN = 0x0201;
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case WM_LBUTTONDOWN:
if (!this.MultiSelect)
break;
int x = (m.LParam.ToInt32() & 0xffff);
int y = (m.LParam.ToInt32() >> 16) & 0xffff;
var hitTest = this.HitTest(x, y);
if (hitTest != null && hitTest.Item != null)
hitTest.Item.Selected = !hitTest.Item.Selected;
return;
}
base.WndProc(ref m);
}
}
```
|
Listview Multiple Selection
|
[
"",
"c#",
"winforms",
""
] |
Can you please point to alternative data storage tools and give good reasons to use them instead of good-old relational databases? In my opinion, most applications rarely use the full power of SQL--it would be interesting to see how to build an SQL-free application.
|
Plain text files in a filesystem
* Very simple to create and edit
* Easy for users to manipulate with simple tools (i.e. text editors, grep etc)
* Efficient storage of binary documents
---
XML or JSON files on disk
* As above, but with a bit more ability to validate the structure.
---
Spreadsheet / CSV file
* Very easy model for business users to understand
---
Subversion (or similar disk based version control system)
* Very good support for versioning of data
---
[Berkeley DB](http://www.oracle.com/technology/products/berkeley-db/index.html) (Basically, a disk based hashtable)
* Very simple conceptually (just un-typed key/value)
* Quite fast
* No administration overhead
* Supports transactions I believe
---
[Amazon's Simple DB](http://www.amazon.com/SimpleDB-AWS-Service-Pricing/b/ref=sc_fe_l_2?ie=UTF8&node=342335011&no=3435361&me=A36L942TSJ2AJA)
* Much like Berkeley DB I believe, but hosted
---
[Google's App Engine Datastore](http://code.google.com/appengine/docs/datastore/)
* Hosted and highly scalable
* Per document key-value storage (i.e. flexible data model)
---
[CouchDB](http://incubator.apache.org/couchdb/)
* Document focus
* Simple storage of semi-structured / document based data
---
Native language collections (stored in memory or serialised on disk)
* Very tight language integration
---
Custom (hand-written) storage engine
* Potentially very high performance in required uses cases
---
I can't claim to know anything much about them, but you might also like to look into [object database systems](http://en.wikipedia.org/wiki/Object_database).
|
Matt Sheppard's answer is great (mod up), but I would take account these factors when thinking about a spindle:
1. Structure : does it obviously break into pieces, or are you making tradeoffs?
2. Usage : how will the data be analyzed/retrieved/grokked?
3. Lifetime : how long is the data useful?
4. Size : how much data is there?
One particular advantage of CSV files over RDBMSes is that they can be easy to condense and move around to practically any other machine. We do large data transfers, and everything's simple enough we just use one big CSV file, and easy to script using tools like rsync. To reduce repetition on big CSV files, you could use something like [YAML](http://yaml.org). I'm not sure I'd store anything like JSON or XML, unless you had significant relationship requirements.
As far as not-mentioned alternatives, don't discount [Hadoop](http://hadoop.apache.org/core/), which is an open source implementation of MapReduce. This should work well if you have a TON of loosely structured data that needs to be analyzed, and you want to be in a scenario where you can just add 10 more machines to handle data processing.
For example, I started trying to analyze performance that was essentially all timing numbers of different functions logged across around 20 machines. After trying to stick everything in a RDBMS, I realized that I really don't need to query the data again once I've aggregated it. And, it's only useful in it's aggregated format to me. So, I keep the log files around, compressed, and then leave the aggregated data in a DB.
*Note* I'm more used to thinking with "big" sizes.
|
Good reasons NOT to use a relational database?
|
[
"",
"sql",
"database",
"nosql",
""
] |
How do I enumerate the properties of a JavaScript object?
I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
|
Simple enough:
```
for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}
```
Now, you will not get private variables this way because they are not available.
---
EDIT: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) is correct that unless you use the `hasOwnProperty()` method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.
Now, that said, `hasOwnProperty()` *is* useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.
EDIT 2: [@bitwiseplatypus](https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306) brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use `hasOwnProperty()`. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via `jQuery.extend` and `jQuery.fn.extend`).
|
Use a `for..in` loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.
```
var myObject = {foo: 'bar'};
for (var name in myObject) {
alert(name);
}
// results in a single alert of 'foo'
Object.prototype.baz = 'quux';
for (var name in myObject) {
alert(name);
}
// results in two alerts, one for 'foo' and one for 'baz'
```
To avoid including inherited properties in your enumeration, check `hasOwnProperty()`:
```
for (var name in myObject) {
if (myObject.hasOwnProperty(name)) {
alert(name);
}
}
```
**Edit:** I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There *is* danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.
It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.
This is why JavaScript provides `hasOwnProperty()`, and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using `hasOwnProperty()`.
|
How do I enumerate the properties of a JavaScript object?
|
[
"",
"javascript",
"properties",
""
] |
I know what `yield` does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?
(Ideally some problem that cannot be solved some other way)
|
I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement.
The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.
For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list\_size \* row\_size bytes of memory.
Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a "streaming" capability over large sets of data.
Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).
Regarding:
```
Ideally some problem that cannot be solved some other way
```
The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way.
Here are a couple of more recent questions and answers that provide more detail:
[Yield keyword value added?](https://stackoverflow.com/questions/384392/yield-keyword-value-added)
[Is yield useful outside of LINQ?](https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq)
|
actually I use it in a non traditional way on my site [IdeaPipe](http://www.ideapipe.com)
```
public override IEnumerator<T> GetEnumerator()
{
// goes through the collection and only returns the ones that are visible for the current user
// this is done at this level instead of the display level so that ideas do not bleed through
// on services
foreach (T idea in InternalCollection)
if (idea.IsViewingAuthorized)
yield return idea;
}
```
so basically it checks if viewing the idea is currently authorized and if it is it returns the idea. If it isn't, it is just skipped. This allows me to cache the Ideas but still display the ideas to the users that are authorized. Else I would have to re pull them each time based on permissions, when they are only re-ranked every 1 hour.
|
What are real life applications of yield?
|
[
"",
"c#",
".net",
"yield",
""
] |
How do i measure how long a client has to wait for a request.
On the server side it is easy, through a filter for example.
But if we want to take into accout the total time including latency and data transfer, it gets diffcult.
is it possible to access the underlying socket to see when the request is finished?
or is it neccessary to do some javascript tricks? maybe through clock synchronisation between browser and server? are there any premade javascripts for this task?
|
There's no way you can know how long the client had to wait purely from the server side. You'll need some JavaScript.
You don't want to synchronize the client and server clocks, that's overkill. Just measure the time between when the client makes the request, and when it finishes displaying its response.
If the client is AJAX, this can be pretty easy: call new Date().getTime() to get the time in milliseconds when the request is made, and compare it to the time after the result is parsed. Then send this timing info to the server in the background.
For a non-AJAX application, when the user clicks on a request, use JavaScript to send the current timestamp (from the client's point of view) to the server along with the query, and pass that same timestamp back through to the client when the resulting page is reloaded. In that page's onLoad handler, measure the total elapsed time, and then send it back to the server - either using an XmlHttpRequest or tacking on an extra argument to the next request made to the server.
|
You could wrap the HttpServletResponse object and the OutputStream returned by the HttpServletResponse. When output starts writing you could set a startDate, and when it stops (or when it's flushed etc) you can set a stopDate.
This can be used to calculate the length of time it took to stream all the data back to the client.
We're using it in our application and the numbers look reasonable.
edit: you can set the start date in a ServletFilter to get the length of time the client waited. I gave you the length of time it took to write output to the client.
|
Measure Total Network Transfer Time from Servlets
|
[
"",
"java",
"tomcat",
"servlets",
"time",
"sockets",
""
] |
```
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
```
---
This is the output I am getting. I see the data is there in datarray but when
I `echo $_GET[$field]`
I only get "Array"
But `print_r($datarray)` prints all the data. Any idea how I pull those values?
## OUTPUT
```
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
```
|
EDIT: When I completed your test, here was the final URL:
<http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24>
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
<http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan®ion=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24>
This will create individual entries for most of the fields, and make $\_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
|
Use `var_export($_GET)` to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
```
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
```
so to get those variables out you need something like:
```
echo $_GET[0][0][0]; // => "Grade1"
```
|
Php $_GET issue
|
[
"",
"php",
"arrays",
"printing",
"foreach",
"get",
""
] |
I'm trying to the the flv Flash player [from here](http://www.jeroenwijering.com/?item=JW_FLV_Player) in a windows forms application. I currently have it playing 1 .flv file with no problems but I really need to be able to play multiple files. Has anyone had experienace of using the playlists that this control offers or is there a better way to do this?
|
Can you get the control to run the way you want it in a webpage/browser? If yes (and the problem is with winforms, I'd just embed it in a browser control. If no, I'd as the creators directly.
|
I would be very hesitant to place the WebBrowser control between your software and the flv, because you will lose all control of the flv and will not get any meaningful notifications about its status. The lack of tight integration will lead to a very poor user experience. The blog post [here](http://weblogs.asp.net/twalters/archive/2003/12/29/46265.aspx) has instructions on embedding flash via COM.
|
Embedding flv (flash) player in windows forms
|
[
"",
"c#",
"winforms",
"flash",
"flv",
"embedded-flashplayer",
""
] |
Using C# 2.0 what is the best way to implement dynamic form controls?
I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?
|
You can use panels with automatic layout such as [FlowLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.asp) and [TableLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx).
Unfortunately there are only 2 panels with automatic layout out of box but you can create custom layout panel.
I would recommend you to read following articles:
[How to: Create a Resizable Windows Form for Data Entry](http://msdn.microsoft.com/en-us/library/d4d31tbk.aspx)
[Walkthrough: Creating a Resizable Windows Form for Data Entry](http://msdn.microsoft.com/en-us/library/991eahec.aspx)
Another option would be using of WPF (Windows Presentation Presentation).
WPF is a perfect match for your task.
WPF controls can be hosted in WinForms apps so you don't have to switch to it completely.
|
@Sam I know this question was about Windows Forms, but you should definitely start looking at WPF. This sort of scenario is *really* easy in WPF with DataTemplates and TemplateSelectors.
|
Dynamic Form Controls
|
[
"",
"c#",
".net",
"winforms",
""
] |
We are trying to create a web-service that we plan to pass a variable amount of variables to it.
Can this be done?
Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.
Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.
```
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
```
Will this work or should we do a different way?
|
I would pass in an xml document instead of doing concreate functions for this.
The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally.
XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice.
Take a look at these
[IBM Developer](http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html)
[ASP.NET Forum](http://forums.asp.net/p/1253455/2323689.aspx#2323689)
I would also recommend using this for testing webservices and its free
[WSStudio](http://www.codeplex.com/wsstudioexpress)
|
You can simply pass a variable-length array as a parameter.
|
How to you pass a variable amount of parmeters to web-service
|
[
"",
"c#",
"web-services",
"soap",
""
] |
example:
```
a_list = [1, 2, 3]
a_list.len() # doesn't work
len(a_list) # works
```
Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object.
Plus I keep trying the wrong solution since it appears as the logical one to me
|
Guido's explanation is [here](http://mail.python.org/pipermail/python-3000/2006-November/004643.html):
> First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwined reasons actually, both HCI:
>
> (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x\*(a+b) into x\*a + x\*b to the clumsiness of doing the same thing using a raw OO notation.
>
> (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
>
> Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
|
The short answer: 1) backwards compatibility and 2) there's not enough of a difference for it to really matter. For a more detailed explanation, read on.
The idiomatic Python approach to such operations is special methods which aren't intended to be called directly. For example, to make `x + y` work for your own class, you write a `__add__` method. To make sure that `int(spam)` properly converts your custom class, write a `__int__` method. To make sure that `len(foo)` does something sensible, write a `__len__` method.
This is how things have always been with Python, and I think it makes a lot of sense for some things. In particular, this seems like a sensible way to implement operator overloading. As for the rest, different languages disagree; in Ruby you'd convert something to an integer by calling `spam.to_i` directly instead of saying `int(spam)`.
You're right that Python is an extremely object-oriented language and that having to call an external function on an object to get its length seems odd. On the other hand, `len(silly_walks)` isn't any more onerous than `silly_walks.len()`, and Guido has said that he actually prefers it (<http://mail.python.org/pipermail/python-3000/2006-November/004643.html>).
|
Why isn't the 'len' function inherited by dictionaries and lists in Python
|
[
"",
"python",
""
] |
It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead.
One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing? Is the whole URL to the file used as a key in the browser's cache, or is it just the filename itself and some meta-data?
If my code changes from fetching `/r20/example.js` to `/r21/example.js`, can I be sure that revision 20 of `example.js` was cached, but now revision 21 has been fetched instead and it is now cached?
|
Yes, any change in *any part* of the URL (excluding HTTP and HTTPS protocols changes) is interpreted as a different resource by the browser (and any intermediary proxies), and will thus result in a separate entity in the browser-cache.
**Update:**
The claim in [this ThinkVitamin article](http://www.thinkvitamin.com/features/webapps/serving-javascript-fast) that Opera and Safari/Webkit browsers don't cache URLs with ?query=strings is **false**.
Adding a version number parameter to a URL is a perfectly acceptable way to do cache-busting.
What may have confused the author of the ThinkVitamin article is the fact that hitting Enter in the address/location bar in Safari and Opera results in different behavior for URLs with query string in them.
However, (*and this is the important part!*) Opera and Safari **behave just like IE and Firefox** when it comes to caching embedded/linked images and stylesheets and scripts in web pages - regardless of whether they have "?" characters in their URLs. (This can be verified with a simple test on a normal Apache server.)
(I would have commented on the currently accepted answer if I had the reputation to do it. :-)
|
Browser cache key is a combination of the request method and resource URI. URI consists of scheme, authority, path, query, and fragment.
Relevant excerpt from [HTTP 1.1 specification](https://www.rfc-editor.org/rfc/rfc7234#section-2):
> The primary cache key consists of the request method and target URI.
> However, since HTTP caches in common use today are typically limited
> to caching responses to GET, many caches simply decline other methods
> and use only the URI as the primary cache key.
Relevant excerpt from [URI specification](https://www.rfc-editor.org/rfc/rfc3986#section-3):
> The generic URI syntax consists of a hierarchical sequence of
> components referred to as the scheme, authority, path, query, and
> fragment.
> ```
> URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
> ```
> ```
> hier-part = "//" authority path-abempty
> ```
```
/ path-absolute
/ path-rootless
/ path-empty
```
|
Is it the filename or the whole URL used as a key in browser caches?
|
[
"",
"javascript",
"url",
"browser",
"caching",
"filenames",
""
] |
I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.
To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.
|
To add to @David Crow, here's [a dependency:tree example](http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html) from the Maven site:
```
mvn dependency:tree -Dincludes=velocity:velocity
```
might output
```
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- velocity:velocity:jar:1.4:compile
```
|
Using the [Maven Dependency Plugin](http://maven.apache.org/plugins/maven-dependency-plugin/):
```
mvn dependency:tree
```
|
In Maven 2, how do I know from which dependency comes a transitive dependency?
|
[
"",
"java",
"maven-2",
"build-process",
""
] |
I'm wondering the *best* way to start a pthread that is a member of a C++ class? My own approach follows as an answer...
|
I usually use a static member function of the class, and use a pointer to the class as the void \* parameter. That function can then either perform thread processing, or call another non-static member function with the class reference. That function can then reference all class members without awkward syntax.
|
This can be simply done by using the boost library, like this:
```
#include <boost/thread.hpp>
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
boost::thread* pThread = new boost::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
```
Notes:
* This uses an ordinary class member function. There is no need to add extra, static members which confuse your class interface
* Just include boost/thread.hpp in the source file where you start the thread. If you are just starting with boost, all the rest of that large and intimidating package can be ignored.
In C++11 you can do the same but without boost
```
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
std::thread * pThread = new std::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
```
|
Best way to start a thread as a member of a C++ class?
|
[
"",
"c++",
"pthreads",
""
] |
I have **1 red polygon** say and **50 randomly placed blue polygons** - they are situated in geographical **2D space**. What is the quickest/speediest algorithim to find the the shortest distance between a red polygon and its nearest blue polygon?
Bear in mind that it is not a simple case of taking the points that make up the vertices of the polygon as values to test for distance as they may not necessarily be the closest points.
So in the end - the answer should give back the closest blue polygon to the singular red one.
This is harder than it sounds!
|
I doubt there is better solution than calculating the distance between the red one and every blue one and sorting these by length.
Regarding sorting, usually QuickSort is hard to beat in performance (an optimized one, that cuts off recursion if size goes below 7 items and switches to something like InsertionSort, maybe ShellSort).
Thus I guess the question is how to quickly calculate the distance between two polygons, after all you need to make this computation 50 times.
The following approach will work for 3D as well, but is probably not the fastest one:
[Minimum Polygon Distance in 2D Space](http://cgm.cs.mcgill.ca/~orm/mind2p.html)
The question is, are you willing to trade accuracy for speed? E.g. you can pack all polygons into bounding boxes, where the sides of the boxes are parallel to the coordinate system axes. 3D games use this approach pretty often. Therefor you need to find the maximum and minimum values for every coordinate (x, y, z) to construct the virtual bounding box. Calculating the distances of these bounding boxes is then a pretty trivial task.
Here's an example image of more advanced bounding boxes, that are not parallel to the coordinate system axes:
[Oriented Bounding Boxes - OBB](http://xna-uk.net/photos/screen_shots/images/1291/original.aspx)
However, this makes the distance calculation less trivial. It is used for collision detection, as you don't need to know the distance for that, you only need to know if one edge of one bounding box lies within another bounding box.
The following image shows an axes aligned bounding box:
[Axes Aligned Bounding Box - AABB](http://www.gamasutra.com/features/20000330/bobic_05.gif)
OOBs are more accurate, AABBs are faster. Maybe you'd like to read this article:
[Advanced Collision Detection Techniques](http://www.gamasutra.com/features/20000330/bobic_pfv.htm)
This is always assuming, that you are willing to trade precision for speed. If precision is more important than speed, you may need a more advanced technique.
|
You might be able to reduce the problem, and then do an intensive search on a small set.
Process each polygon first by finding:
* Center of polygon
* Maximum radius of polygon (i.e., point on edge/surface/vertex of the polygon furthest from the defined center)
Now you can collect, say, the 5-10 closest polygons to the red one (find the distance center to center, subtract the radius, sort the list and take the top 5) and then do a much more exhaustive routine.
|
What is the quickest way to find the shortest cartesian distance between two polygons
|
[
"",
"c#",
"algorithm",
"gis",
"polygon",
"distance",
""
] |
My web application has a login page that submits authentication credentials via an AJAX call. If the user enters the correct username and password, everything is fine, but if not, the following happens:
1. The web server determines that although the request included a well-formed Authorization header, the credentials in the header do not successfully authenticate.
2. The web server returns a 401 status code and includes one or more WWW-Authenticate headers listing the supported authentication types.
3. The browser detects that the response to my call on the XMLHttpRequest object is a 401 and the response includes WWW-Authenticate headers. It then pops up an authentication dialog asking, again, for the username and password.
This is all fine up until step 3. I don't want the dialog to pop up, I want want to handle the 401 response in my AJAX callback function. (For example, by displaying an error message on the login page.) I want the user to re-enter their username and password, of course, but I want them to see my friendly, reassuring login form, not the browser's ugly, default authentication dialog.
Incidentally, I have no control over the server, so having it return a custom status code (i.e., something other than a 401) is not an option.
Is there any way I can suppress the authentication dialog? In particular, can I suppress the Authentication Required dialog in Firefox 2 or later? Is there any way to suppress the Connect to *[host]* dialog in IE 6 and later?
---
**Edit**
*Additional information from the author (Sept. 18):*
I should add that the real problem with the browser's authentication dialog popping up is that it give insufficient information to the user.
The user has just entered a username and password via the form on the login page, he believes he has typed them both correctly, and he has clicked the submit button or hit enter. His expectation is that he will be taken to the next page or perhaps told that he has entered his information incorrectly and should try again. However, he is instead presented with an unexpected dialog box.
The dialog makes no acknowledgment of the fact he just *did* enter a username and password. It does not clearly state that there was a problem and that he should try again. Instead, the dialog box presents the user with cryptic information like "The site says: '*[realm]*'." Where *[realm]* is a short realm name that only a programmer could love.
Web broswer designers take note: no one would ask how to suppress the authentication dialog if the dialog itself were simply more user-friendly. The *entire* reason that I am doing a login form is that our product management team rightly considers the browsers' authentication dialogs to be awful.
|
I don't think this is possible -- if you use the browser's HTTP client implementation, it will always pop up that dialog. Two hacks come to mind:
1. Maybe Flash handles this differently (I haven't tried yet), so having a flash movie make the request might help.
2. You can set up a 'proxie' for the service that you're accessing on your own server, and have it modify the authentication headers a bit, so that the browser doesn't recognise them.
|
I encountered the same issue here, and the backend engineer at my company implemented a behavior that is apparently considered a good practice : when a call to a URL returns a 401, if the client has set the header `X-Requested-With: XMLHttpRequest`, the server drops the `www-authenticate` header in its response.
The side effect is that the default authentication popup does not appear.
Make sure that your API call has the `X-Requested-With` header set to `XMLHttpRequest`. If so there is nothing to do except changing the server behavior according to this good practice...
|
How can I suppress the browser's authentication dialog?
|
[
"",
"javascript",
"ajax",
"http-authentication",
""
] |
I have a simple setter method for a property and `null` is not appropriate for this particular property. I have always been torn in this situation: should I throw an [`IllegalArgumentException`](http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html), or a [`NullPointerException`](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html)? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?
|
It seems like an `IllegalArgumentException` is called for if you don't want `null` to be an allowed value, and the `NullPointerException` would be thrown if you were trying to *use* a variable that turns out to be `null`.
|
You should be using `IllegalArgumentException` (IAE), not `NullPointerException` (NPE) for the following reasons:
First, the [NPE JavaDoc](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/NullPointerException.html) explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown *by the runtime* when `null` is used inappropriately. In contrast, the [IAE JavaDoc](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/IllegalArgumentException.html) couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!
Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a `null`. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.
Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.
Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal `null` is so special that it deserves a separate exception from all other types of illegal arguments?
Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.
|
IllegalArgumentException or NullPointerException for a null parameter?
|
[
"",
"java",
"exception",
"null",
"nullpointerexception",
"illegalargumentexception",
""
] |
I'm trying to find a way to validate a large XML file against an XSD. I saw the question [...best way to validate an XML...](https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file) but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.
Are there any other tools,libraries, strategies for validating a larger than normal XML file?
EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.
|
Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory.
```
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource(new FileReader ("document.xml")));
```
|
Use [libxml](http://xmlsoft.org/), which performs validation *and* has a streaming mode.
|
Validating a HUGE XML file
|
[
"",
"java",
"xml",
"validation",
"xsd",
""
] |
I'm maintaining some code that uses a \*= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what \*= does? I assume that it is some sort of a join.
```
select * from a, b where a.id *= b.id
```
I can't figure out how this is different from:
```
select * from a, b where a.id = b.id
```
|
From <http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm>:
Inner and outer tables
The terms outer table and inner table describe the placement of the tables in an outer join:
* In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively.
* In a right join, the outer table and inner table are the right and left tables respectively.
For example, in the queries below, T1 is the outer table and T2 is the inner table:
* T1 left join T2
* T2 right join T1
Or, using Transact-SQL syntax:
* T1 \*= T2
* T2 =\* T1
|
It means outer join, a simple = means inner join.
```
*= is LEFT JOIN and =* is RIGHT JOIN.
```
(or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for \*=)
|
*= in Sybase SQL
|
[
"",
"sql",
"t-sql",
"join",
"sybase",
""
] |
I'm looking for a Java library for SWIFT messages. I want to
* parse SWIFT messages into an object model
* validate SWIFT messages (including SWIFT network validation rules)
* build / change SWIFT messages by using an object model
Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535.
So far I've looked at two libraries
* AnaSys Message Objects ([link text](http://www.anasys.com/products/messageobjects/))
* Datamation SWIFT Message Suite ([link text](http://www.paymentcomponents.com/swift/message_suite/components_suite.html))
Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy.
AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message".
And the Datamation library seems to have the nicer API but does not find all errors.
So does anyone know other SWIFT libraries to use?
|
SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library".
From the doc:
"The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network."
Java source code will also be made available, again from the doc:
"Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format."
See: <http://www.swift.com/support/drc/develop/standards.page>
This can be a great aid in dealing with FIN messages in XML syntax.
|
Have you looked at [WIFE](http://wife.sourceforge.net/)? We use that in our application which translates SWIFT messages to an internal XML format and back again. We haven't had any problems with it. Also, it's licensed under the LGPL, so you can hack it up if you need to. Check it out.
|
Java SWIFT Library
|
[
"",
"java",
"swift-mt",
""
] |
I'm trying to use `strtotime()` to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click.
**Example:**
* It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th.
* I click the "-1 day" button again and now the readout states the 8th day.
* I click the "+1 day" button and now the readout states it's the 9th.
I understand the buttons and the displaying the date and using `$_GET` and PHP to pass info, but how do I get `strtotime()` to work on the relative date from the last time the time travel script was called?
My work so far has let me show yesterday and today relative to *now* but not relative to, for example, the *day before yesterday*, or the *day after tomorrow*. Or if I use my **"last monday"** button, the day before or after whatever that day is.
|
Working from previous calls to the same script isn't really a good idea for this type of thing.
What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it)
Example
<http://www.site.com/addOneDay.php?date=1999-12-31>
```
<?php
echo Date("Y-m-d",(strtoTime($_GET[date])+86400));
?>
```
Please note that you should check to make sure that isset($\_GET[date]) before as well
If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case.
|
Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the relative time periods. So, for example, by default, if you were showing a calendar, you'd work from todays date.
```
int strtotime ( string $time [, int $now ] )
```
You can see in the function definition here of strtotime, the second argument is now, i.e. you can change the date from which it's relative.
This might be easier to display through a quick loop
This will loop through the last 10 days using "yesterday" as the first argument. We then use date to print it out.
```
$time = time();
for ($i = 0; $i < 10; $i++) {
$time = strtotime("yesterday", $time);
print date("r", $time) . "\n";
}
```
So pass the time/date in via the URI so you can save the relative date.
|
Advancing through relative dates using strtotime()
|
[
"",
"php",
"date",
"strtotime",
""
] |
The Gang of Four's [Design Patterns](http://en.wikipedia.org/wiki/Design_Patterns) uses a word processor as an example for at least a few of their patterns, particularly Composite and Flyweight.
Other than by using C or C++, could you really use those patterns and the object-oriented overhead they entail to write a high-performing fully featured word processor?
I know that Eclipse is written in Java but I haven't used it much so I don't know if it's all that fast or as polished as something like Visual Studio, which has a C++ based text editing system.
---
I only used C++ and Java as examples. The question has more to do with the overhead of having a lot of in-memory objects like you would in an application such as a word processor or even a game.
Design patterns promote abstraction at the expense of parsimony even though they usually point out when you might take some kind of performance hit. Word processors and especially games get the most benefit from being as close to the metal as possible.
I was just wondering if anyone knew of an fast object-oriented word processor or text editor that wasn't written in C++, and whether they'd build one using patterns or would they forgoe a lot of the abstracting away of things?
|
Flyweight really is just a way of conserving resources in situations where there are thousands of objects with intrinsic shared state, so it could be useful in higher level languages than C/C++. Maybe the GoF's example using glyphs in a document was not the best choice to illustrate this pattern.
I think there's a lot more to building a high performance word processor than just these basic patterns though - not sure whether there is anything in GoF that rules out being able to successfully do this.
Generally, Visual Studio (VS) is more advanced and performs significantly better than Eclipse - at least, the versions of VS that I have seen. Eclipse is one of the most impressive Java applications out there though, it runs quite well on more recent machines with lots of RAM.
|
Well, [flyweight](http://en.wikipedia.org/wiki/Flyweight_pattern) is a ridiculous pattern to use in a word processor. IIRC, they had each character being referenced as a object [note: it was for each *glyph*, which is still crazy because your OS will happily draw that for you]. With a pointer being wider than a character and all the processing associated with indirection, you'd be mad to use that particular pattern that way in a word processor.
If you're interested in the design of word processors, I found an article that doesn't address patterns but does look at some of the [data structures underlying word processor design and design considerations](http://www.bluemug.org/research/text.pdf).
Try to remember that design patterns are there to make your life easier, not for you to be pure. There has to be a reason to use a pattern, it has to offer some benefit.
|
Can you really build a fast word processor with GoF Design Patterns?
|
[
"",
"java",
"performance",
"design-patterns",
"ide",
"text-processing",
""
] |
I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a `AutoSize = false` in my constructor, however, when I place it in design mode, the property always is True.
I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?
Here's the full source code of my Label in case anyone is interested.
```
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dentactil.UI.WinControls
{
[DefaultProperty("TextString")]
[DefaultEvent("TextClick")]
public partial class RoundedLabel : UserControl
{
private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 );
private const float DEFAULT_BORDER_WIDTH = 2.0F;
private const int DEFAULT_ROUNDED_WIDTH = 16;
private const int DEFAULT_ROUNDED_HEIGHT = 12;
private Color mBorderColor = DEFAULT_BORDER_COLOR;
private float mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH;
private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT;
public event EventHandler TextClick;
private Padding mPadding = new Padding(8);
public RoundedLabel()
{
InitializeComponent();
}
public Cursor TextCursor
{
get { return lblText.Cursor; }
set { lblText.Cursor = value; }
}
public Padding TextPadding
{
get { return mPadding; }
set
{
mPadding = value;
UpdateInternalBounds();
}
}
public ContentAlignment TextAlign
{
get { return lblText.TextAlign; }
set { lblText.TextAlign = value; }
}
public string TextString
{
get { return lblText.Text; }
set { lblText.Text = value; }
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
lblText.Font = value;
}
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
base.ForeColor = value;
lblText.ForeColor = value;
}
}
public Color BorderColor
{
get { return mBorderColor; }
set
{
mBorderColor = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_BORDER_WIDTH)]
public float BorderWidth
{
get { return mBorderWidth; }
set
{
mBorderWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_WIDTH)]
public int RoundedWidth
{
get { return mRoundedWidth; }
set
{
mRoundedWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_HEIGHT)]
public int RoundedHeight
{
get { return mRoundedHeight; }
set
{
mRoundedHeight = value;
Invalidate();
}
}
private void UpdateInternalBounds()
{
lblText.Left = mPadding.Left;
lblText.Top = mPadding.Top;
int width = Width - mPadding.Right - mPadding.Left;
lblText.Width = width > 0 ? width : 0;
int heigth = Height - mPadding.Bottom - mPadding.Top;
lblText.Height = heigth > 0 ? heigth : 0;
}
protected override void OnLoad(EventArgs e)
{
UpdateInternalBounds();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode smoothingMode = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth;
int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight;
GraphicsPath path = new GraphicsPath();
path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight);
path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90);
path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90);
path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90);
path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0);
path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90);
e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path);
e.Graphics.SmoothingMode = smoothingMode;
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
UpdateInternalBounds();
base.OnResize(e);
}
private void lblText_Click(object sender, EventArgs e)
{
if (TextClick != null)
{
TextClick(this, e);
}
}
}
}
```
(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).
---
I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)
I basically hate the autosize property "on by default".
|
I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults.
I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a *default* value of false?
|
I spent a lot of time with it and this finally works! (my code is vb.net but is simple to convert it)
```
Private _Autosize As Boolean
Public Sub New()
_Autosize=False
End Sub
Public Overrides Property AutoSize() As Boolean
Get
Return MyBase.AutoSize
End Get
Set(ByVal Value As Boolean)
If _Autosize <> Value And _Autosize = False Then
MyBase.AutoSize = False
_Autosize = Value
Else
MyBase.AutoSize = Value
End If
End Set
End Property
```
|
C#.NET Winforms: Is it possible to override Label.Autosize?
|
[
"",
"c#",
"winforms",
""
] |
I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.
|
Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.
non-idiomatic python using a loop with append:
```
mylist = [1, 2, 3, 4]
newlist = []
for i in mylist:
newlist.append(i * 2)
```
idiomatic python using a list comprehension:
```
mylist = [1, 2, 3, 4]
newlist = [(i * 2) for i in mylist]
```
|
Some examples:
**Resource management**, non idiomatic:
```
string content;
StreamReader sr = null;
try {
File.OpenText(path);
content = sr.ReadToEnd();
}
finally {
if (sr != null) {
sr.Close();
}
}
```
Idiomatic:
```
string content;
using (StreamReader sr = File.OpenText(path)) {
content = sr.ReadToEnd();
}
```
**Iteration**, non idiomatic:
```
for (int i=0;i<list.Count; i++) {
DoSomething(list[i]);
}
```
Also non-idiomatic:
```
IEnumerator e = list.GetEnumerator();
do {
DoSomenthing(e.Current);
} while (e.MoveNext());
```
Idiomatic:
```
foreach (Item item in list) {
DoSomething(item);
}
```
**Filtering**, non-idiomatic:
```
List<int> list2 = new List<int>();
for (int num in list1) {
if (num>100) list2.Add(num);
}
```
idiomatic:
```
var list2 = list1.Where(num=>num>100);
```
|
What is idiomatic code?
|
[
"",
"c#",
"idioms",
""
] |
I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?
|
There are two rules I follow:
* Accept the most basic type that will work
* Return the richest type your user will need
So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.
On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.
|
Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.
Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:
```
public interface IMyApi
{
IList<int> GetReadOnlyValues();
}
public class MyApiImplementation : IMyApi
{
public IList<int> GetReadOnlyValues()
{
List<int> myList = new List<int>();
... populate list
return myList.AsReadOnly();
}
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
public IList<int> GetReadOnlyValues()
{
IList<int> testValues = new int[] { 1, 2, 3 };
return testValues;
}
}
```
|
When to use IList and when to use List
|
[
"",
"c#",
".net",
""
] |
I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept.
Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me to an idiots guide tutorial?
|
I have been in your shoes, but I saw the light after I read this book (a few times!) <http://www.apress.com/book/view/9781590599099> After I read this, I really "got" it and I haven't looked back. You'll get it on Amazon.
I hope you persist, get it, and love it. When it comes together, it will make you smile.
Composition beats inheritence.
|
Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast.
(All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP)
So you define a template for how you'd represent a breakfast. This is a class:
```
class Breakfast {
}
```
Breakfasts contain attributes. In normal non-object-oriented stuff, you might use an array for this:
```
$breakfast = array(
'toast_slices' => 2,
'eggs' => 2,
'egg_type' => 'fried',
'beans' => 'Hell yeah',
'bacon_rashers' => 3
);
```
And you'd have various functions for fiddling with it:
```
function does_user_want_beans($breakfast){
if (isset($breakfast['beans']) && $breakfast['beans'] != 'Hell no'){
return true;
}
return false;
}
```
And you've got a mess, and not just because of the beans. You've got a data structure that programmers can screw with at will, an ever-expanding collection of functions to do with the breakfast entirely divorced from the definition of the data. So instead, you might do this:
```
class Breakfast {
var $toast_slices = 2;
var $eggs = 2;
var $egg_type = 'fried';
var $beans = 'Hell yeah';
var $bacon_rashers = 3;
function wants_beans(){
if (isset($this->beans) && $this->beans != 'Hell no'){
return true;
}
return true;
}
function moar_magic_pig($amount = 1){
$this->bacon += $amount;
}
function cook(){
breakfast_cook($this);
}
}
```
And then manipulating the program's idea of Breakfast becomes a lot cleaner:
```
$users = fetch_list_of_users();
foreach ($users as $user){
// So this creates an instance of the Breakfast template we defined above
$breakfast = new Breakfast();
if ($user->likesBacon){
$breakfast->moar_magic_pig(4);
}
// If you find a PECL module that does this, Email me.
$breakfast->cook();
}
```
I think this looks cleaner, and a far neater way of representing blobs of data we want to treat as a consistent object.
There are better explanations of what OO actually is, and why it's academically better, but this is my practical reason, and it contains bacon.
|
OO and how it works in PHP
|
[
"",
"php",
"oop",
""
] |
Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.
|
UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP.
|
First of all, the "IP checksum" referenced above is only an IP header checksum. It does not protect the payload. See RFC 791
Secondly, UDP allows transport with NO checksum, which means that the 16-bit checksum is set to 0 (ie, none). See RFC 768. (An all zero transmitted checksum value means that the transmitter generated no checksum)
Thirdly, as others have mentioned, UDP has a 16-bit checkSUM, which is not the best way to detect a multi-bit error, but is not bad. It is certainly possible for an undetected error to sneak in, but very unlikely.
|
Can UDP data be delivered corrupted?
|
[
"",
"c++",
"networking",
"udp",
""
] |
What is a good way to render data produced by a Java process in the browser?
I've made extensive use of JSP and the various associated frameworks ([JSTL](http://java.sun.com/products/jsp/jstl/), [Struts](http://struts.apache.org/), [Tapestry](http://tapestry.apache.org/), etc), as well as more comprehensive frameworks not related to JSP ([GWT](http://code.google.com/webtoolkit/), [OpenLaszlo](http://www.openlaszlo.org/)). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems.
Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here.
|
I personally use [Tapestry 5](http://tapestry.apache.org/tapestry5/) for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS ([java.net project](https://jsr311.dev.java.net/), [jsr311](http://jcp.org/en/jsr/detail?id=311)) it is pretty simple to use, it supports marshalling and unmarshalling objects to/from XML out of the box. It is possible to extend it to support JSON via [Jettison](http://jettison.codehaus.org/).
There are two implementations that I have tried:
* [Jersey](http://jersey.java.net/) - the reference implementation for JAX-RS.
* [Resteasy](http://www.jboss.org/resteasy/) - the implementation I prefer, good support for marshalling and unmarshalling a wide-range of formats. Also pretty stable and has more features that Jersey.
Take a look at the following code to get a feeling for what JAX-RS can do for you:
```
@Path("/")
class TestClass {
@GET
@Path("text")
@Produces("text/plain")
String getText() {
return "String value";
}
}
```
This tiny class will expose itself at the root of the server (@Path on the class), then expose the getText() method at the URI /text and allow access to it via HTTP GET. The @Produces annotation tells the JAX-RS framework to attempt to turn the result of the method into plain text.
The easiest way to learn about what is possible with JAX-RS is to read the [specification](http://jcp.org/en/jsr/detail?id=311).
|
We're using [Stripes](http://www.stripesframework.org/). It gives you more structure than straight servlets, but it lets you control your urls through a @UrlBinding annotation. We use it to stream xml and json back to the browser for ajax stuff.
You could easily consume it with another technology if you wanted to go that route, but you may actually enjoy developing with stripes.
|
Web Scripting for Java
|
[
"",
"java",
"jsp",
"scripting",
""
] |
I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)...
```
UPDATE MyTable
SET MyVal1 = @val1,
MyVal2 = @val2
WHERE @id = @id
```
...it would cycle through the querystring keys thusly:
```
For Each Key As String In Request.QueryString.Keys
Command.Parameters.AddWithValue("@" & Key, Request.QueryString(Key))
Next
```
HOWEVER, I'm now running into a situation where, under certain circumstances, some of these variables may not be present in the querystring. If I don't pass along val2 in the querystring, I get an error: `System.Data.SqlClient.SqlException: Must declare the scalar value "@val2"`.
Attempts to detect the missing value in the SQL statement...
```
IF @val2 IS NOT NULL
UPDATE MyTable
SET MyVal1 = @val1,
MyVal2 = @val2
WHERE @id = @id
```
... have failed.
What's the best way to attack this? Must I parse the SQL block with RegEx, scanning for variable names not present in the querystring? Or, is there a more elegant way to approach?
UPDATE: Detecting null values in the VB codebehind defeats the purpose of decoupling the code from its context. I'd rather not litter my function with conditions for every conceivable variable that might be passed, or not passed.
|
After struggling to find a simpler solution, I gave up and wrote a routine to parse my SQL query for variable names:
```
Dim FieldRegEx As New Regex("@([A-Z_]+)", RegexOptions.IgnoreCase)
Dim Fields As Match = FieldRegEx.Match(Query)
Dim Processed As New ArrayList
While Fields.Success
Dim Key As String = Fields.Groups(1).Value
Dim Val As Object = Request.QueryString(Key)
If Val = "" Then Val = DBNull.Value
If Not Processed.Contains(Key) Then
Command.Parameters.AddWithValue("@" & Key, Val)
Processed.Add(Key)
End If
Fields = Fields.NextMatch()
End While
```
It's a bit of a hack, but it allows me to keep my code blissfully ignorant of the context of my SQL query.
|
First of all, I would suggest against adding all entries on the querystring as parameter names, I'm not sure this is unsafe, but I wouldn't take that chance.
The problem is you're calling
```
Command.Parameters.AddWithValue("@val2", null)
```
Instead of this you should be calling:
```
If MyValue Is Nothing Then
Command.Parameters.AddWithValue("@val2", DBNull.Value)
Else
Command.Parameters.AddWithValue("@val2", MyValue)
End If
```
|
Handling empty values with ADO.NET and AddWithValue()
|
[
"",
"sql",
"vb.net",
"ado.net",
""
] |
I'm working on a game (C#) that uses a [Robocode-like](http://robocode.sourceforge.net/) programming model: participants inherit a base Class and add strategic behaviors. The game then loads instances of participants' Classes and the competition begins. Unfortunately, participants can "cheat" by sharing static variables between instances of their competitor Class.
How do I prevent static variable sharing between Class instances in a .NET language? I know this is accomplished in Java by using a separate ClassLoader per instance. What's the .NET equivalent?
Further, my testing shows that separate AppDomains only work when loading a Class that extends MarshalByRefObject. I guess this makes sense - if you simply load a Serializable Class, the Class is copied into the current AppDomain so a second object from a different AppDomain will share its static vars. MarshalByRefObject guarantees that only a proxy is loaded into the current AppDomain and the statics stay behind in the loading AppDomain. See also: <http://blogs.msdn.com/ericlippert/archive/2004/05/27/143203.aspx>
|
Load each competitor into a different AppDomain.
|
static variables are per-AppDomain, so you could look into using different AppDomains, but I totally don't know what other consequences that may have.
Otherwise you could check the classes beforehand using reflection, and reject any classes that have static members.
|
How do I prevent static variable sharing in the .NET runtime?
|
[
"",
"c#",
".net",
"multithreading",
""
] |
Since the WMI class Win32\_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system.
```
private Boolean is64BitOperatingSystem()
{
RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE");
if (processorArchitecture.Equals("x86")) {
return false;
}
else {
return true;
}
}
```
It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method?
**Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
|
Take a look at Raymond Chens solution:
[How to detect programmatically whether you are running on 64-bit Windows](http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx)
and here's the PINVOKE for .NET:
[IsWow64Process (kernel32)](http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y)
**Update:** I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Ask yourself the questions, 1 - is the registry entry concerned properly documented by MS, 2 - If it is do they provide a definitive list of possible values that is guaranteed to permit you as a developer to make the informed decision between whether you are running 32 bit or 64 bit. If the answer is no, then call the API's, yeah it's a but more long winded but it is documented and definitive.
|
> The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size.
I believe the value of IntPtr.Size is 4 for a 32bit app that's running under WOW, isn't it?
**Edit**: @Edit: Yeah. :)
|
Is this a good way to determine OS Architecture?
|
[
"",
"c#",
"windows",
"registry",
""
] |
I'm designing this collection of classes and abstract (MustInherit) classes…

This is the database table where I'm going to store all this…

As far as the Microsoft SQL Server database knows, those are all nullable ("Allow Nulls") columns.
But really, that depends on the class stored there: LinkNode, HtmlPageNode, or CodePageNode.
Rules might look like this...

How do I enforce such data integrity rules within my database?
---
UPDATE: Regarding this single-table design...
I'm still trying to zero in on a final architecture.
I initially started with many small tables with almost zero nullalbe fields.
[Which is the best database schema for my navigation?](https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation)
And I learned about the LINQ to SQL IsDiscriminator property.
[What’s the best way to handle one-to-one relationships in SQL?](https://stackoverflow.com/questions/57152/whats-the-best-way-to-handle-one-to-one-relationships-in-sql)
But then I learned that LINQ to SQL only supports single table inheritance.
[Can a LINQ to SQL IsDiscriminator column NOT inherit?](https://stackoverflow.com/questions/67659/can-a-linq-to-sql-isdiscriminator-column-not-inherit)
Now I'm trying to handle it with a collection of classes and abstract classes.
[Please help me with my .NET abstract classes.](https://stackoverflow.com/questions/84263/please-help-me-with-my-net-abstract-classes)
|
Use CHECK constraints on the table. These allow you to use any kind of boolean logic (including on other values in the table) to allow/reject the data.
From the [Books Online](http://msdn.microsoft.com/en-us/library/ms188258.aspx) site:
> You can create a CHECK constraint with
> any logical (Boolean) expression that
> returns TRUE or FALSE based on the
> logical operators. For the previous
> example, the logical expression is:
> salary >= 15000 AND salary <= 100000.
|
Have a unique table for each type of node.
Why not just make the class you're building enforce the data integrity for its own type?
---
**EDIT**
In that case, you can either a) use logical constraints (see below) or b) stored procedures to do inserts/edits (a good idea regardless) or c) again, just make the class enforce data integrity.
A mixture of C & B would be the course of events I take. I would have unique stored procedures for add/edits for each node type (i.e. Insert\_Update\_NodeType) as well as make the class perform data validation before saving data.
|
How do I enforce data integrity rules in my database?
|
[
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:
1. Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.
2. If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.
Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?
The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.
|
```
Process.Start(@"C:\Program Files\Microsoft Office\Officexx\excel.exe", "yourfile.xml");
```
That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.
|
If you insert the following into the 2nd line of your XML it directs Windows to open with Excel
```
<?mso-application progid="Excel.Sheet"?>
```
|
XML to Excel (2007) Ideas using Windows XP, and C#.Net
|
[
"",
"c#",
".net",
"xml",
"excel",
""
] |
In a C# windows forms application. I have a splash screen with some multi-threaded processes happening in the background. What I would like to do is when I display the splash screen initially, I would like to have it appear to "fade in". And then, once all the processes finish, I would like it to appear as though the splash screen is "fading out". I'm using C# and .NET 2.0. Thanks.
|
You could use a timer to modify the [Form.Opacity level](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity(VS.80).aspx).
|
When using Opacity property have to remember that its of type double, where 1.0 is complete opacity, and 0.0 is completely transparency.
```
private void fadeTimer_Tick(object sender, EventArgs e)
{
this.Opacity -= 0.01;
if (this.Opacity <= 0)
{
this.Close();
}
}
```
|
Fade splash screen in and out
|
[
"",
"c#",
"winforms",
".net-2.0",
"splash-screen",
""
] |
For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:
```
private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
```
This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:
```
[DesignerCategory("Custom")]
```
But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...
### Update:
@John said:
> DesignerCatogy is used to say if the
> class is a form, component etc.
>
> Try this:
>
> [Category("Custom")]
Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.
In .NETCF all I seem to have available from System.ComponentModel is:
```
DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
```
The only one it doesn't scream at is EditorBrowsable
|
Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it:
<http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx>
Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig!
Scroll down about half way for the good stuff ;)
|
`DesignerCategory` is used to say if the class is a form, component etc.
For full windows the attribute you want is:
```
[System.ComponentModel.Category("Custom")]
```
and for the description you can use `[System.ComponentModel.Description("This is the description")]`
To use both together:
```
[System.ComponentModel.Category("Custom"),System.ComponentModel.Description("This is the description")]
```
However this is part of `system.dll` which may be different for windows mobile.
|
User Control Property Designer Properties
|
[
"",
"c#",
"user-controls",
"windows-mobile",
""
] |
I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
|
I usually use `Request.Url.ToString()` to get the full url (including querystring), no concatenation required.
|
Here is a list I normally refer to for this type of information:
```
Request.ApplicationPath : /virtual_dir
Request.CurrentExecutionFilePath : /virtual_dir/webapp/page.aspx
Request.FilePath : /virtual_dir/webapp/page.aspx
Request.Path : /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath : /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host : localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port : 80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme : http
Request.Url.Segments : /
virtual_dir/
webapp/
page.aspx
```
Hopefully you will find this useful!
|
How do I get the full url of the page I am on in C#
|
[
"",
"c#",
"asp.net",
"user-controls",
""
] |
I've tried to do this several times with no luck. After reading [this post](https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477), it made me interested in doing this again. So can anyone tell me why the following doesn't work?
```
<?php
$guest = 1;
$editor = 2;
$admin = 4;
$user = $editor;
if( $user == ($editor | $admin) ) {
echo "Test";
}
?>
```
|
Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this:
```
<?php
$guest = 1;
$editor = 2;
$admin = 4;
$user = $editor;
if( $user & ($editor | $admin) ) {
echo "Test";
}
?>
```
If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better.
|
In the interest of not reinventing the wheel, why not take a look at ACL/Authentication systems like [Zend ACL](http://framework.zend.com/manual/en/zend.acl.html) and [Zend Auth](http://framework.zend.com/manual/en/zend.auth.html)? Both can be used independently from the Zend Framework as a whole. Access Control is a tricky situation so it benefits one to at least look at how other systems do it.
|
Implementing permissions in PHP
|
[
"",
"php",
"permissions",
""
] |
Does anyone know if it is possible to detect whether the browser has closed the connection during the execution of a long `PHP` script, when using `apache` and `mod_php`?
For example, in `Java`, the `HttpOutputStream` will throw an `exception` if one attempts to write to it after the browser has closed it -- Or will respond negatively to `checkError()`.
|
Use [connection\_aborted()](https://www.php.net/manual/en/function.connection-aborted.php)
|
In at least PHP4, connection\_aborted and connection\_status only worked after the script sent any output to the browser (using: flush() | ob\_flush()).
Also don't expect accurately timed results.
It's mostly useful to check if there is still someone waiting on the other side.
|
Detect browser connection closed in PHP
|
[
"",
"php",
"apache",
"http",
"mod-php",
""
] |
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.
Is there a way to tell the runtime that the dlls are in a seperate subfolder?
|
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.
```
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
```
Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.
EDIT:
Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
|
You can use the `<probing>` element in a manifest file to tell the Runtime to look in different directories for its assembly files.
<http://msdn.microsoft.com/en-us/library/823z9h8w.aspx>
e.g.:
```
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin;bin2\subbin;bin3"/>
</assemblyBinding>
</runtime>
</configuration>
```
|
Loading assemblies and its dependencies
|
[
"",
"c#",
".net",
""
] |
How do I turn the following 2 queries into 1 query
```
$sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;";
$result = $db->sql_query($sql);
$level = (int) $db->sql_fetchfield('level');
$db->sql_freeresult($result);
++$level;
$sql = "UPDATE skills SET level = $level WHERE id = $id;";
$result = $db->sql_query($sql);
$db->sql_freeresult($result);
```
I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query.
Edit: `$id` has already been forced to be an integer, thus no escaping is needed this time.
|
I get downmodded for this?
```
$sql = "UPDATE skills SET level = level+1 WHERE id = $id";
$result = $db->sql_query($sql);
$db->sql_freeresult($result);
```
In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL.
In the general case, you should not use NULL to represent zero. Incrementing NULL *should* give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use
```
$sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id";
```
...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include
```
level INT DEFAULT '0' NOT NULL
```
in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.
|
This way:
```
UPDATE skills
SET level = level + 1
WHERE id = $id
```
|
Add 1 to a field
|
[
"",
"php",
"mysql",
""
] |
I know almost nothing about linq.
I'm doing this:
```
var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
```
Which gets me all the running processes which match that criteria.
But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this
```
var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
```
which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?
**UPDATE**
I'm actually trying to find the first matching item, and call `SetForegroundWindow` on it
I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?
```
var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
```
|
@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:
```
var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);
if (app == null)
return;
SetForegroundWindow(app.MainWindowHandle);
```
|
Do *not* use `Count()` like ICR says. `Count()` will iterate through the `IEnumerable` to figure out how many items it has. In this case the performance penalty may be negligible since there aren't many processes, but it's a bad habit to get into. Only use `Count()` when your query is only interested in the *number of results.* `Count` is almost never a good idea.
There are several problems with FryHard's answer. First, because of [delayed execution](http://devlicio.us/blogs/derik_whittaker/archive/2008/04/07/linq-and-delayed-execution.aspx "Derik Whittaker on LINQ's Delayed Execution"), you will end up executing the LINQ query twice, once to get the number of results, and once to get the `FirstOrDefault`. Second, there is no reason whatsoever to use `FirstOrDefault` after checking the count. Since it can return null, you should never use it without checking for null. Either do `apps.First().MainWindowHandle` or:
```
var app = apps.FirstOrDefault();
if (app != null)
SetForegroundWindow(app.MainWindowHandle);
```
This is why the best solution is Mark's, without question. It's the most efficient and stable way of using LINQ to get what you want.
|
Linq to objects - select first object
|
[
"",
"c#",
"linq",
"linq-to-objects",
""
] |
Does [Facelets](https://facelets.dev.java.net/) have any features for neater or more readable internationalised user interface text labels that what you can otherwise do using JSF?
For example, with plain JSF, using h:outputFormat is a very verbose way to interpolate variables in messages.
*Clarification:* I know that I can add a message file entry that looks like:
```
label.widget.count = You have a total of {0} widgets.
```
and display this (if I'm using Seam) with:
```
<h:outputFormat value="#{messages['label.widget.count']}">
<f:param value="#{widgetCount}"/>
</h:outputFormat>
```
but that's a lot of clutter to output one sentence - just the sort of thing that gives JSF a bad name.
|
You could create your own faces tag library to make it less verbose, something like:
```
<ph:i18n key="label.widget.count" p0="#{widgetCount}"/>
```
Then create the taglib in your view dir: /components/ph.taglib.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "https://facelets.dev.java.net/source/browse/*checkout*/facelets/src/etc/facelet-taglib_1_0.dtd">
<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
<namespace>http://peterhilton.com/core</namespace>
<tag>
<tag-name>i18n</tag-name>
<source>i18n.xhtml</source>
</tag>
</facelet-taglib>
```
create /components/i18n.xhtml
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:outputFormat value="#{messages[key]}">
<!-- crude but it works -->
<f:param value="#{p0}" />
<f:param value="#{p1}" />
<f:param value="#{p2}" />
<f:param value="#{p3}" />
</h:outputFormat>
</ui:composition>
```
You can probably find an elegant way of passing the arguments with a little research.
Now register your new taglib in web.xml
```
<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>
/components/ph.taglib.xml
</param-value>
</context-param>
```
Just add `xmlns:ph="http://peterhilton.com/core"` to your views and you're all set!
|
Since you're using Seam, [you can use EL](http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e13037) in the messages file.
Property:
```
label.widget.count = You have a total of #{widgetCount} widgets.
```
XHTML:
```
<h:outputFormat value="#{messages['label.widget.count']}" />
```
This still uses outputFormat, but is less verbose.
|
Internationalised labels in JSF/Facelets
|
[
"",
"java",
"jsf",
"internationalization",
"facelets",
""
] |
Using a configuration file I want to enable myself to turn on and off things like (third party) logging and using a cache in a C# website. The solution should not be restricted to logging and caching in particular but more general, so I can use it for other things as well.
I have a configuration xml file in which I can assert that logging and caching should be turned on or off (it could also be in the Web.Config, that's not the point right now) which will result in for example a `bool logging` and a `bool caching` that are `true` or `false`.
The question is about this part:
**What I can do is prepend every logging/caching related statement with `if (logging)` and `if (caching)`.
What is better way of programming this? Is there also a programming term for this kind of problem? Maybe attributes are also a way to go?**
|
I'm curious what kind of logging/caching statements you have? If you have some class that is doing WriteLog or StoreCahce or whatever... why not just put the if(logging) in the WriteLog method. It seems like if you put all of your logging caching related methods into once class and that class knew whether logging/caching was on, then you could save your self a bunch of If statements at each instance.
|
Why not just use the web.config and the System.Configuration functionality that already exists?
Your web app is going to parse web.config on every page load anyway, so the overhead involved in having yet another XML config file seems overkill when you can just define your own section on the existing configuration.
|
How to conditionally enable actions in C# ASP.NET website
|
[
"",
"c#",
""
] |
Does anyone know of any 'standard' way to interface with a telephony system (think Cisco CCM) from a C/C++ app in \*nix? I have used MS TAPI in the past but this is Windows only and don't want to go the jTAPI (Java) route, which seems to be the only option on the face of it.
I want to monitor the phone system for logging purposes (so I know when users have made calls, received calls, etc.). TAPI is good at this sort of thing but I can't be the first person who wants to do something similar without having a Windows server.
Note that I need to integrate with existing PABX systems - notably Cisco CCM and Nortel BCM.
|
I have experience with two telephony standards TAPI, and CSTA, as far as I know there is no such agreement between vendors (e.g. Cisco, Nortel, NEC) regarding THE standard API.
I would recommend looking at the availability of [SMDR](http://en.wikipedia.org/wiki/Call_detail_record) (Station Messaging Detail Recording) on the PBX platforms you are targeting, assuming that no call/device control is required. This will allow you to access the PBX activity as a text stream and you can parse the data for further manipulations to suit your purpose.
Most likely the format between the PBX vendors will be different but hopefully this could be abstracted away so that the core application functionality is re-usable.
This is likely to be a more portable option, again assuming no call/device control is required, as you are not relying on the vendor providing CTI connectivity on your platform of choice.
|
Here's another vote for SMDR. The telephony systems I've seen all offer the option of SMDR logging through a serial port on the phone box. Just capture the text from the serial port and parse it as needed.
I wrote a server process that captures the SMDR output, parses it and saves the result in a database that our other applications can use to see the extension, phone number, time and length of each phone call.
|
Interfacing with telephony systems from *nix
|
[
"",
"c++",
"unix",
"cisco",
"tapi",
""
] |
I'm regularly running into similar situations :
I have a bunch of COM .DLLs (no IDL files) which I need to use and invoke to be able to access some foreign (non-open, non-documented) data format.
Microsoft's Visual Studio platform has very nice capabilities to import such COM DLLs and use them in my project (Visual C++'s #import directive, or picking and adding them using Visual Basic .NET's dialogs) - and that's the vendors recommended way to use them.
I would be interested into finding a way to use those DLLs on non-microsoft development platforms. Namely, using these COM classes in C++ project compiled with MinGW or Cygwin, or even Wine's GCC port to linux (compiles C++ targeting Win32 into binary running natively on Linux).
I have got some limited success using [this](http://www.codeproject.com/KB/COM/comdispatchdriver.aspx) driver, but this isn't successful in 100% of situations (I can't use COM objects returned by some methods).
Has someone had success in similar situations ?
|
Answering myself but I managed to find the **perfect** library for OLE/COM calling in non-Microsoft compilers : [disphelper](http://disphelper.sourceforge.net/).
(it's available from [sourceforge.net](http://sourceforge.net/projects/disphelper/) under a permissive BSD license).
It works both in C and C++ (and thus any other language with C bindings as well). It uses a printf/scanf-like [format string syntax](http://disphelper.sourceforge.net/readme.htm).
(You pass whatever you want as long as you specify it in the format string, unlike [XYDispDriver](http://www.codeproject.com/KB/COM/comdispatchdriver.aspx) which requires the arguments to exactly match whatever is specified in the type library).
I modified it a little bit to get it also compile under Linux with WineGCC (to produce native Linux elf out of Win32 code), and to handle "by ref" calls automatically (stock disthelper requires the programmer to setup his/her own VARIANT).
My patched version and patches are available as a fork on github:
* <https://github.com/DrYak/disphelper>
And here are my patches :
* [patch for single source](https://gist.github.com/DrYak/81f73fff0d572130ff9d)
* [patch for split source](https://gist.github.com/DrYak/532c10720065d18e27bd)
|
The problem with the Ole/Com Object Viewer packaged with Visual Studio and Windows SDKs is that it produces a broken .IDL out of the .DLL, which can't further be compiled by MIDL into a .H/.CPP pair.
Wine's own reimplementation of OleViewer is currently unstable and crashes when trying to use those libraries.
|
Using Component Object Model (COM) on non-Microsoft platforms
|
[
"",
"c++",
"com",
"cygwin",
"mingw",
"wine",
""
] |
* Do you need to use some kind of provider?
* Can you setup your own SMS server?
* Does any open source solutions exist?
I am an SMS newbie so any insight on how this is accomplished would be great. I am partial to Java but any language is fine.
|
This is easy. Yes, you need a "sms gateway" provider. There are a lot out there. These companies provide APIs for you to send/receive SMS.
e.g. the German company [Mobilant](http://mobilant.de/) provides an easy API. If you want to receive a SMS just program a simple PHP / JSP / s.th.else dynamic web page and let Mobilant call it.
e.g.
* Mobilant receives a SMS for you
* Mobilant calls your web page <http://yourpage.com/receive.php?message=>...
* You do what you need to do
You really don't want to setup your own SMS Server or Center ;-) This is really expensive, takes months to setup and costs some nice ferraris.
Use a provider and pay per SMS. It's the cheapest and fastest way.
|
I used kannel on a linux box with an old mobile phone connected via a serial cable to the box. Got a pre-paid card in the phone as I was using it for private use only. Worked like a charm!
|
What can you use to get an application to be able to receive SMS message?
|
[
"",
"java",
"sms",
""
] |
How to restrict the maximum number of characters that can be entered into an HTML `<textarea>`? I'm looking for a cross-browser solution.
|
The `TEXTAREA` tag does not have a `MAXLENGTH` attribute the way that an
`INPUT` tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be *typed* into a `TEXTAREA` tag is:
```
<textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
```
**Note:** `onKeyPress`, is going to prevent any button press, **any button** *including* the backspace key.
This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, `false` if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the `KeyPress` action is cancelled, and the character is not added.
One fly in the ointment is the possibility of pasting into a `TEXTAREA`,
which does not cause the `KeyPress` event to fire, circumventing this check.
Internet Explorer 5+ contains an `onPaste` event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.[1](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html) Thus:
```
<textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
```
Again, the `onPaste` event and `clipboardData` object are IE 5+ only. For a cross-browser solution, you will just have to use an `OnChange` or `OnBlur` handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.
[Source](http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html)
Also, there is another way here, including a finished script you could include in your page:
<http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html>
|
HTML5 now allows [`maxlength` attribute on `<textarea>`](https://developer.mozilla.org/en/docs/Web/HTML/Element/textarea#attr-maxlength).
It is supported by all browsers except IE <= 9 and iOS Safari 8.4. See [support table on caniuse.com](http://caniuse.com/#feat=maxlength).
|
Max length for HTML <textarea>
|
[
"",
"javascript",
"html",
"cross-browser",
"textarea",
""
] |
I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:
```
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
```
If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).
The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?
**EDIT:** See my answer below for the contents of the batch file.
* The output.txt never gets created.
I added these lines:
```
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
```
and stepped through them in debug mode. The code hangs on the `ReadLine()`. I'm stumped!
|
I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:
<http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx>
That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.
|
Why not just do all the work in C# instead of using batch files?
I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths.
```
using System;
using System.IO;
using System.Text;
using System.Security;
using System.Diagnostics;
namespace asdf
{
class StackoverflowQuestion
{
private const string MSBUILD = @"path\to\msbuild.exe";
private const string BMAIL = @"path\to\bmail.exe";
private const string WORKING_DIR = @"path\to\working_directory";
private string stdout;
private Process p;
public void DoWork()
{
// build project
StartProcess(MSBUILD, "myproject.csproj /t:Build", true);
}
public void StartProcess(string file, string args, bool redirectStdout)
{
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = WORKING_DIR;
psi.FileName = file;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = redirectStdout;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
if (redirectStdout)
{
stdout = p.StandardOutput.ReadToEnd();
}
}
void p_Exited(object sender, EventArgs e)
{
if (p.ExitCode != 0)
{
// failed
StringBuilder args = new StringBuilder();
args.Append("-s k2smtpout.secureserver.net ");
args.Append("-f build@example.com ");
args.Append("-t josh@example.com ");
args.Append("-a \"Build failed.\" ");
args.AppendFormat("-m {0} -h", stdout);
// send email
StartProcess(BMAIL, args.ToString(), false);
}
}
}
}
```
|
C#.Net: Why is my Process.Start() hanging?
|
[
"",
"c#",
".net",
""
] |
Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests.
Server Side, you still kept all the individual .js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc.
In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please?
|
It's called [Script Combining](http://msdn.microsoft.com/en-us/library/cc837190.aspx). There is a video example from asp.net explaining it [here](http://www.asp.net/Learn/3.5-SP1/video-296.aspx).
|
you can find [here](http://www.codeproject.com/KB/aspnet/HttpCombine.aspx) an usefull article for it
|
Combining and Caching multiple JavaScript files in ASP.net
|
[
"",
"asp.net",
"javascript",
""
] |
I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.
How should I go about doing that?
|
You can probably do this by setting your own [FileSystemView](https://docs.oracle.com/javase/8/docs/api/javax/swing/filechooser/FileSystemView.html).
|
Incase anyone else needs this in the future:
```
class DirectoryRestrictedFileSystemView extends FileSystemView
{
private final File[] rootDirectories;
DirectoryRestrictedFileSystemView(File rootDirectory)
{
this.rootDirectories = new File[] {rootDirectory};
}
DirectoryRestrictedFileSystemView(File[] rootDirectories)
{
this.rootDirectories = rootDirectories;
}
@Override
public File createNewFolder(File containingDir) throws IOException
{
throw new UnsupportedOperationException("Unable to create directory");
}
@Override
public File[] getRoots()
{
return rootDirectories;
}
@Override
public boolean isRoot(File file)
{
for (File root : rootDirectories) {
if (root.equals(file)) {
return true;
}
}
return false;
}
}
```
You'll obviously need to make a better "createNewFolder" method, but this does restrict the user to one of more directories.
And use it like this:
```
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
```
or like this:
```
FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
```
|
How do I restrict JFileChooser to a directory?
|
[
"",
"java",
"swing",
"jfilechooser",
""
] |
When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-insert them manually.
I *know* you can reorder columns fairly easily in a DataGridView, however that would result in a lot of hardcoding and I want the designer to match up to the grid.
Does anyone know of any easier way of achieving this or is cutting/pasting the only available method?
I tried manually editing the .designer.cs file, but reordering properties there doesn't appear to do anything!
**Edit:** Just to make it clear - I want to reorder what's in the LINQ to SQL designer, not what's in the table. I haven't made an error in ordering requiring a reversion to the original table layout; rather I have a table which I want to possess a different ordering in Visual Studio than in SQL Server.
|
Using Linq-to-Sql, you can have columns in the DataGridView appear different than in the original table by:
1. In your Linq query, extract the columns that you want, in the order than you want, and store them in a var. Then the autogenerate columns should show them in that order in the DataGridView
2. Use Template columns in your DataGridView
3. Do not use drag-and-drop on the Linq-to-Sql design surface to create your entities. Rather, create them by hand and associate them with the database table using table and column properties
As far as I know, there is no drag-and-drop column reorder in the designer itself
|
Open the [DataClasses].dbml file in your favorite XML editor, and reorder the [Column] elements for the table. Save, and reopen (or reload) the designer in Visual studio. The order of the columns displayed in the designer will be fixed.
|
How can you easily reorder columns in LINQ to SQL designer?
|
[
"",
"c#",
"linq",
"linq-to-sql",
""
] |
Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.
|
At the risk of sounding stupid, I don't believe SQL Server supports the delete / cascade syntax. I think you can configure a delete rule to do cascading deletes (<http://msdn.microsoft.com/en-us/library/ms152507.aspx>), but as far as I know the trick with SQL Server is to just to run your drop query once for each table you're dropping, then check it worked.
|
A diferent approach could be: first get rid of the constraints, then drop the tables in a single shot.
In other words, a DROP CONSTRAINT for every constraint, then a DROP TABLE for each table; at this point the order of execution shouldn't be an issue.
|
Dropping a group of tables in SQL Server
|
[
"",
"sql",
"sql-server",
"database",
""
] |
How is your javaScript code organized? Does it follow patterns like MVC, or something else?
I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with [jQuery](http://jquery.com), however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":
* The 'model' is a JSON tree that gets extended with helpers
* The view is the DOM plus classes that tweak it
* The controller is the object where I connect events handling and kick off view or model manipulation
I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"
Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
|
..but Javascript has many facets that **are** OO.
Consider this:
```
var Vehicle = jQuery.Class.create({
init: function(name) { this.name = name; }
});
var Car = Vehicle.extend({
fillGas: function(){
this.gas = 100;
}
});
```
I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).
This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.
|
JavaScriptMVC is a great choice for organizing and developing a large scale JS application.
The architecture design very well thought out. There are 4 things you will ever do with JavaScript:
1. Respond to an event
2. Request Data / Manipulate Services (Ajax)
3. Add domain specific information to the ajax response.
4. Update the DOM
JMVC splits these into the Model, View, Controller pattern.
First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.
```
$.Controller.extend('TodosController',{
'click' : function(el, ev){ ... },
'.delete mouseover': function(el, ev){ ...}
'.drag draginit' : function(el, ev, drag){ ...}
})
```
Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:
Todo.findAll({after: new Date()}, myCallbackFunction);
Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view.
```
'.show click' : function(el, ev){
Todo.findAll({after: new Date()}, this.callback('list'));
},
list : function(todos){
$('#todos').html( this.view(todos));
}
```
In 'views/todos/list.ejs'
```
<% for(var i =0; i < this.length; i++){ %>
<label><%= this[i].description %></label>
<%}%>
```
JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:
* Code generators
* Integrated Browser, Selenium, and Rhino Testing
* Documentation
* Script compression
* Error reporting
|
Alternative "architectural" approaches to javaScript client code?
|
[
"",
"javascript",
"model-view-controller",
"architecture",
"client",
"ria",
""
] |
Anybody have a good example how to deep clone a WPF object, preserving databindings?
---
The marked answer is the first part.
The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:
<http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571>
|
The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader.
ex:
Write the object to xaml (let's say the object was a Grid control):
```
string gridXaml = XamlWriter.Save(myGrid);
```
Load it into a new object:
```
StringReader stringReader = new StringReader(gridXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
Grid newGrid = (Grid)XamlReader.Load(xmlReader);
```
|
In .NET 4.0, the new xaml serialization stack makes this MUCH easier.
```
var sb = new StringBuilder();
var writer = XmlWriter.Create(sb, new XmlWriterSettings
{
Indent = true,
ConformanceLevel = ConformanceLevel.Fragment,
OmitXmlDeclaration = true,
NamespaceHandling = NamespaceHandling.OmitDuplicates,
});
var mgr = new XamlDesignerSerializationManager(writer);
// HERE BE MAGIC!!!
mgr.XamlWriterMode = XamlWriterMode.Expression;
// THERE WERE MAGIC!!!
System.Windows.Markup.XamlWriter.Save(this, mgr);
return sb.ToString();
```
|
How can you clone a WPF object?
|
[
"",
"c#",
"wpf",
"binding",
"clone",
""
] |
So, I am seeing a curious problem. If I have a function
```
// counter wraps around to beginning eventually, omitted for clarity.
var counter;
cycleCharts(chartId) {
// chartId should be undefined when called from setInterval
console.log('chartId: ' + chartId);
if(typeof chartId == 'undefined' || chartId < 0) {
next = counter++;
}
else {
next = chartId;
}
// ... do stuff to display the next chart
}
```
This function can be called explicitly by user action, in which case `chartId` is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a `setInterval` which is initialized by the following:
```
var cycleId = setInterval(cycleCharts, 10000);
```
The odd thing is, I'm actually seeing the `cycleCharts()` get a `chartId` argument even when it's called from `setInterval`! The `setInterval` doesn't even have any parameters to pass along to the `cycleCharts` function, so I'm very baffled as to why `chartId` is not undefined when `cycleCharts` is called from the `setInterval`.
|
setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation )
you want
```
var cycleId = setInterval(function(){ cycleCharts(); }, 10000);
```
( this behavior may not be standardized, so don't rely on it too heavily )
|
It tells you how many milliseconds late the callback is called.
|
Why is setInterval calling a function with random arguments?
|
[
"",
"javascript",
"firefox",
""
] |
I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.
|
I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a **[LookupOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/LookupOp.html).** Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage.
Using Nicks example from above heres how I would do it.
> Let Y = 0.3\*R + 0.59\*G + 0.11\*B for
> each pixel
>
> (R1,G1,B1) is what you are colorizing
> with
```
protected LookupOp createColorizeOp(short R1, short G1, short B1) {
short[] alpha = new short[256];
short[] red = new short[256];
short[] green = new short[256];
short[] blue = new short[256];
int Y = 0.3*R + 0.59*G + 0.11*B
for (short i = 0; i < 256; i++) {
alpha[i] = i;
red[i] = (R1 + i*.3)/2;
green[i] = (G1 + i*.59)/2;
blue[i] = (B1 + i*.11)/2;
}
short[][] data = new short[][] {
red, green, blue, alpha
};
LookupTable lookupTable = new ShortLookupTable(0, data);
return new LookupOp(lookupTable, null);
}
```
It creates a [BufferedImageOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImageOp.html) that will mask out each color if the mask boolean is true.
Its simple to call too.
```
BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);
BufferedImage targetImage = colorizeFilter.filter(sourceImage, null);
```
If this is not what your looking for I suggest you look more into BufferedImageOp's.
This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.
|
Let `Y = 0.3*R + 0.59*G + 0.11*B` for each pixel in the image, then set them to be
`((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)`
if `(R1,G1,B1)` is what you are colorizing with.
|
Colorizing images in Java
|
[
"",
"java",
"colors",
"bufferedimage",
"colorize",
""
] |
I would much prefer to do this without catching an exception in `LoadXml()` and using this results as part of my logic. Any ideas for a solution that doesn't involve manually parsing the xml myself? I think VB has a return value of false for this function instead of throwing an XmlException. Xml input is provided from the user. Thanks much!
```
if (!loaded)
{
this.m_xTableStructure = new XmlDocument();
try
{
this.m_xTableStructure.LoadXml(input);
loaded = true;
}
catch
{
loaded = false;
}
}
```
|
Just catch the exception. The small overhead from catching an exception drowns compared to parsing the XML.
If you want the function (for stylistic reasons, not for performance), implement it yourself:
```
public class MyXmlDocument: XmlDocument
{
bool TryParseXml(string xml){
try{
ParseXml(xml);
return true;
}catch(XmlException e){
return false;
}
}
```
|
Using a XmlValidatingReader will prevent the exceptions, if you provide your own ValidationEventHandler.
|
How to check for valid xml in string input before calling .LoadXml()
|
[
"",
"c#",
".net",
"xml",
"exception",
""
] |
What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.
Currently I use code like this:
```
// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
match = mo;
break;
}
}
```
or
```
// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
foundIt = true;
break;
}
}
```
|
> @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber.
In C# 2.0 you'd write:
```
result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });
```
3.0 knows lambdas:
```
result = mObjList.Find(x => x.ID == magicNumber);
```
|
Using a Lambda expression:
```
List<MyObject> list = new List<MyObject>();
// populate the list with objects..
return list.Find(o => o.Id == myCriteria);
```
|
Cleanest Way to Find a Match In a List
|
[
"",
"c#",
"refactoring",
""
] |
The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked.
```
public void saveAndExit(string filename)
{
excelApplication.Save(filename);
excelApplication.Quit();
}
```
Original file opened is c:\testing\template.xls
The file name that is passed in is c:\testing\7777 (date).xls
Does anyone have an answer?
(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)
|
Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA.
```
Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0]; //or some other way of obtaining this workbook reference, as Jason Z mentioned
wbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
wbk.Close();
excelApplication.Quit();
```
Gotta love all those Type.Missings. But I think they're necessary.
|
Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method. You can pass the updated file name in there.
|
Using Interop with C#, Excel Save changing original. How to negate this?
|
[
"",
"c#",
"excel",
""
] |
So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an `std::string` to a class and assigning it a value from another `std::string`:
```
std::string hello = "Hello, world.\n";
/* exampleString = "Hello, world.\n" would work fine. */
exampleString = hello;
```
crashes on my system with a stack dump. So basically I need to **stop** and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able.
Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with `valgrind`, and while not knowing completely what I'm doing, it did report that the `std::string`'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.
(In before `rm -rf ProjectDir`, do again in C# :D)
EDIT:
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.
|
These are relatively cheap mechanisms for possibly solving the problem:
1. Keep an eye on my [heap corruption question](https://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate) - I'm updating with the answers as they shake out. The first was balancing `new[]` and `delete[]`, but you're already doing that.
2. Give [valgrind](http://valgrind.org/) more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents.
3. Think about using the [Google Performance Tools](http://code.google.com/p/google-perftools/) as a replacement malloc/new.
4. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal"
5. You're not `assert()`ing enough in your code. How do I know that without having seen it? Like flossing, no-one `assert()`s enough in their code. Add in a validation function for your objects and call that on method start and method end.
6. Are you [compiling -wall](http://gcc.gnu.org/onlinedocs/gcc-4.3.0/cpp/Invocation.html#Invocation)? If not, do so.
7. Find yourself a lint tool like [PC-Lint](http://www.gimpel.com/). A small app like yours might fit in the [PC-lint demo](http://gimpel-online.com/cgi-bin/genPage.py?srcFile=diy.cpp&cgiScript=analyseCode.py&title=Blank+Slate+(C%2B%2B)+&intro=An+empty+page+in+which+to+write+your+own+C%2B%2B+code.&compilerOption=co-gcc.lnt+co-gnu3.lnt&includeOption=%7B%7BquotedIncludeOption%7D%7D) page, meaning no purchase for you!
8. Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers.
9. Stop using arrays. Use a [vector](http://en.wikipedia.org/wiki/Vector_(STL)) instead.
10. Don't use raw pointers. Use a [smart pointer](http://en.wikipedia.org/wiki/Smart_pointer). Don't use `auto_ptr`! That thing is... surprising; its semantics are very odd. Instead, choose one of the [Boost smart pointers](http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/smart_ptr.htm), or something out of [the Loki library](http://en.wikipedia.org/wiki/Loki_(C%2B%2B)).
|
We once had a bug which eluded all of the regular techniques, valgrind, purify etc. The crash only ever happened on machines with lots of memory and only on large input data sets.
Eventually we tracked it down using debugger watch points. I'll try to describe the procedure here:
1) Find the cause of the failure. It looks from your example code, that the memory for "exampleString" is being corrupted, and so cannot be written to. Let's continue with this assumption.
2) Set a breakpoint at the last known location that "exampleString" is used or modified without any problem.
3) Add a watch point to the data member of 'exampleString'. With my version of g++, the string is stored in `_M_dataplus._M_p`. We want to know when this data member changes. The GDB technique for this is:
```
(gdb) p &exampleString._M_dataplus._M_p
$3 = (char **) 0xbfccc2d8
(gdb) watch *$3
Hardware watchpoint 1: *$3
```
I'm obviously using linux with g++ and gdb here, but I believe that memory watch points are available with most debuggers.
4) Continue until the watch point is triggered:
```
Continuing.
Hardware watchpoint 2: *$3
Old value = 0xb7ec2604 ""
New value = 0x804a014 ""
0xb7e70a1c in std::string::_M_mutate () from /usr/lib/libstdc++.so.6
(gdb) where
```
The gdb `where` command will give a back trace showing what resulted in the modification. This is either a perfectly legal modification, in which case just continue - or if you're lucky it will be the modification due to the memory corruption. In the latter case, you should now be able to review the code that is *really* causing the problem and hopefully fix it.
The cause of our bug was an array access with a negative index. The index was the result of a cast of a pointer to an 'int' modulos the size of the array. The bug was missed by valgrind et al. as the memory addresses allocated when running under those tools was never "`> MAX_INT`" and so never resulted in a negative index.
|
Of Memory Management, Heap Corruption, and C++
|
[
"",
"c++",
"memory",
"stack",
"heap-memory",
""
] |
What profilers have you used when working with .net programs, and which would you particularly recommend?
|
I have used [JetBrains dotTrace](http://www.jetbrains.com/profiler/) and [Redgate ANTS](http://www.red-gate.com/products/ants_performance_profiler/) extensively. They are fairly similar in features and price. They both offer useful performance profiling and quite basic memory profiling.
dotTrace integrates with Resharper, which is really convenient, as you can profile the performance of a unit test with one click from the IDE. However, dotTrace often seems to give spurious results (e.g. saying that a method took several years to run)
I prefer the way that ANTS presents the profiling results. It shows you the source code and to the left of each line tells you how long it took to run. dotTrace just has a tree view.
[EQATEC profiler](http://www.eqatec.com/Profiler/) is quite basic and requires you to compile special instrumented versions of your assemblies which can then be run in the EQATEC profiler. It is, however, free.
Overall I prefer ANTS for performance profiling, although if you use Resharper then the integration of dotTrace is a killer feature and means it beats ANTS in usability.
The free Microsoft CLR Profiler ([.Net framework 2.0](http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=13382) / [.Net Framework 4.0](http://www.microsoft.com/download/en/details.aspx?id=16273)) is all you need for .NET memory profiling.
**2011 Update:**
The [Scitech memory profiler](http://memprofiler.com/) has quite a basic UI but lots of useful information, including some information on unmanaged memory which dotTrace and ANTS lack - you might find it useful if you are doing COM interop, but I have yet to find any profiler that makes COM memory issues easy to diagnose - you usually have to break out `windbg.exe`.
The ANTS profiler has come on in leaps and bounds in the last few years, and its memory profiler has some truly useful features which now pushed it ahead of dotTrace as a package in my estimation. I'm lucky enough to have licenses for both, but if you are going to buy one .Net profiler for both performance and memory, make it ANTS.
|
Others have covered performance profiling, but **with regards to memory profiling**
I'm currently evaluating both the Scitech .NET Memory Profiler 3.1 and ANTS Memory Profiler 5.1 (current versions as of September 2009). I tried the JetBrains one a year or two ago and it wasn't as good as ANTS (for memory profiling) so I haven't bothered this time. From reading the web sites it looks like it doesn't have the same *memory profiling* features as the other two.
Both ANTS and the Scitech memory profiler have features that the other doesn't, so which is best will depend upon your preferences. Generally speaking, the Scitech one provides more detailed information while the ANTS one is really incredible at identifying the leaking object. Overall, I prefer the ANTS one because it is so quick at identifying possible leaks.
Here are the main the pros and cons of each from my experience:
**Common Features of ANTS and Scitech .NET Memory Profiler**
* Real-time analysis feature
* Excellent how-to videos on their web sites
* Easy to use
* Reasonably performant (obviously slower than without the profiler attached, but not so much you become frustrated)
* Show instances of leaking objects
* Basically they both do the job pretty well
**ANTS**
* **One-click filters to find common leaks** including: objects kept alive only by event handlers, objects that are disposed but still live and objects that are only being kept alive by a reference from a disposed object. This is probably the killer feature of ANTS - finding leaks is incredibly fast because of this. In my experience, the majority of leaks are caused by event handlers not being unhooked and ANTS just takes you straight to these objects. Awesome.
* Object retention graph. While the same info is available in Scitech, it's much easier to interpret in ANTS.
* Shows size with children in addition to size of the object itself (but only when an instance is selected unfortunately, not in the overall class list).
* Better integration to Visual Studio (right-click on graph to jump to file)
**Scitech .NET Memory Profiler**
* Shows stack trace when object was allocated. This is **really** useful for objects that are allocated in lots of different places. With ANTS it is difficult to determine exactly where the leaked object was created.
* Shows count of disposable objects that were not disposed. While not indicative of a leak, it does identify opportunities to fix this problem and improve your application performance as a result of faster garbage collection.
* More detailed filtering options (several columns can be filtered independently).
* Presents info on total objects created (including those garbage collected). ANTS only shows 'live' object stats. This makes it easier to analyze and tune overall application performance (eg. identify where lots of objects being created unnecessarily that aren't necessarily leaking).
By way of summary, I think ANTS helps you find what's leaking faster while Scitech provides a bit more detail about your overall application memory performance and individual objects once you know what to look at (eg. stack trace on creation). If the stack trace and tracking of undisposed disposable objects was added to ANTS I wouldn't see the need to use anything else.
|
What Are Some Good .NET Profilers?
|
[
"",
"c#",
".net",
"profiling",
"profiler",
""
] |
In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
```
So if tblCustomer looks like this:
```
ParentID CustID
5 5
1 8
5 4
4 1
```
The result I get from the code above is:
```
ParentID CustID
4 1
5 4
5 5
```
What I want is just the last row of that result:
```
ParentID CustID
5 5
```
How do I just return the last record generated in the CTE (which would be highest level CustID)?
Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT \* FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.
|
If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:
```
DECLARE @LookupID int
--Our test value
SET @LookupID = 1;
WITH cteLevelOne (ParentID, CustID, Depth) AS
(
SELECT a.ParentID, a.CustID, 1
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID, c.Depth + 1
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustID
)
select * from CTELevelone where Depth = (select max(Depth) from CTELevelone)
```
or, adapting what trevor suggests, this could be used with the same CTE:
```
select top 1 * from CTELevelone order by Depth desc
```
I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either.
|
I'm not certain I fully understand the problem, but just to hack & slash at it you could try:
```
SELECT TOP 1 FROM cteLevelOne ORDER BY CustID DESC
```
That assumes that the CustID is also in order as in the example, and not something like a GUID.
|
How do you get the last record generated in a recursive CTE?
|
[
"",
"sql",
"sql-server",
"recursion",
"common-table-expression",
""
] |
What are the differences between delegates and an events? Don't both hold references to functions that can be executed?
|
An **Event** declaration adds a layer of abstraction and protection on the **delegate** instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
|
To understand the differences you can look at this 2 examples
Example with Delegates (in this case, an Action - that is a kind of delegate that doesn't return a value)
```
public class Animal
{
public Action Run {get; set;}
public void RaiseEvent()
{
if (Run != null)
{
Run();
}
}
}
```
To use the delegate, you should do something like this:
```
Animal animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();
```
This code works well but you could have some weak spots.
For example, if I write this:
```
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;
```
with the last line of code, I have overridden the previous behaviors just with one missing `+` (I have used `=` instead of `+=`)
Another weak spot is that every class which uses your `Animal` class can invoke the delegate directly. For example, `animal.Run()` or `animal.Run.Invoke()` are valid outside the Animal class.
To avoid these weak spots you can use `events` in c#.
Your Animal class will change in this way:
```
public class ArgsSpecial : EventArgs
{
public ArgsSpecial (string val)
{
Operation=val;
}
public string Operation {get; set;}
}
public class Animal
{
// Empty delegate. In this way you are sure that value is always != null
// because no one outside of the class can change it.
public event EventHandler<ArgsSpecial> Run = delegate{}
public void RaiseEvent()
{
Run(this, new ArgsSpecial("Run faster"));
}
}
```
to call events
```
Animal animal= new Animal();
animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
animal.RaiseEvent();
```
Differences:
1. You aren't using a public property but a public field (using events, the compiler protects your fields from unwanted access)
2. Events can't be assigned directly. In this case, it won't give rise to the previous error that I have showed with overriding the behavior.
3. No one outside of your class can raise or invoke the event. For example, `animal.Run()` or `animal.Run.Invoke()` are invalid outside the Animal class and will produce compiler errors.
4. Events can be included in an interface declaration, whereas a field cannot
Notes:
EventHandler is declared as the following delegate:
```
public delegate void EventHandler (object sender, EventArgs e)
```
it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.
This example, which uses `EventHandler<ArgsSpecial>`, can also be written using `EventHandler` instead.
Refer [here](http://msdn.microsoft.com/it-it/library/db0etb8x(v=vs.110).aspx) for documentation about EventHandler
|
What are the differences between delegates and events?
|
[
"",
"c#",
"events",
"delegates",
"glossary",
""
] |
I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns.
|
I needed this functionality also. I made a class that inherits PictureBox, overrides `OnPaint` and adds a property to allow the interpolation mode to be set:
```
using System.Drawing.Drawing2D;
using System.Windows.Forms;
/// <summary>
/// Inherits from PictureBox; adds Interpolation Mode Setting
/// </summary>
public class PictureBoxWithInterpolationMode : PictureBox
{
public InterpolationMode InterpolationMode { get; set; }
protected override void OnPaint(PaintEventArgs paintEventArgs)
{
paintEventArgs.Graphics.InterpolationMode = InterpolationMode;
base.OnPaint(paintEventArgs);
}
}
```
|
I suspect you're going to have to do the resizing manually thru the Image class and DrawImage function and respond to the resize events on the PictureBox.
|
How do I make a PictureBox use Nearest Neighbor resampling?
|
[
"",
"c#",
".net",
"winforms",
"gdi+",
"picturebox",
""
] |
Recently I tried understanding the use of **java.math.MathContext** but failed to understand properly. Is it used for rounding in `java.math.BigDecimal`. If yes why does not it round the decimal digits but even mantissa part.
From API docs, I came to know that it follows the standard specified in `ANSI X3.274-1996` and `ANSI X3.274-1996/AM 1-2000` specifications but I did not get them to read online.
Please let me know if you have any idea on this.
|
@jatan
> Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
There's nothing special about `BigDecimal.round()` *vs.* any other `BigDecimal` method. In all cases, the `MathContext` specifies the number of significant digits and the rounding technique. Basically, there are two parts of every [`MathContext`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/MathContext.html). There's a precision, and there's also a [`RoundingMode`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html).
The precision again specifies the number of significant digits. So if you specify `123` as a number, and ask for 2 significant digits, you're going to get `120`. It might be clearer if you think in terms of scientific notation.
`123` would be `1.23e2` in scientific notation. If you only keep 2 significant digits, then you get `1.2e2`, or `120`. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
The `RoundingMode` part specifies how we should handle the loss of precision. To reuse the example, if you use `123` as the number, and ask for 2 significant digits, you've reduced your precision. With a `RoundingMode` of `HALF_UP` (the default mode), `123` will become `120`. With a `RoundingMode` of `CEILING`, you'll get `130`.
For example:
```
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
```
Outputs:
```
123.4
1.2E+2
1.3E+2
2E+2
```
You can see that both the precision and the rounding mode affect the output.
|
For rounding just the fractional part of a BigDecimal, check out the `BigDecimal.setScale(int newScale, int roundingMode)` method.
E.g. to change a number with three digits after the decimal point to one with two digits, and rounding up:
```
BigDecimal original = new BigDecimal("1.235");
BigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP);
```
The result of this is a BigDecimal with the value 1.24 (because of the rounding up rule)
|
Use of java.math.MathContext
|
[
"",
"java",
"math",
"bigdecimal",
"mathcontext",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.