Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I have a .ini file with sensitive information in my php wab app. I denied access to it using a .htaccess file:
```
<files my.ini>
order deny,allow
deny from all
</files>
```
I don't have access to folders outside of htdocs, so I can't move the .ini file out of browsable territory.
Is my solution safe?
|
The .htaccess will block access from the web. However, if you're using a shared hosting environment, it might be possible for other users to access your ini. If its on a (virtual private) server and you're the only user for that server you're safe.
In case of shared hosting it depends on server configuration.
For more info read: [PHP Security in a shared hosting environment](http://www.hostreview.com/guides/Technical_Support/articles/PHPSecurityinSharedEnvironment.html)
You can temporarily install [PHPShell](http://phpshell.sourceforge.net/) and browse through the server filesystem to check if your server is vulnerable. (requires some commandline knowledge)
|
Another good solution and my personal favourite (especially when developing code that might not remain under my stringent .htaccess control) is securing the actual .ini file. Thanks to a kind soul [here - user notes: pd at frozen-bits dot de](http://php.net/manual/en/function.parse-ini-file.php), what I do is:
```
my.ini -> changes to my.ini.php
```
my.ini.php starts off:
```
;<?php
;die(); // For further security
;/*
[category]
name="value"
;*/
```
Works perfectly! Access the file directly and all you see is ';' ***and*** it is a valid, parseable .ini file. What's not to like :)
A few notes on actual implementation (apologies if this counts as "overshare" but maybe save someone some time):
1. This file makes my IDE very Upset and it keeps trying to auto-reformat which then makes PHP Upset. Blessings be on Notepad++.
2. Don't forget the closing `;*/`. It still works if you leave it out but PHP warns you that it is about to become Upset.
Sorted.
|
Is it safe to deny access to .ini file in .htaccess?
|
[
"",
"php",
".htaccess",
""
] |
When browsing ASP.NET MVC source code in [codeplex](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266503&changeSetId=17272), I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then invoke another "protected virtual" method/property with same name.
For example,
```
public class MvcHandler : IHttpHandler, IRequiresSessionState
{
protected virtual bool IsReusable
{
get
{
return false;
}
}
bool IHttpHandler.IsReusable
{
get
{
return IsReusable;
}
}
}
```
I'm now sure what's the benefit of this kind of programming. For me, I prefer to just implicitly implement the interface IHttpHandler.
I guess the author just don't want **MvcHandler** has a public property **IsResuable**. The property **IsReusable** can only be used when instance of **MvcHandler** is treated as a **IHttpHandler**. Still, I'm not sure why the author what this way.
Anybody know more benefits about this style of interface implementation?
|
Well, not specific to MVC, but this approach allows you to **keep the core public API clean**. It is also useful if there is ever a risk of different interfaces / etc having the same name & signature, but different meaning. In reality this is rare.
It also allows you to provide an implementation where you want the return type to change in subclasses:
(`ICloneable` chosen for simplicity - don't get hung up on the fact that it is a poorly defined interface... a better example would have been things like `DbCommand` etc, which do this - but that is harder to show in a short example)
```
class Foo : ICloneable
{
public Foo Clone() { return CloneCore(); }
object ICloneable.Clone() { return CloneCore(); }
protected virtual Foo CloneCore() { ... }
}
class Bar : Foo
{
protected override Foo CloneCore() { ... }
public new Bar Clone() { return (Bar)CloneCore(); }
}
```
If we had used a public virtual method, we wouldn't be able to `override` it *and* use `new` in the base-class, as you aren't allowed to do both:
```
class A
{
public virtual A SomeMethod() { ... }
}
class B : A
{
public override A SomeMethod() { ... }
//Error 1 Type 'B' already defines a member called 'SomeMethod' with the same parameter types
public new B SomeMethod() { ... }
}
```
Using the protected virtual approach, any usage:
* Foo.Clone()
* Bar.Clone()
* ICloneable.Clone()
all use the correct `CloneCore()` implementation for the concrete type.
|
If a class implements `IFoo.Bar` explicitly, and a derived class needs `IFoo.Bar` to do something different, there will be no way for the derived class to call the base-class implementation of that method. A derived class which does not re-implement `IFoo.Bar` could call the base-class implementation via `((IFoo)this).Bar()`, but if the derived class re-implements `IFoo.Bar` (as it would have to in order to change its behavior) the aforementioned call would go to the derived-class re-implementation, rather than the base-class implementation. Even `((IFoo)(BaseType)this).bar` wouldn't help, since casting a reference to an interface type will discard any information about the type of the reference (as opposed to the type of the instance instance) that was cast.
Having an explicit interface implementation do nothing but call a protected method avoids this problem, since a derived class can change the behavior of the interface method by overriding the virtual method, while retaining the ability to call the base implementation as it sees fit. IMHO, C# should have had an explicit interface implementation produce a virtual method with a CLS-compliant name, so someone writing in C# a derivative of a class that explicitly implemented `IFoo.Bar` could say `override void IFoo.Bar`, and someone writing in some other language could say, e.g. `Overrides Sub Explicit_IFoo_Bar()`; since any derived class can re-implement `IFoo.Bar`, and since any derived class which doesn't re-implement `IFoo.Bar` can call it on itself, I don't see that there's any useful purpose to having the explicit implementation be sealed.
Incidentally, in vb.net, the normal pattern would simply be `Protected Overridable Sub IFoo_Bar() Implements IFoo.Bar`, without need for a separate virtual method.
|
Why to Use Explicit Interface Implementation To Invoke a Protected Method?
|
[
"",
"c#",
"interface",
"implicit",
"explicit-interface",
""
] |
I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP.
### Regex
```
(?<selector>[A-Za-z]+[\s]*)[\s]*{[\s]*((?<properties>[A-Za-z0-9-_]+)[\s]*:[\s]*(?<values>[A-Za-z0-9#, ]+);[\s]*)*[\s]*}
```
### Test case
```
body { background: #f00; font: 12px Arial; }
```
### Expected Outcome
```
Array(
[0] => Array(
[0] => body { background: #f00; font: 12px Arial; }
[selector] => Array(
[0] => body
)
[1] => Array(
[0] => body
)
[2] => font: 12px Arial;
[properties] => Array(
[0] => font
)
[3] => Array(
[0] => font
)
[values] => Array(
[0] => 12px Arial
[1] => background: #f00
)
[4] => Array(
[0] => 12px Arial
[1] => background: #f00
)
)
)
```
### Real Outcome
```
Array(
[0] => Array
(
[0] => body { background: #f00; font: 12px Arial; }
[selector] => body
[1] => body
[2] => font: 12px Arial;
[properties] => font
[3] => font
[values] => 12px Arial
[4] => 12px Arial
)
)
```
Thanks in advance for any help - this has been confusing me all afternoon!
|
That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it.
Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g.,
```
/([^{])\s*\{\s*([^}]*?)\s*}/
```
Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }'s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it's probably even better to avoid regex's altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.
|
You are trying to pull structure out of the data, and not just individual values. Regular expressions might could be painfully stretched to do the job, but you are really entering parser territory, and should be pulling out the big guns, namely parsers.
I have never used the PHP parser generating tools, but they look okay after a light scan of the docs. Check out [LexerGenerator](http://pear.php.net/package/PHP_LexerGenerator) and [ParserGenerator](http://pear.php.net/package/PHP_ParserGenerator). LexerGenerator will take a bunch of regular expressions describing the different types of tokens in a language (in this case, CSS) and spit out some code that recognizes the individual tokens. ParserGenerator will take a grammar, a description of what things in a language are made up of what other things, and spit out a parser, code that takes a bunch of tokens and returns a syntax tree (the data structure that you are after.
|
Parsing CSS by regex
|
[
"",
"php",
"css",
"regex",
"css-parsing",
""
] |
I've almost completely installed Boost, but I have a problem with how to set my path to Boost in *Tools->options->projects->VC++ Directories*.
I've written the path to include files and libraries (my folder contains two subfolders, `lib` and `include`), but when I try to use Boost with
`#include boost/regex.hpp`, I got this linking error:
```
LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_36.lib
```
Could you please tell me how to install Boost correctly for Visual Studio 2008?
|
Use the [Boost Installer](http://www.boostpro.com/download/) by the Boost consulting group.
|
You might be interested in the Visual Studio 2008 Feature pack. It adds many of the features that have only been available from Boost until now, the features that are part of the C++ TR1.
|
how to install boost to the VS 2008?
|
[
"",
"c++",
"visual-studio-2008",
"boost",
"installation",
""
] |
Is there a better way to do the following:
```
$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$array[] = 'test6';
end($array);
echo key($array); // gives me 6
```
This will give the key of the most recently add array element.
Is there a better way to do this?
|
You could also do:
```
$end = end(array_keys($array));
```
But I think your way makes it clear what you want to do, so you could whip something up like:
```
function array_last_key($array) {
end($array);
return key($array);
}
```
That's about it.
|
Simply put no. Both end and key are Big O(1) time. Any other way slows your code down and adds complexity.
|
What is the best method of getting the key of the last added array item in PHP?
|
[
"",
"php",
"arrays",
"key",
""
] |
I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java.
I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.
|
If the only thing in there is whitespace and integers, just try something like this:
```
int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
```
or easier:
```
int i1, i2;
theFileStream >> i1 >> i2;
```
|
There are a couple of things to consider:
Lets assume you have two numbers on each line followed by text you don't care about.
```
while(inFile >> rows >> columns)
{
// Successfully read rows and columns
// Now remove the extra stuff on the line you do not want.
inFile.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
```
Also note if the only thing separating the integer values is "white space" then you don't even need to use the ignore() line.
The above while() works because: The operator >> returns a stream object (reference). Because the stream object is being used in a boolean context the compiler will try and convert it into a bool and the stream object has a cast operator that does that conversion (by calling good() on the stream).
The important thing to note is **NOT** to use the line
```
while(inFile.eof())
```
If you do use this then you fall into the trap of the last line problem. If you have read all the data eof() is still false (as it is not true until you try and read past EOF). So there is no data left in the file but you still enter the loop body. In your code the getline() is then executed and fails (no more data), EOF is now set. What the rest of the loop does will depend on how and where inLine is defined.
You can use this test as above. But you must also be willing to test the stream is OK after you have used it.
```
while(inFile.eof()) // Should probably test good()
{
getLine(inFile,inputline);
if(inFile.eof()) // should probably test good()
{
break;
}
}
```
|
Parsing integers from a line
|
[
"",
"c++",
"string",
"parsing",
""
] |
I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent.
Below is the code that I'm using. The code is invoked when a user clicks on a link, not a form "submit" button. It runs without error, invokes the servlet that is being called but, as I mentioned earlier, the body of the POST never seems to be sent.
I can validate that the request body is never sent since I have access to the servlet being called.
I've tried using "parameters" in replace of "requestBody." I've also tried using a parameter string (x=a?y=b). I've also validated that "ckULK" does contain a valid value.
Any ideas?
```
new Ajax.Request(sURL,
{
method: 'POST'
, contentType: "text/x-json"
, requestBody: {ulk:ckULK}
, onFailure:
function(transport)
{
vJSONResp = transport.responseText;
var JSON = eval( "(" + vJSONResp + ")" );
updateStatus(JSON.code + ": " + JSON.message);
} // End onFailure
, onSuccess:
function(transport)
{
if (200 == transport.status)
{
vJSONResp = transport.responseText;
}
else
{
log.value += "\n" + transport.status;
}
} // End onSuccess
}); // End Ajax.request
```
|
These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent.
You also definitely need to stick to `parameters` instead of `requestBody`.
This:
```
new Ajax.Request(sURL,
{
method: 'POST',
parameters: 'hello=world&test=yes',
onFailure: function(transport) {
vJSONResp = transport.responseText;
var JSON = eval( "(" + vJSONResp + ")" );
updateStatus(JSON.code + ": " + JSON.message);
},
onSuccess: function(transport) {
if (200 == transport.status) {
vJSONResp = transport.responseText;
} else {
log.value += "\n" + transport.status;
}
}
});
```
Should definitely work.
|
Simply pass the data as **`parameters`** to the Ajax Request constructor:
```
new Ajax.Request(url, {
method: 'POST',
parameters: {
hello: "world", test: "test"
},
onSuccess: function(transport){
var data = transport.responseText.evalJSON();
}
});
```
|
AJAX.Request POST body not send
|
[
"",
"javascript",
"post",
"prototypejs",
""
] |
Please one library per answer so that people can vote for the individually.
|
[Calendar Date Select](http://code.google.com/p/calendardateselect/)
|
[Timeframe](http://stephencelis.com/projects/timeframe) for visual selection of date ranges...
|
What's your favorite Prototype framework compatible, javascript date picker?
|
[
"",
"javascript",
"ruby-on-rails",
"user-interface",
""
] |
I have an interesting problem and would appreciate your thoughts for the best solution.
I need to parse a set of logs. The logs are produced by a multi-threaded program and a single process cycle produces several lines of logs.
When parsing these logs I need to pull out specific pieces of information from each process - naturally this information is across the multiple lines (I want to compress these pieces of data into a single line). Due to the application being multi-threaded, the block of lines belonging to a process can be fragmented as other processes at written to the same log file at the same time.
Fortunately, each line gives a process ID so I'm able to distinguish what logs belong to what process.
Now, there are already several parsers which all extend the same class but were designed to read logs from a single threaded application (no fragmentation - from original system) and use a readLine() method in the super class. These parsers will keep reading lines until all regular expressions have been matched for a block of lines (i.e. lines written in a single process cycle).
So, what can I do with the super class so that it can manage the fragmented logs, and ensure change to the existing implemented parsers is minimal?
|
It sounds like there are some existing parser classes already in use that you wish to leverage. In this scenario, I would write a [decorator](http://en.wikipedia.org/wiki/Decorator_pattern) for the parser which strips out lines not associated with the process you are monitoring.
It sounds like your classes might look like this:
```
abstract class Parser {
public abstract void parse( ... );
protected String readLine() { ... }
}
class SpecialPurposeParser extends Parser {
public void parse( ... ) {
// ... special stuff
readLine();
// ... more stuff
}
}
```
And I would write something like:
```
class SingleProcessReadingDecorator extends Parser {
private Parser parser;
private String processId;
public SingleProcessReadingDecorator( Parser parser, String processId ) {
this.parser = parser;
this.processId = processId;
}
public void parse( ... ) { parser.parse( ... ); }
public String readLine() {
String text = super.readLine();
if( /*text is for processId */ ) {
return text;
}
else {
//keep readLine'ing until you find the next line and then return it
return this.readLine();
}
}
```
Then any occurrence you want to modify would be used like this:
```
//old way
Parser parser = new SpecialPurposeParser();
//changes to
Parser parser = new SingleProcessReadingDecorator( new SpecialPurposeParser(), "process1234" );
```
This code snippet is simple and incomplete, but gives you the idea of how the decorator pattern could work here.
|
I would write a simple distributor that reads the log file line by line and stores them in different VirtualLog objects in memory -- a VirtualLog being a kind of virtual file, actually just a String or something that the existing parsers can be applied to. The VirtualLogs are stored in a Map with the process ID (PID) as the key. When you read a line from the log, check if the PID is already there. If so, add the line to the PID's respective VirtualLog. If not, create a new VirtualLog object and add it to the Map. Parsers run as separate Threads, one on every VirtualLog. Every VirtualLog object is destroyed as soon as it has been completely parsed.
|
How to parse logs written by multiple threads?
|
[
"",
"java",
"regex",
"multithreading",
"inheritance",
"parsing",
""
] |
I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!
|
You can read a file into an array of lines and do all the splitting with:
```
$lines = file("filename");
foreach($lines as $line) {
$parts = explode("|", $line);
// do the database inserts here
}
```
If you already have all the text in a variable as you said (e.g., with something like file\_get\_contents() ), you can explode on \n first and then do the same foreach statement as above.
|
If you are reading out of your textarea post, you can use the explode function using the newline character as your separator to get each "line" in the variable as a new element of an array, then you can do explode on your array elements.
i.e.
```
$sometext = "balh | balh blah| more blah \n extra balh |some blah |this blah";
$lines = explode("\n", $sometext);
foreach($lines as $oneLine)
{
$lineElements[] = explode("|", $oneLine);
}
```
then you have a 2d array of your elems.
If you are reading out of a file, you can simply use the file function documented here:
<https://www.php.net/manual/en/function.file.php>
to get each line of the file as an element of an array.
|
Parsing A Data Feed
|
[
"",
"php",
"database",
"parsing",
"explode",
"datafeed",
""
] |
I am having a peculiar problem with the order in which FlowLayoutPanels are added in to the form's **controls** property. This is what I tried,
I added 7 FlowLayoutPanels in to a C# window application from left to right in vertical strips. Then I tagged the flow layouts as 1, 2, 3, ... 7 again from left to right. Now in the load handler of the form, I wrote the following snippet,
```
foreach (FlowLayoutPanel aDaysControl in this.Controls)
{
MessageBox.Show(aDaysControl.Tag.ToString());
}
```
I expected messages to appear in the order of **1, 2, ... 7**. But I got it in the reverse order (7, 6, ...1). Could some one help me out with the mistake I did ??
Reason behind preserving the order,
> I am trying to make a calendar control
> with each row representing a day. If a
> month starts from Wednesday, then I
> need to add a empty label to the
> first(Monday) and the second(Tuesday)
> row. So the order matters a bit
|
look at the order in which they are added to the form in the yourForm.designer.cs
|
I know this is quite an old question, but...
You might want to use `SetChildIndex`. e.g. `this.Controls.SetChildIndex(button1, 0);`
|
Order of controls in a form's Control property in C#
|
[
"",
"c#",
"winforms",
"user-interface",
"controls",
""
] |
I could do this in C#..
```
int number = 2;
string str = "Hello " + number + " world";
```
..and str ends up as "Hello 2 world".
In VB.NET i could do this..
```
Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"
```
..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."
I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?
|
In VB I believe the string concatenation operator is & rather than + so try this:
```
Dim number As Integer = 2
Dim str As String = "Hello " & number & " world"
```
Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that `System.String` doesn't define an addition operator - it's all hidden in the compiler by calls to `String.Concat`. (This allows much more efficient concatenation of multiple strings.)
|
Visual Basic makes a distinction between the `+` and `&` operators. The `&` will make the conversion to a string if an expression is not a string.
[`&`Operator (Visual Basic)](http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx)
The `+` operator uses more complex evaluation logic to determine what to make the final cast into (for example it's affected by things like **Option Strict** configuration)
[`+`Operator (Visual Basic)](http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx)
|
Automatic casting to string in C# and VB.NET
|
[
"",
"c#",
"vb.net",
"casting",
""
] |
Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees their values listed in the Variables window as arg0, arg1, arg2, etc but at least the values are visible.
This is occurring at present in relation to classes defined within the core JDK. I have verified that the installed and current JRE is a JDK.
Is anybody able to shed some light on this behaviour?
|
Apparently, the [answer](http://dev.eclipse.org/newslists/news.eclipse.platform/msg56943.html) is:
> the rt.jar that ships with the JDK (where the core Java classes live) is not compiled with full debug information included in the .class files, so the debugger does not have local variable info.
>
> Unfortunately, this is not something that Eclipse can do anything about - all debuggers will have the same problem with JDK core classes.
The [release notes of Eclipse 3.4](http://www.eclipse.org/eclipse/development/readme_eclipse_3.4.html) states:
> **Missing debug attributes**
> The debugger requires that class files be compiled with debug attributes if it is to be able to display line numbers and local variables. Quite often, class libraries (for example, "rt.jar") are compiled without complete debug attributes, and thus local variables and method arguments for those classes are not visible in the debugger.
|
It [used to be](http://forums.java.net/jive/thread.jspa?messageID=10811&tstart=0) that you can get debug rt.jar from http: //download.java.net/jdk6/binaries/, but not any more.
So [building your own rt.jar with -g](http://www.javalobby.org/java/forums/t103334.html) seems to be the only option now. It's very simple: just use javac and jar from your JDK.
* `mkdir \tmp; mkdir \tmp\out`
* Extract `src.zip` in JDK installation directory to `tmp\src`
* `cd src`
* `find -name *.java > files.txt`
* `javac -verbose -g -d \tmp\out -J-Xmx512m -cp "<jdk>\jre\lib\rt.jar";"<jdk>\lib\tools.jar" @files.txt`
* `cd \tmp\out; jar cvf rt.jar *`
If you use Eclipse, you don't need -Xbootclasspath/p:, instead just put your debug jar to Bootstrap Entries before JRE in launch configuration.
|
Locally declared variables can not be inspected
|
[
"",
"java",
"eclipse",
"debugging",
""
] |
I use `x != null` to avoid [`NullPointerException`](https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html). Is there an alternative?
```
if (x != null) {
// ...
}
```
|
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
1. Where null is a valid response in terms of the contract; and
2. Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use [`Objects.requireNonNull(foo)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)). (If you are stuck with a previous version then [`assert`ions](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html) may be a good alternative.)
"Proper" usage of this method would be like below. The method returns the object passed into it and throws a `NullPointerException` if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
```
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
```
It can also be used like an `assert`ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
```
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
```
Generally throwing a specific exception like `NullPointerException` when a value is null but shouldn't be is favorable to throwing a more general exception like `AssertionError`. This is the approach the Java library takes; favoring `NullPointerException` over `IllegalArgumentException` when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
```
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
```
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the [Null Object pattern](https://en.wikipedia.org/wiki/Null_Object_pattern):
```
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
```
Compare:
```
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
```
to
```
ParserFactory.getParser().findAction(someInput).doSomething();
```
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
```
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
```
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
```
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
```
|
If you use (or planning to use) a Java IDE like [JetBrains IntelliJ IDEA](https://www.jetbrains.com/idea/), [Eclipse](https://www.eclipse.org/) or [Netbeans](https://netbeans.org/) or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got `@Nullable` and `@NotNull`.
You can use in method and parameters, like this:
```
@NotNull public static String helloWorld() {
return "Hello World";
}
```
or
```
@Nullable public static String helloWorld() {
return "Hello World";
}
```
The second example won't compile (in IntelliJ IDEA).
When you use the first `helloWorld()` function in another piece of code:
```
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
```
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the `helloWorld()` function won't return `null`, ever.
Using parameter
```
void someMethod(@NotNull someParameter) { }
```
if you write something like:
```
someMethod(null);
```
This won't compile.
Last example using `@Nullable`
```
@Nullable iWantToDestroyEverything() { return null; }
```
Doing this
```
iWantToDestroyEverything().something();
```
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other `@Nullable` `@NotNull` implementations.
See blog post *[More flexible and configurable @Nullable/@NotNull annotations](https://blog.jetbrains.com/idea/2011/03/more-flexible-and-configurable-nullublenotnull-annotations/)*.
|
How do I avoid checking for nulls in Java?
|
[
"",
"java",
"nullpointerexception",
"null",
""
] |
There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away. Would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collection?
My concern is that internal cross-references may "protect" the entire subgraph from garbage collection. In other words, is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged.
|
As stated in this [SO question](https://stackoverflow.com/questions/176745/circular-references-in-java), circular reference is well managed.
Java does not do reference counting, it does uses [tracing garbage collection](https://en.wikipedia.org/wiki/Tracing_garbage_collection) (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are "reachable" and then it cleans up everything else.
References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not.
About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method.
In that case, setting null to the reference of the graph will help making an **island of isolation** (even for internal circular references) as described in this [article](http://detailfocused.blogspot.com/2008/03/garbage-collection.html).
You will find more details about the unreachable state in [The Truth About Garbage Collection](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html):
**Unreachable**
An object enters an unreachable state when no more strong references to it exist.
When an object is unreachable, it is a candidate for collection.
Note the wording:
Just because an object is a candidate for collection doesn’t mean it will be immediately
collected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object.
It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes:
* Temporary variables on the stack (of any thread)
* Static variables (from any class)
* Special references from JNI native code
**Circular strong references don’t necessarily cause memory leaks**.
Consider a code creating two objects, and assigns them references to each other.
```
public void buidDog() {
Dog newDog = new Dog();
Tail newTail = new Tail();
newDog.tail = newTail;
newTail.dog = newDog;
}
```
Before the method returns, there are strong references from the temporary stack variables in the `buildDog` method pointing to both the `Dog` and the `Tail`.
After the `buildDog` method returns, the `Dog` and `Tail` both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).
|
Yes - the garbage collector can cope with circular references etc.
|
Cross-references and garbage collection
|
[
"",
"java",
""
] |
I need to search a string in the string array. I dont want to use any for looping in it
```
string [] arr = {"One","Two","Three"};
string theString = "One"
```
I need to check whether theString variable is present in arr.
|
Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string
```
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
```
|
Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:
```
bool has = arr.Contains(var); // .NET 3.5
```
or
```
bool has = Array.IndexOf(arr, var) >= 0;
```
For info: **avoid names like var** - this is a keyword in C# 3.0.
|
How to search a string in String array
|
[
"",
"c#",
"asp.net",
""
] |
I have the following interface:
```
internal interface IRelativeTo<T> where T : IObject
{
T getRelativeTo();
void setRelativeTo(T relativeTo);
}
```
and a bunch of classes that (should) implement it, such as:
```
public class AdminRateShift : IObject, IRelativeTo<AdminRateShift>
{
AdminRateShift getRelativeTo();
void setRelativeTo(AdminRateShift shift);
}
```
I realise that these three are not the same:
```
IRelativeTo<>
IRelativeTo<AdminRateShift>
IRelativeTo<IObject>
```
but nonetheless, I need a way to work with all the different classes like AdminRateShift (and FXRateShift, DetRateShift) that should all implement IRelativeTo. Let's say I have a function which returns AdminRateShift as an Object:
```
IRelativeTo<IObject> = getObjectThatImplementsRelativeTo(); // returns Object
```
By programming against the interface, I can do what I need to, but I can't actually cast the Object to IRelativeTo so I can use it.
It's a trivial example, but I hope it will clarify what I am trying to do.
|
If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.
```
internal interface IRelativeTo
{
object getRelativeTo(); // or maybe something else non-generic
void setRelativeTo(object relativeTo);
}
internal interface IRelativeTo<T> : IRelativeTo
where T : IObject
{
new T getRelativeTo();
new void setRelativeTo(T relativeTo);
}
```
Another option is for you to code largely in generics... i.e. you have methods like
```
void DoSomething<T>() where T : IObject
{
IRelativeTo<IObject> foo = // etc
}
```
If the `IRelativeTo<T>` is an argument to `DoSomething()`, then *usually* you don't need to specify the generic type argument yourself - the compiler will infer it - i.e.
```
DoSomething(foo);
```
rather than
```
DoSomething<SomeType>(foo);
```
There are benefits to both approaches.
|
unfortunately inheritance doesn't work with generics. If your function expects IRelativeTo, you can make the function generic as well:
```
void MyFunction<T>(IRelativeTo<T> sth) where T : IObject
{}
```
If I remember correctly, when you use the function above you don't even need to specify the type, the compiler should figure it out based on the argument you supply.
If you want to keep a reference to one of these IRelativeTo objects inside a class or method (and you don't care what T is that), you need to make this class/method generic again.
I agree, it is a bit of pain.
|
Casting an object to a generic interface
|
[
"",
"c#",
"generics",
"interface",
"casting",
""
] |
Using Java, how can I test that a URL is contactable, and returns a valid response?
```
http://stackoverflow.com/about
```
|
The solution as a unit test:
```
public void testURL() throws Exception {
String strUrl = "http://stackoverflow.com/about";
try {
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}
```
|
Since java 5 if i recall, the InetAdress class contains a method called isReachable(); so you can use it to make a ping implementation in java. You can also specify a timeout for this method. This is just another alternative to the unit test method posted above, which is probably more efficient.
|
How can I programmatically test an HTTP connection?
|
[
"",
"java",
"http",
"url",
"httpconnection",
""
] |
> **EDIT**: This question duplicates [How to access the current Subversion build number?](https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#111173) (Thanks for the heads up, Charles!)
Hi there,
This question is similar to [Getting the subversion repository number into code](https://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code)
The differences being:
1. I would like to add the revision number to Python
2. I want the revision of the repository (not the checked out file)
I.e. I would like to extract the Revision number from the return from 'svn info', likeso:
$ svn info
```
Path: .
URL: svn://localhost/B/trunk
Repository Root: svn://localhost/B
Revision: 375
Node Kind: directory
Schedule: normal
Last Changed Author: bmh
Last Changed Rev: 375
Last Changed Date: 2008-10-27 12:09:00 -0400 (Mon, 27 Oct 2008)
```
I want a variable with 375 (the Revision). It's easy enough with put $Rev$ into a variable to keep track of changes on a file. However, I would like to keep track of the repository's version, and I understand (and it seems based on my tests) that $Rev$ only updates when the file changes.
My initial thoughts turn to using the svn/libsvn module built in to Python, though I can't find any documentation on or examples of how to use them.
Alternatively, I've thought calling 'svn info' and regex'ing the code out, though that seems rather brutal. :)
Help would be most appreciated.
Thanks & Cheers.
|
There is a command called `svnversion` which comes with subversion and is meant to solve exactly that kind of problem.
|
Stolen directly from django:
```
def get_svn_revision(path=None):
rev = None
if path is None:
path = MODULE.__path__[0]
entries_path = '%s/.svn/entries' % path
if os.path.exists(entries_path):
entries = open(entries_path, 'r').read()
# Versions >= 7 of the entries file are flat text. The first line is
# the version number. The next set of digits after 'dir' is the revision.
if re.match('(\d+)', entries):
rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
if rev_match:
rev = rev_match.groups()[0]
# Older XML versions of the file specify revision as an attribute of
# the first entries node.
else:
from xml.dom import minidom
dom = minidom.parse(entries_path)
rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
if rev:
return u'SVN-%s' % rev
return u'SVN-unknown'
```
Adapt as appropriate. YOu might want to change MODULE for the name of one of your codemodules.
This code has the advantage of working even if the destination system does not have subversion installed.
|
How does one add a svn repository build number to Python code?
|
[
"",
"python",
"svn",
""
] |
You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.
However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons.
A trivial example would be if you were sorting a collection of objects that represent contact data. Sometimes you will want to sort by
```
last name, first name, area code
```
. Other times
```
first name, last name
```
- yet other times
```
age, first name, area code
```
... etc
Now, you can certainly write an additional function object for each case, but that violates the DRY principle - especially if each comparison is less trivial.
It seems like you should be able to write a hierarchy of comparison functions - the low level ones do the single, primitive, comparisons (e.g. first name < first name), then higher level ones call the lower level ones in succession (probably chaining with && to make use of short circuit evaluation) to generate the composite functions.
The trouble with this approach is that std::sort takes a binary predicate - the predicate can only return a bool. So if you're composing them you can't tell if a "false" indicates equality or greater than. You can make your lower level predicates return an int, with three states - but then you would have to wrap those in higher level predicates before they could be used with std::sort on their own.
In all, these are not insurmountable problems. It just seems harder than it should be - and certainly invites a helper library implementation.
Therefore, does anyone know of any pre-existing library (esp. if it's a std or boost library) that can help here - of have any other thoughts on the matter?
[Update]
As mentioned in some of the comments - I've gone ahead and written my own implementation of a class to manage this. It's fairly minimal, and probably has some issues with it in general. but on that basis, for anyone interested, the class is here:
<http://pastebin.com/f52a85e4f>
And some helper functions (to avoid the need to specify template args) is here:
<http://pastebin.com/fa03d66e>
|
You could build a little chaining system like so:
```
struct Type {
string first, last;
int age;
};
struct CmpFirst {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; }
};
struct CmpLast {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; }
};
struct CmpAge {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.age < rhs.age; }
};
template <typename First, typename Second>
struct Chain {
Chain(const First& f_, const Second& s_): f(f_), s(s_) {}
bool operator () (const Type& lhs, const Type& rhs) {
if(f(lhs, rhs))
return true;
if(f(rhs, lhs))
return false;
return s(lhs, rhs);
}
template <typename Next>
Chain <Chain, Next> chain(const Next& next) const {
return Chain <Chain, Next> (*this, next);
}
First f;
Second s;
};
struct False { bool operator() (const Type& lhs, const Type& rhs) { return false; } };
template <typename Op>
Chain <False, Op> make_chain(const Op& op) { return Chain <False, Op> (False(), op); }
```
Then to use it:
```
vector <Type> v; // fill this baby up
sort(v.begin(), v.end(), make_chain(CmpLast()).chain(CmpFirst()).chain(CmpAge()));
```
The last line is a little verbose, but I think it's clear what's intended.
|
One conventional way to handle this is to sort in multiple passes and use a stable sort. Notice that `std::sort` is generally *not* stable. However, there’s `std::stable_sort`.
That said, I would write a wrapper around functors that return a tristate (representing less, equals, greater).
|
Chaining of ordering predicates (e.g. for std::sort)
|
[
"",
"c++",
"stl",
"sorting",
"compare",
"predicate",
""
] |
Say I have the following interface that I want to share between my server (a regular web service) and my client (a silverlight 2.0 application):
```
public interface ICustomerService
{
Customer GetCustomer(string name);
}
```
My web service implements this interface, and references a class library where `Customer` type is defined.
Usually, if you want to consume this service from a WCF client, say a winforms app, you could share your model assembly and your service contract interfaces. Then, by using a `ChannelFactory`, you can dynamically create a proxy which implements your service interface. Something like:
```
ICustomerService myService = new ChannelFactory<ICustomerService>(myBinding, myEndpoint);
Customer customer = myService.GetCustomer("romain");
```
I basically want to do the same thing, but from a Silverlight 2.0 application. The silverlight `ChannelFactory` doesn't seems to act like the other one...
**Do you know if it's possible ?**
Note : Since a Silverlight application can only refers Silverlight projects, I have:
Two versions of MyModel.dll which contains `Customer` type:
* One compiled targetting .NET framework 3.5, referenced by my web service project
* Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app
Two versions of MyServicesContracts.dll which contains `ICustomerService` interface:
* One compiled targetting .NET framework 3.5, referenced by my web service project
* Another compiled targetting the silverlight 2.0 framework, referenced by my silverlight app
|
I think you will find this [thread](http://silverlight.net/forums/t/34368.aspx) interesting. You can share code files between separate projects or compile a single project against multiple targets.
|
I could be wrong, but I think if you decorate objects being returned by your WCF Service with the DataContract and DataMember attributes, you should be able to share objects between your Silverlight application and WCF service without creating the class in your client (should be handled by the proxy.
|
Sharing service interfaces and model in Silverlight, using WCF
|
[
"",
"c#",
".net",
"wcf",
"silverlight",
""
] |
> **Possible Duplicate:**
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
|
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be placed in `AssemblyInfo.cs`
```
[assembly: InternalsVisibleTo("OtherAssembly")]
```
|
The closest equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
|
What is the C# equivalent of friend?
|
[
"",
"c#",
"encapsulation",
"friend",
""
] |
In c#, is there any difference in the excecution speed for the order in which you state the condition?
```
if (null != variable) ...
if (variable != null) ...
```
Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.
If there is no difference, what is the advantage of the first one?
|
It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):
```
// Probably wrong
if (x = 5)
```
when you actually probably meant
```
if (x == 5)
```
You can work around this in C by doing:
```
if (5 == x)
```
A typo here will result in invalid code.
Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "`x=5`" is `Int32`, not `Boolean`.
I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.
|
Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.
Just take this simple example:
```
if(someVariableThatShouldBeChecked != null
&& anotherOne != null
&& justAnotherCheckThatIsNeededForTestingNullity != null
&& allTheseChecksAreReallyBoring != null
&& thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)
{
// ToDo: Everything is checked, do something...
}
```
If you would simply swap all the *null* words to the beginning you can much easier spot all the checks:
```
if(null != someVariableThatShouldBeChecked
&& null != anotherOne
&& null != justAnotherCheckThatIsNeededForTestingNullity
&& null != allTheseChecksAreReallyBoring
&& null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)
{
// ToDo: Everything is checked, do something...
}
```
So this example is maybe a bad example (refer to coding guidelines) but just think about you quick scroll over a complete code file. By simply seeing the pattern
```
if(null ...
```
you immediately know what's coming next.
If it would be the other way around, you always have to *scan* to the end of the line to see the nullity check, just letting you stumble for a second to find out what kind of check is made there. So maybe syntax highlighting may help you, but you are always slower when those keywords are at the end of the line instead of the front.
|
Why does one often see "null != variable" instead of "variable != null" in C#?
|
[
"",
"c#",
"coding-style",
""
] |
Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?
```
#ifndef ofxBASE_SND_OBJ
#define ofxBASE_SND_OBJ
#include "ofConstants.h"
class ofxBaseSndObj {
public:
virtual string getType(){}
string key;
};
#endif
```
Here's my buzz class
```
#ifndef OFXSO_BUZZ
#define OFXSO_BUZZ
#include "ofxBaseSndObj.h"
class ofxSOBuzz : public ofxBaseSndObj
{
public:
string getType();
};
#endif
```
ofxSOBuzz.cpp
```
string ofxSOBuzz::getType()
{
string s = string("ofxSOBuzz");
printf(" ********* returning string type %s", s.c_str()); // doesn't get called!
return s;
}
```
Then in another class I try to call it this way:
```
string ofxSndObj::createFilter(ofxBaseSndObj obj)
{
string str = obj.getType();
if(str.compare("ofxSOBuzz") == 0)
{
printf(" all is well ");
}
}
```
In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!
|
Change this line:
```
string ofxSndObj::createFilter(ofxBaseSndObj obj)
```
to
```
string ofxSndObj::createFilter(ofxBaseSndObj& obj)
```
What you are doing is passing by value (passing a copy).
This means you are copying the object to the function. Because the function does not know what type you are actually passing it only passes the type defined in the function declaration and thus it makes a copy of the base class (this is know as the [slicing](http://www.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/section/slice.htm) problem).
The solution is to pass by reference.
If you do not want the function to modify the object (maybe that is why you were passing by value so it could not alter the original) then pass a const reference.
```
class ofxBaseSndObj
{
public:
virtual string getType() const;
// If the method does not change the object mark it const
string key;
};
string ofxSndObj::createFilter(ofxBaseSndObj const& obj)
{
// allowed to call this if getType() is a const
string str = obj.getType();
if(str.compare("ofxSOBuzz") == 0)
{
printf(" all is well ");
}
}
```
|
You need to pass the instance to createFilter as a **pointer** (or reference) to the object. You are [passing by value](http://cplus.about.com/od/glossar1/g/passbyvaldefn.htm), and this causes the compiler to copy the derived object you use as an argument into an instance of the base class. When it does this you lose the fact that it was originally a derived type.
As written your code shouldn't actually compile since the declaration of ofxBaseSndObj::getType doesn't return anything. Did you mean for this to be an abstract method or return an empty string?
If you made it an abstract method then the compiler would complain about trying to instantiate an abstract class in your ofxSndObj::createFilter method.
|
Inheritance in C++
|
[
"",
"c++",
"oop",
"inheritance",
""
] |
I'm trying to delete a directory that contains XML files from a remote computer. My code compiles and runs fine, but when I go to get a list of XML files in the path I specify, it is not returning anything. Am I missing something permission wise?
I have ran it from my computer logged on as myself and from another computer logged on as a different user. Both accounts have full control over the directory that contains the XML files.
I'm using .NET 2.0.
```
static void Main(string[] args) {
string directory, ext = ".xml"; // have tried xml and .xml
if (args.Length != 1) {
// do absolutely nothing if we do not exactly 1 argument
} else {
Console.WriteLine("Argument accepted.");
directory = args[0];
// make sure the directory passed is valid
if (ValidateDirectory(directory)) {
Console.WriteLine("Directory is valid.");
DeleteFiles(directory, ext);
}
}
Console.WriteLine("Done.");
}
static bool ValidateDirectory(string d) {
return Regex.IsMatch(d, @""); // I removed my regex - it validates properly
}
static void DeleteFiles(string d, string ext) {
DirectoryInfo di;
FileInfo[] fi;
di = new DirectoryInfo(d);
fi = di.GetFiles(ext);
Console.WriteLine("Number of files = " + fi.Length + ".");
foreach (FileInfo f in fi) {
try {
Console.WriteLine(f.FullName);
f.Delete();
} catch (Exception ex) {
// do nothing when there is an exception
// just do not want it to quit
Console.WriteLine(ex.ToString());
}
}
}
```
|
I think you should be using \*.xml instead of simply .xml. But I also concur with Kyralessa, test on your local machine first, then add in the complexity of going across a network.
|
in DeleteFiles, you have the following line:
fi = di.GetFiles(ext);
where ext is the extension you pass in, which I believe is just '.xml'. Get files is looking for any files called '.xml'. GetFiles takes wildcards, which I believe is what you are intending to do. Put an asterisk (\*) at the front and give that a try.
-Brett
|
Delete files from remote computer
|
[
"",
"c#",
"windows",
"file-io",
"permissions",
""
] |
I launch the following command line (process) from a Windows VC++ 6 program using CreateProcess (or \_spawnv()):
* java -cp c:\dir\updates.jar;c:\dir\main.jar Main
and class updates in updates.jar (overiding some in main.jar) are not read or found. It is as if the updates.jar library cannot be found or read.
If I launch the same line from a shortcut, or from the command line proper, everything IS found and executes properly.
If I launch a JVM from the command line, keep it running, AND THEN launch the executable stub (above), then everything works OK also. (This makes it look like the issue is a file rights thing).
Any insight would be greatly appreciated!
--Edward
|
Try using Microsoft's FileMon utility to figure out what's happening. Set the include filter to "updates" to focus in on the problem.
<http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx>
|
Thanks **jdigital**!
I tried FileMon and it showed me what I was doing wrong. The executable calling CreateProcess() had an unclosed file handle to updates.jar from an attempt to copy the update JAR earlier. Bad code that works in the production environment, but not in the test environment.
|
JVM Launched via CreateProcess() Loses Classpath Library
|
[
"",
"java",
"windows",
"process",
"jvm",
"classpath",
""
] |
How do you automate [integration testing](http://en.wikipedia.org/wiki/Integration_testing)? I use JUnit for some of these tests. This is one of the solutions or is totally wrong? What do you suggest?
|
JUnit works. There are no limitations that restrict it to being unit tests only. We use JUnit, Maven and CruiseControl to do CI.
There may be tools that are specific for integration testing, but I would think their usefulness is dependent on what type of system components you are integrating. JUnit will work fine for non UI type testing.
|
I've used JUnit for doing a lot of integration testing. Integration testing can, of course, mean many different things. For more system level integration tests, I prefer to let scripts drive my testing process from outside.
Here's an approach that works well for me for applications that use http and databases and I want to verify the whole stack:
1. Use `Hypersonic or H2` in in-memory mode as a replacement for the database (this works best for ORMs)
2. Initialize the database in `@BeforeSuite` or equivalent (again: easiest with ORMs)
3. Use Jetty to start an in-process web server.
4. `@Before` each test, clear the database and initialize with the necessary data
5. Use `JWebUnit` to execute HTTP requests towards Jetty
This gives you integration tests that can run without any setup of database or application server and that exercises the stack from http down. Since it has no dependencies on external resources, this test runs fine on the build server.
Here some of the code I use:
```
@BeforeClass
public static void startServer() throws Exception {
System.setProperty("hibernate.hbm2ddl.auto", "create");
System.setProperty("hibernate.dialect", "...");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setJdbcUrl("jdbc:hsqldb:mem:mytest");
new org.mortbay.jetty.plus.naming.Resource(
"jdbc/primaryDs", dataSource);
Server server = new Server(0);
WebAppContext webAppContext = new WebAppContext("src/main/webapp", "/");
server.addHandler(webAppContext);
server.start();
webServerPort = server.getConnectors()[0].getLocalPort();
}
// From JWebUnit
private WebTestCase tester = new WebTestCase();
@Before
public void createTestContext() {
tester.getTestContext().setBaseUrl("http://localhost:" + webServerPort + "/");
dao.deleteAll(dao.find(Product.class));
dao.flushChanges();
}
@Test
public void createNewProduct() throws Exception {
String productName = uniqueName("product");
int price = 54222;
tester.beginAt("/products/new.html");
tester.setTextField("productName", productName);
tester.setTextField("price", Integer.toString(price));
tester.submit("Create");
Collection<Product> products = dao.find(Product.class);
assertEquals(1, products.size());
Product product = products.iterator().next();
assertEquals(productName, product.getProductName());
assertEquals(price, product.getPrice());
}
```
For those who'd like to know more, I've written an [article about Embedded Integration Tests with Jetty and JWebUnit](http://today.java.net/pub/a/today/2007/04/12/embedded-integration-testing-of-web-applications.html) on Java.net.
|
Can we use JUNIT for Automated Integration Testing?
|
[
"",
"java",
"unit-testing",
"integration-testing",
""
] |
Is there a way to pass null arguments to C# methods (something like null arguments in c++)?
For example:
Is it possible to translate the following c++ function to C# method:
```
private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
```
|
Yes. There are two kinds of types in .NET: reference types and value types.
References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.
Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.
The usage is slightly different, though.
```
// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
if (arg1.HasValue)
DoSomething();
arg1 = null; // Valid.
arg1 = 123; // Also valid.
DoSomethingWithInt(arg1); // NOT valid!
DoSomethingWithInt(arg1.Value); // Valid.
}
```
|
I think the nearest C# equivalent to `int*` would be `ref int?`. Because `ref int?` allows the called method to pass a value back to the calling method.
`int*`
* Can be null.
* Can be non-null and point to an integer value.
* ***If not null, value can be changed***, and the change propagates to the caller.
* ***Setting to null is not passed back to the caller***.
`ref int?`
* Can be null.
* Can have an integer value.
* ***Value can be always be changed***, and the change propagates to the caller.
* ***Value can be set to null, and this change will also propagate to the caller***.
|
Passing null arguments to C# methods
|
[
"",
"c#",
"methods",
"null",
""
] |
For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:
```
find -type f |
while read file
do
if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]
then
echo "found BOM in: $file"
fi
done
```
Or, if you prefer short, unreadable one-liners:
```
find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done
```
It doesn't work with filenames that contain a line break,
but such files are not to be expected anyway.
Is there any shorter or more elegant solution?
Are there any interesting text editors or macros for text editors?
|
What about this one simple command which not just finds but clears the nasty BOM? :)
```
find . -type f -exec sed '1s/^\xEF\xBB\xBF//' -i {} \;
```
I love "find" :)
**Warning** The above will **modify** binary files which contain those three characters.
If you want just to show BOM files, use this one:
```
grep -rl $'\xEF\xBB\xBF' .
```
|
The best and easiest way to do this on Windows:
[Total Commander](https://en.wikipedia.org/wiki/Total_Commander) → go to project's root dir → find files (`Alt` + `F7`) → file types \*.\* → Find text "EF BB BF" → check 'Hex' checkbox → search
And you get the list :)
|
Elegant way to search for UTF-8 files with BOM?
|
[
"",
"php",
"utf-8",
"shell",
"text-editor",
""
] |
Looking for code samples to access a memory map file in C#
|
Looks like C# 4.0 will have MemoryMappedFile support in the library
|
You can take a look at [this CodeProject article](http://www.codeproject.com/KB/recipes/MemoryMappedGenericArray.aspx) which shows a simple array over MMF implementation using [Winterdom's FileMap library](http://www.winterdom.com/dev/dotnet/index.html) - basically a wrapper around the Win32 APIs for memory mapped files.
Caveat emptor: 1) I have not used FileMap, so I can't vouch for it; 2) FileMap is under LGPL, if the licensing terms are of any concer of you.
You can also search on <http://pinvoke.net> for the P/Invoke definitions of the corresponding Win32 APIs and roll your own implementation.
|
C# accessing memory map file
|
[
"",
"c#",
"memory",
""
] |
I've got a Java application that I'm writing an installer for. We're using the AdvancedInstaller program to create our installer (well, we're evaluating it currently, but will definitely purchase a license soon), and although it has special support for Java applications, it is geared more towards repackaging them as desktop-type apps, and our software is a series of Java services and other utilities which doesn't make sense to distribute in EXE-wrappers. The target audience for this software is very specific, and we know that our software will probably be automatically distributed on freshly-imaged Windows 2003 Server machines. So requiring Java as a prerequisite basically makes more work for some poor sysadmin, and I'd rather avoid that if at all possible by repackaging the JRE's installer inside of our own.
I discovered that if I tried to execute the JRE's installer as a pre-install step from my MSI, it complains that another installer is already running (mine, of course), so it bails out. When I try to add the JRE installer as a software prerequisite in the AdvancedInstaller project (as a bundled EXE, not a URL link), it never seems to actually get installed, despite me trying to force-install it.
What's the best way to repackage the JRE? I'm not really a Java guy, so I don't know too much about how other developers deal with this same problem, short of requiring their users to hunt out and install the JRE on their own. The ideal solution here would be for us to find a EXE installer which can be executed from inside of another MSI installer, or if it's possible, to just package all of the files inside of the JRE and then create the appropriate registry and environment variables. How should I go about doing this?
|
I agree with [bdumitriu's answer](https://stackoverflow.com/questions/271596/how-do-i-properly-repackage-the-jre-installer-in-my-installer#271622):
a simple zip of a jre is enough, unless you want to link that jre to:
* default java (meaning you must add java.exe of the unzipped jre to the path, before any other java path references)
* default java for some script (you could define JAVA\_HOME as referencing your new unzipped jre, but that may have side effects on other script also using JAVA\_HOME before that new JRE)
* file associations like .jnlp or .jar files (this requires some [registry modifications](http://www.tech-archive.net/Archive/WinXP/microsoft.public.windowsxp.help_and_support/2006-01/msg03838.html))
* browser java plugin registration (which requires also registry modifications)
If the last two points do not interest you on the desktop concerned by this deplyment, a simple zip is enough.
|
I have not idea if this is "the way" to do it, but confronted with a somewhat similar problem, we simply archive an *installed* JRE with the rest of our application files and make sure that all our start scripts don't use `java ...`, but rather `..\..\jre\bin\java ...` or similar. The JRE is unpackaged as part of our installation process in a subdirectory of where we install and that's that.
|
How do I properly repackage the JRE installer in my installer?
|
[
"",
"java",
"installation",
""
] |
Given two absolute paths, e.g.
```
/var/data/stuff/xyz.dat
/var/data
```
How can one create a relative path that uses the second path as its base? In the example above, the result should be: `./stuff/xyz.dat`
|
It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.
```
String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"
```
Please note that for file path there's [`java.nio.file.Path#relativize`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Path.html#relativize(java.nio.file.Path)) since Java 1.7, as pointed out by [@Jirka Meluzin](https://stackoverflow.com/users/1113396/jirka-meluzin) in [the other answer](https://stackoverflow.com/a/25743823/537554).
|
Since Java 7 you can use the [relativize](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#relativize%28java.nio.file.Path%29) method:
```
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) {
Path pathAbsolute = Paths.get("/var/data/stuff/xyz.dat");
Path pathBase = Paths.get("/var/data");
Path pathRelative = pathBase.relativize(pathAbsolute);
System.out.println(pathRelative);
}
}
```
Output:
```
stuff/xyz.dat
```
|
How to construct a relative path in Java from two absolute paths (or URLs)?
|
[
"",
"java",
"url",
"file",
"path",
""
] |
I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.
What is going on?
VB.Net version - fails:
```
<TestFixture()> _
Public Class TestClass
<Test()> _
Public Sub EventTest()
Dim eventClass As New EventClass
Dim eventRaised As Boolean = False
AddHandler eventClass.AnEvent, Function() (eventRaised = True)
eventClass.RaiseIt()
Assert.IsTrue(eventRaised)
End Sub
End Class
Public Class EventClass
Public Event AnEvent()
Public Sub RaiseIt()
RaiseEvent AnEvent()
End Sub
End Class
```
C# version - passes:
```
[TestFixture]
public class TestClass
{
[Test]
public void EventTest()
{
var eventClass = new EventClass();
var eventRaised = false;
eventClass.AnEvent += () => { eventRaised = true; };
eventClass.RaiseIt();
Assert.IsTrue(eventRaised);
}
}
public class EventClass
{
public delegate void EventHandler();
public event EventHandler AnEvent;
public void RaiseIt()
{
AnEvent();
}
}
```
|
> **Note:** This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10
The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression `eventRaised = true` is being interpreted as a boolean expression rather than an assignment i.e. is evaluating to false rather than setting to true.
Further details on [MSDN](http://msdn.microsoft.com/en-us/library/bb531253.aspx).
I'm don't think the c# pattern for testing events used in the example can be done in VB.Net without introducing another function e.g.
```
<TestFixture()> _
Public Class Test
<Test()> _
Public Sub EventTest()
Dim eventClass As New EventClass
Dim eventRaised As Boolean = False
AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised))
eventClass.RaiseIt()
Assert.IsTrue(eventRaised)
End Sub
Private Function SetValueToTrue(ByRef value As Boolean) As Boolean
value = True
Return True
End Function
End Class
Public Class EventClass
Public Event AnEvent()
Public Sub RaiseIt()
RaiseEvent AnEvent()
End Sub
End Class
```
|
For those finding this question now: since Visual Basic 2010 (VB 10.0), anonymous `Sub`s do work, so you can write something like:
```
Sub() eventRaised = True
```
|
How to declare lambda event handlers in VB.Net?
|
[
"",
"c#",
"vb.net",
"unit-testing",
"events",
"lambda",
""
] |
I have written a web app in PHP which makes use of Ajax requests (made using YUI.util.Connect.asyncRequest).
Most of the time, this works fine. The request is sent with an **X-Requested-With** value of **XMLHttpRequest**. My PHP controller code uses apache\_request\_headers() to check whether an incoming request is Ajax or not and all works well.
But not always. Intermittently, I'm getting a situation where the Ajax request is sent (and Firebug confirms for me that the headers on the request include an X-Requested-With of XMLHttpRequest) but apache\_request\_headers() is not returning that header in its list.
The output from when I var\_dump the apache\_request\_headers() is as follows (note the lack of X-
```
'Host' => string 'peterh.labs.example.com' (length=26)
'User-Agent' => string 'Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3' (length=105)
'Accept' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63)
'Accept-Language' => string 'en-gb,en;q=0.5' (length=14)
'Accept-Encoding' => string 'gzip,deflate' (length=12)
'Accept-Charset' => string 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' (length=30)
'Keep-Alive' => string '300' (length=3)
'Connection' => string 'keep-alive' (length=10)
'Referer' => string 'http://peterh.labs.example.com/qmail/' (length=40)
'Cookie' => string 'WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6' (length=57)
'Pragma' => string 'no-cache' (length=8)
'Cache-Control' => string 'no-cache' (length=8)
```
But Firebug tells me:
```
Request Headers:
Host peterh.labs.example.com
User-Agent Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3
Accept text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://peterh.labs.example.com/qmail/
Cookie WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6
```
This mismatch is (apparently) intermittent when executing the same code. But I don't believe in "intermittent" when it comes to software! Help!
|
I'm not sure why the apache\_request\_headers() and firebug mismatching, but in order to read request headers you can use the $\_SERVER super global
each header that is being sent by a client (and it doesn't matter how is the client) will arrive to the $*SERVER array.
The key of that header will be with HTTP* prefix, all letters capital and dash is converted to underscore (\_)
in your case you can find your necessary value in:
$\_SERVER['HTTP\_X\_REQUESTED\_WITH'] = 'XMLHttpRequest'
|
For future reference of those coming across this question, the "intermittent" may be due to a redirect happening server-side. If a 302 redirect occurs the X-Requested-With header isn't passed along even though it's been sent in the original request. This may have been the original cause of the problem.
|
PHP apache_request_headers() diagrees with reality (as confirmed by Firebug): why?
|
[
"",
"php",
"ajax",
"http-headers",
"firebug",
""
] |
Does anyone know how to use the [Raw Input](http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx) facility on Windows from a WX Python application?
What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.
|
Have you tried using ctypes?
```
>>> import ctypes
>>> ctypes.windll.user32.RegisterRawInputDevices
<_FuncPtr object at 0x01FCFDC8>
```
It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.
|
Theres a nice looking library here
<http://code.google.com/p/pymultimouse/>
It's not wx-python specific - but it does use raw input in python with ctypes (and worked in my test with 2 mice)
|
WX Python and Raw Input on Windows (WM_INPUT)
|
[
"",
"python",
"windows",
"wxpython",
"raw-input",
""
] |
Some databases support commands such as:
```
SELECT TOP 10 START AT 10 * FROM <TABLE>
```
Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc. Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.
|
Which version of SQL Server?
In SQL Server 2000 this is a real pain (though possible using ugly tricks like that posted by stingyjack).
In 2005 and later it's a little easier- look at the [Row\_Number()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function.
And, depending on your client application it may not even be that hard. Some of the ASP.Net grid controls have support for automatic paging.
|
For [SQL Server 2012](http://msdn.microsoft.com/en-us/library/ms188385%28v=SQL.110%29.aspx)
```
SELECT *
FROM <TABLE>
ORDER BY <SomeCol>
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;
```
|
Is there a 'START AT' equivalent in MS-SQL?
|
[
"",
"sql",
"sql-server",
""
] |
Help!
I have a PHP (PHP 5.2.5) script on HOST1 trying to connect to an MySql database HOST2. Both hosts are in Shared Host environments controlled through CPanel.
HOST2 is set to allow remote database connections from HOST1.
The PHP connect I'm using is:-
$h2 = IPADDRESS;
$dbu = DBUSER;
$dbp = DBPASS;
```
$DBlink = mysql_connect($h2, $dbu, $dbp);
```
This always fails with:-
```
Access denied for user '<dbusername>'@'***SOMESTRING***' (using password: YES)
```
nb: ***SOMESTRING*** looks like it could be something to do with the shared host environment.
Any ideas???
BTW: I can make remote connections to HOST2 from my laptop using OpenOffice via ODBC, and SQLyog. The SQLyog and ODBC settings are exactly the same as the PHP script is trying to use.
|
somestring is probably the reverse-lookup for your web-server.
Can you modify privileges from your cPanel? Have you done anything to allow access from your workstation (ODBC)?
The error-message seems to indicate that you have network-access to the mysql-server, but not privileges for your username from that specific host.
If you're allowed to grant privileges for your database, invoking:
GRANT SELECT ON database.\* TO username@ip.address.of.host1 IDENTIFIED BY 'password'
might work for you. I just wrote this out of my head, you might want to doublecheck the syntax in mysql-docs.
|
* Have you read the MySQL documentation on [Causes of Access denied Errors](http://dev.mysql.com/doc/refman/5.0/en/access-denied.html)?
* Have you contacted support for your hosting provider? They should have access to troubleshoot the database connection. People on the internet do not have access.
* Do you need to specify the database name? Your account might have access to connect only to a specific database. The `mysql_connect()` function does not allow you do specify the database, but [`new mysqli()`](http://php.net/manual/en/mysqli.connect.php) does. I'm not sure if this is relevant -- it might allow you to connect but give you errors when you try to query tables that aren't in your database.
* Are you sure you're using the right password? MySQL allows each account to have a different password per client host. Admittedly, this is not a common configuration, but it's possible. Your hosting provider should be able to tell you.
|
php access to remote database
|
[
"",
"php",
"mysql",
""
] |
There's a lot to C# & ASP.net. Where should I start? What should I not bother focusing on?
Should I learn Winforms then WPF? Ditto for webforms / Silverlight?
Should I learn ASP.MVC or classic ASP.NET? If both, which first?
In the either/or cases - which will make more sense having known the other first?
What major .NET feature(s) should I learn upfront that will open the doors of understanding to what lies ahead?
I am deliberately not mentioning fundamentals like value / reference Types, Classes, object-oriented concepts, etc since they should come first, before specifics. Here, I am interested in specifics.
[edit - added detail of what my goals are]
Good points raised - "what do I want to write"?
Basically, an intranet application that monitors a set of documents and implements a workflow as a change control process. The app will also audit the documents and report problems, self-correcting common errors. A lot of the parameters will need to be end-user definable and pluggable. The document format needs to be adaptable to different proprietary formats although they are fundamentally the same. The app will be very modular.
I'm leaning towards a web interface because the client specs & admin rights will vary - a browser is really the only thing I can count on.
As you can see, it's a bit of everything.
|
I had the same question when I moved from Classic ASP to .NET 2.0... .NET is huge: so where should I start?
What i did was put my hand dirty and started slow, take a project (in my case was a **very important project** - a finance web app that would cover and automatize all 4 persons work) and start to implement, every time I didn't know how to accomplish something or I had an idea in ASP but not in ASP.NET I would go to **[www.asp.net](http://www.asp.net/learn)** or **[4GuysFromRolla](http://www.4GuysFromRolla.com)** website and search for examples, copy/paste, understand what I was doing and ... continue to the next wall.
**Took me 6 month** to have everything up and running but was worst it! now that passed almost 3 years I know I did the right choice but back then ... I was scared!
now... you refer .NET 3.5, it has a bunch of new things like extensions, linq, etc... I would go by the simple part and when the times comes, "maybe I can use LINQ here, let me search how to use it on this part"
hope you follow your own path and **buy some reference book** so you can read something new and have a reference whenever you need "ahhh, I read this somewhere in the book, let me search... where was it?"
I bought [Professional ASP.NET from Wrox](https://rads.stackoverflow.com/amzn/click/com/0764576100) as a reference book, and even today I go there to see new things, even when I'm started to use .NET 3.5, the idea is there, there is only a new way to accomplishing it.
|
What do you want to write? If you want to write a Windows client-side app, look into WinForms and WPF (no real need to learn WinForms before WPF, other than the way that a lot of tutorials/books will probably compare WPF concepts with WinForms concepts). If you're looking at a web app, then ASP.NET or ASP.MVC - I don't know whether you really need the "normal" ASP.NET before MVC.
Silverlight is a bit of both, in a way - rich client probably talking to a server for interesting data etc.
Before learning any of these though, I suggest you learn the fundamentals which are one step up from the topics you mentioned - things like how text works in .NET (including encodings and regular expressions), I/O, perhaps threading. Oh, and LINQ :) There are a few books which are very good on this front:
* [C# 3.0 in a Nutshell](https://rads.stackoverflow.com/amzn/click/com/0596527578)
* [CLR via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632)
* [Accelerated C# 2008](https://rads.stackoverflow.com/amzn/click/com/1590598733)
|
Learning C#, ASP.NET 3.5 - what order should I learn in / what to skip?
|
[
"",
"c#",
".net",
"asp.net",
""
] |
I am instantiating a local COM server using CoCreateInstance. Sometimes the application providing the server takes a long time to start. When this happens, Windows pops a dialog box like this:
**Server Busy**
The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy program and correct the problem.
[Switch To...] [Retry] [Cancel]
I have found mention of a Visual Basic property on the Application object, OleRequestPendingTimeout, that can be used to control the time before this dialog comes up. I can't find any good documentation on this or an equivalent that is useful from C++. Can anyone point me in the right direction?
|
If you're using MFC, we used to do stuff like this:
```
// prevent the damned "Server Busy" dialog.
AfxOleGetMessageFilter()->EnableBusyDialog(0);
AfxOleGetMessageFilter()->EnableNotRespondingDialog(0);
```
|
Have a look at `IMessageFilter` and `CoRegisterMessageFilter`.
|
Set OLE Request Timeout from C++
|
[
"",
"c++",
"com",
"ole",
""
] |
We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows?
Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?
|
Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like
```
java ...
```
This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable `JAVA6HOME` with the value `C:\java\java6` (if Java 6 is installed in this directory) and change the batch file calling
```
%JAVA6HOME%\bin\java ...
```
|
I was appalled at the clumsiness of the CLASSPATH, JAVA\_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.
Article by: Ted Neward: [Multiple Java Homes: Giving Java Apps Their Own JRE](http://www.tedneward.com/files/Papers/MultipleJavaHomes/MultipleJavaHomes.pdf)
> With the exponential growth of Java as a server-side development language has come an equivablent
> exponential growth in Java development tools, environments, frameworks, and extensions.
> Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some
> require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above,
> some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0
> days, others require the "javax.swing" package names.
>
> Worse yet, this problem can be found even within the corporate enterprise, as systems developed using
> Java from just six months ago may suddenly "not work" due to the installation of some Java Extension
> required by a new (seemingly unrelated) application release. This can complicate deployment of Java
> applications across the corporation, and lead customers to wonder precisely why, five years after the
> start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes,
> we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the
> infamous "DLL-Hell" problem just described.)
>
> This paper describes how to configure a Java installation such that a given application receives its own,
> private, JRE, allowing multiple Java environments to coexist without driving customers (or system
> administrators) insane...
|
Multiple Java versions running concurrently under Windows
|
[
"",
"java",
""
] |
My requirement is I have server J2EE web application and client J2EE web application. Sometimes client can go offline. When client comes online he should be able to synchronize changes to and fro. Also I should be able to control which rows/tables need to be synchronized based on some filters/rules. Is there any existing Java frameworks for doing it? If I need to implement on my own, what are the different strategies that you can suggest?
One solution in my mind is maintaining sql logs and executing same statements at other side during synchronization. Do you see any problems with this strategy?
|
There are a number of Java libraries for data synchronizing/replication. Two that I'm aware of are [daffodil](http://opensource.replicator.daffodilsw.com/) and [SymmetricDS](http://www.symmetricds.org/). In a previous life I foolishly implemented (in Java) my own data replication process. It seems like the sort of thing that should be fairly straightforward, but if the data can be updated in multiple places simultaneously, it's hellishly complicated. I strongly recommend you use one of the aforementioned projects to try and bypass dealing with this complexity yourself.
|
The biggist issue with synchronization is when the user edits something offline, and it is edited online at the same time. You need to merge the two changed pieces of data, or deal with the UI to allow the user to say which version is correct. If you eliminate the possibility of both being edited at the same time, then you don't have to solve this sticky problem.
The method is usually to add a field 'modified' to all tables, and compare the client's modified field for a given record in a given row, against the server's modified date. If they don't match, then you replace the server's data.
Be careful with autogenerated keys - you need to make sure your data integrity is maintained when you copy from the client to the server. Strictly running the SQL statements again on the server could put you in a situation where the autogenerated key has changed, and suddenly your foreign keys are pointing to different records than you intended.
Often when importing data from another source, you keep track of the primary key from the foreign source as well as your own personal primary key. This makes determining the changes and differences between the data sets easier for difficult synchronization situations.
|
Strategy for Offline/Online data synchronization
|
[
"",
"java",
"database",
"jakarta-ee",
"data-synchronization",
""
] |
I have the following file/line:
```
pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200
```
and so on.
I wish to parse this and take the key value pairs and put them in a structure:
```
struct pky
{
pky() :
a_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fr(0),
g('U'),
a(0),
pc(0),
p_id(0)
{ }
};
```
wherein either all the structure fields are used or some might be omitted.
How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work.
Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.
|
You can do something like this:
```
std::string line;
std::map<std::string, std::string> props;
std::ifstream file("foo.txt");
while(std::getline(file, line)) {
std::string token;
std::istringstream tokens(line);
while(tokens >> token) {
std::size_t pos = token.find('=');
if(pos != std::string::npos) {
props[token.substr(0, pos)] = token.substr(pos + 1);
}
}
/* work with those keys/values by doing properties["name"] */
Line l(props["pc"], props["ct"], ...);
/* clear the map for the next line */
props.clear();
}
```
i hope it's helpful. Line can be like this:
```
struct Line {
std::string pc, ct;
Line(std::string const& pc, std::string const& ct):pc(pc), ct(ct) {
}
};
```
now that works only if the delimiter is a space. you can make it work with other delimiters too. change
```
while(tokens >> token) {
```
into for example the following, if you want to have a semicolon:
```
while(std::getline(tokens, token, ';')) {
```
actually, it looks like you have only integers as values, and whitespace as delimiters. you might want to change
```
std::string token;
std::istringstream tokens(line);
while(tokens >> token) {
std::size_t pos = token.find('=');
if(pos != std::string::npos) {
props[token.substr(0, pos)] = token.substr(pos + 1);
}
}
```
into this then:
```
int value;
std::string key;
std::istringstream tokens(line);
while(tokens >> std::ws && std::getline(tokens, key, '=') &&
tokens >> std::ws >> value) {
props[key] = value;
}
```
`std::ws` just eats whitespace. you should change the type of props to
```
std::map<std::string, int> props;
```
then too, and make Line accept int instead of std::string's. i hope this is not too much information at once.
|
This is the perfect place to define the stream operators for your structure:
```
#include <string>
#include <fstream>
#include <sstream>
#include <istream>
#include <vector>
#include <algorithm>
#include <iterator>
std::istream& operator>> (std::istream& str,pky& value)
{
std::string line;
std::getline(str,line);
std::stringstream dataStr(line);
static const std::streamsize max = std::numeric_limits<std::streamsize>::max();
// Code assumes the ordering is always as follows
// pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
dataStr.ignore(max,'=') >> value.pc;
dataStr.ignore(max,'=') >> value.ct_id;
dataStr.ignore(max,'=') >> value.a; // Guessing av=
dataStr.ignore(max,'=') >> value.cv_id;
dataStr.ignore(max,'=') >> value.cp_id;
dataStr.ignore(max,'=') >> value.fr; // Guessing rec=
dataStr.ignore(max,'=') >> value.p_id;
dataStr.ignore(max,'=') >> value.g;
dataStr.ignore(max,'=') >> value.a_id;
dataStr.ignore(max,'=') >> value.sz_id;
dataStr.ignore(max,'=') >> value.cr_id;
return str;
}
int main()
{
std::ifstream file("plop");
std::vector<pky> v;
pky data;
while(file >> data)
{
// Do Somthing with data
v.push_back(data);
}
// Even use the istream_iterators
std::ifstream file2("plop2");
std::vector<pky> v2;
std::copy(std::istream_iterator<pky>(file2),
std::istream_iterator<pky>(),
std::back_inserter(v2)
);
}
```
|
Parse a file using C++, load the value to a structure
|
[
"",
"c++",
"file",
"parsing",
""
] |
I was reading *[Java Platform Performance](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html)* (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.
I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that.
Do recent JVMs, in particular Sun's 1.6.0\_07 version, still have this limitation? If so, then I have a lot of code to analyse...
I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC.
---
As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected.
This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope.
The code from the [chosen answer](https://stackoverflow.com/a/271824/7938) illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference.
This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.
|
This code should clear it up:
```
public class TestInvisibleObject{
public static class PrintWhenFinalized{
private String s;
public PrintWhenFinalized(String s){
System.out.println("Constructing from "+s);
this.s = s;
}
protected void finalize() throws Throwable {
System.out.println("Finalizing from "+s);
}
}
public static void main(String[] args) {
try {
PrintWhenFinalized foo = new PrintWhenFinalized("main");
} catch (Exception e) {
// whatever
}
while (true) {
// Provoke garbage-collection by allocating lots of memory
byte[] o = new byte[1024];
}
}
}
```
On my machine (jdk1.6.0\_05) it prints:
> Constructing from main
>
> Finalizing from main
So it looks like the problems has been fixed.
Note that using System.gc() instead of the loop does not cause the object to be collected for some reason.
|
The problem is still there. I tested it with Java 8 and could prove it.
You should note the following things:
1. The only way to force a guaranteed garbage collection is to try an allocation which ends in an OutOfMemoryError as the JVM is required to try freeing unused objects before throwing. This however does not hold if the requested amount is too large to ever succeed, i.e. excesses the address space. Trying to raise the allocation until getting an OOME is a good strategy.
2. The guaranteed GC described in Point 1 does not guaranty a finalization. The time when finalize() methods are invoked is not specified, they might be never called at all. So adding a finalize() method to a class might prevent its instances from being collected, so finalize is not a good choice to analyse GC behavior.
3. Creating another new local variable after a local variable went out of scope will reuse its place in the stack frame. In the following example, object a will be collected as its place in the stack frame is occupied by the local variable b. But b last until the end of the main method as there is no other local variable to occupy its place.
```
import java.lang.ref.*;
public class Test {
static final ReferenceQueue<Object> RQ=new ReferenceQueue<>();
static Reference<Object> A, B;
public static void main(String[] s) {
{
Object a=new Object();
A=new PhantomReference<>(a, RQ);
}
{
Object b=new Object();
B=new PhantomReference<>(b, RQ);
}
forceGC();
checkGC();
}
private static void forceGC() {
try {
for(int i=100000;;i+=i) {
byte[] b=new byte[i];
}
} catch(OutOfMemoryError err){ err.printStackTrace();}
}
private static void checkGC() {
for(;;) {
Reference<?> r=RQ.poll();
if(r==null) break;
if(r==A) System.out.println("Object a collected");
if(r==B) System.out.println("Object b collected");
}
}
}
```
|
Are invisible references still an issue in recent JVMs?
|
[
"",
"java",
"memory-leaks",
"garbage-collection",
"jvm",
"sun",
""
] |
Is there any reason why I should pick JSON over XML, or vice-versa if both are available? Tips for optimizing performance when dealing with data feeds are also appreciated!
|
When it comes to PHP the one reason I choose XML over JSON is because even in PHP 5 there is no officially supported API for traversal. You can encode, and you can decode, and that is it. There is no validation, no efficient way to traverse key/value pairs, and all-in-all, very little support for it. Don't get me wrong, you can just use a foreach looping structure, but it really is cumbersome. JSON was touted as a great data-interchange format because JavaScript has an easy time understanding the lexical structure. So when you go from PHP to JavaScript, it is great, but when you go from JavaScript to PHP, or PHP to PHP, then JSON is not the best choice for data interchange.
|
I would go with JSON myself, simply because XML is very bloaty and excessively difficult to parse. JSON is small and neat, and thus saves on bandwidth, and should also speed up response times simply because it's easier to generate, faster to transmit, and quicker to decode.
|
Which is faster for PHP to deal with/easier to work with in PHP; XML or JSON, and file_get_contents or cURL?
|
[
"",
"php",
"json",
"xml",
""
] |
Having some Geometry data and a Transform how can the transform be applied to the Geometry to get a new Geometry with it's data transformed ?
Ex: I Have a Path object that has it's Path.Data set to a PathGeometry object, I want to tranform **the points** of the PathGeometry object **in place** using a transform, and not apply a transform to the PathGeometry that will be used at render time.
P.S. I know that the Transform class has a method `Point Transform.Transform(Point p)` that can be used to transform a Point but...is there a way to transform a arbitrary geometry at once?
Edit:
See my repply for a currently found [solution](https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250913)
|
You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work.
Here is a sample that worked for me.
```
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));
ScaleTransform transform = new ScaleTransform(2, 2);
PathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);
```
|
I've found a solution with which arbitrary tranform can be applied to a path geometry, thanks to [Todd White](https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250587)'s answer:
Basically Geometry.Combine is used to combine the desired geometry with Geometry.Empty using Union, and the desired transform is given. The resulting geometry is transformed with the given transform.
```
PathGeometry geometryTransformed = Geometry.Combine(Geometry.Empty, geometry, GeometryCombineMode.Union, transform);
```
|
WPF: How to apply a GeneralTransform to a Geometry data and return the new geometry?
|
[
"",
"c#",
".net",
"wpf",
"geometry",
"transform",
""
] |
My WinForms app uses a number of [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) objects to retrieve information from a database. I'm using BackgroundWorker because it allows the UI to remain unblocked during long-running database queries and it simplifies the threading model for me.
I'm getting occasional DatabaseExceptions in some of these background threads, and I have witnessed at least one of these exceptions in a worker thread while debugging. I'm fairly confident these exceptions are timeouts which I suppose its reasonable to expect from time to time.
My question is about what happens when an unhandled exception occurs in one of these background worker threads.
I don't think I can catch an exception in another thread, but can I expect my WorkerCompleted method to be executed? Is there any property or method of the BackgroundWorker I can interrogate for exceptions?
|
If the operation raises an exception that your code does not handle, the `BackgroundWorker` catches the exception and passes it into the `RunWorkerCompleted` event handler, where it is exposed as the Error property of `System.ComponentModel.RunWorkerCompletedEventArgs`. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised.
<http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx>
|
I am fully using `BackgroundWorker` over a years and really know it in deep.
Just recently, My `RunWorkerCompleted` does not catch the `e.Error` when I simply `Throw New Exception("Test")` in `DoWork`. However Unhandled Exception raised. Catch in `DoWork` is not the best practice thus `e.Error` got no meaning.
When I try to create new `Form` with new `BackgroundWorker`, `e.Error` in `RunWorkerCompleted` handled successfully. There should be something wrong in my complicated `BackgroundWorker`.
After a few days googling and debugging, trying an error. I found this in my `RunWorkerCompleted`:
* Check for `e.Error` first, then `e.Cancelled` and lastly `e.Result`
* Do not get the `e.Result` if `e.Cancelled = True`.
* Do not get the `e.Result` if `e.Error` is not `null` (or `Nothing`) \*\*
\*\* This is where I miss. If you trying to use `e.Result` if `e.Error` is not `null` (or `Nothing`), Unhandled Exception will thrown.
---
**UPDATE:**
In the `e.Result` get property .NET design it to check for `e.Error` first, if got error, then they will re-throw the same exception from `DoWork`. That is why we get Unhandled exception in `RunWorkerCompleted` but actually the exception is come from `DoWork`.
Here is the best practice to do in `RunWorkerCompleted`:
```
If e.Error IsNot Nothing Then
' Handle the error here
Else
If e.Cancelled Then
' Tell user the process canceled here
Else
' Tell user the process completed
' and you can use e.Result only here.
End If
End If
```
If you want an object that accessible to all DoWork, ProgressChanged and RunWorkerCompleted, use like this:
```
Dim ThreadInfos as Dictionary(Of BackgroundWorker, YourObjectOrStruct)
```
You can easily access `ThreadInfos(sender).Field` anywhere you want.
|
Unhandled exceptions in BackgroundWorker
|
[
"",
"c#",
".net",
"multithreading",
"debugging",
"backgroundworker",
""
] |
Is there a possible htaccess directive that can transparently forward request from index.php to index\_internal.php if the request is coming from an internal ip range?
|
```
RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\. [OR]
RewriteCond %{REMOTE_ADDR} ^10\.15\.
RewriteRule ^index\.php$ index_internal.php [R,NC,QSA,L]
```
What this does:
start mod\_rewrite engine (you may have that already)
if (client IP address starts with "192.168.1." [or]
client IP address starts with "10.15.")
and page name is index.php ([n]ot [c]ase sensitive), [r]edirect to index\_internal.php, [q]uery [s]tring [a]ppend (i.e. `index.php?foo=bar` becomes `index_internal.php?foo=bar`), [l]eave processing.
Modify as needed for IP address blocks.
|
Something like this should do it (obviously change the IP address to match your network):
```
RewriteCond %{REMOTE_ADDR} ^192\.168\.
RewriteRule index.php index_internal.php
```
If you want an actual header then make it `RewriteRule index.php index_internal.php [L,R,QSA]`
|
htaccess request forwarding if internal ip
|
[
"",
"php",
".htaccess",
"forwarding",
""
] |
I'm not talking about a pointer to an instance, I want a pointer to a class itself.
|
In C++, classes are not "[first class objects](http://en.wikipedia.org/wiki/First-class_object)". The closest you can get is a pointer to its `type_info` instance.
|
No. A pointer is the address of something in the memory of the computer at run-time. A class is just a set of instructions to the compiler.
|
In C++ You Can Have a Pointer to a Function, Can you also have a pointer to a class?
|
[
"",
"c++",
"class",
"pointers",
""
] |
I want to create a file on the webserver dynamically in PHP.
First I create a directory to store the file. THIS WORKS
```
// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user
```
Now I want to create a file called index.php and write out some content into it.
I am trying:
```
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");
fclose($ourFileHandle);
// append data to it
$ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file");
$stringData = "Hi";
fwrite($ourFileHandle, $stringData);
```
But it never gets past the `$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");` Saying the file does not exist, but that is the point. I want to create it.
I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php
Does anyone have any thoughts on what I am doing wrong?
PHP 5 on a linux server I believe.
-Jason
|
First you do :
```
$dirToCreate = "..".$_SESSION['s_USER_URL'];
```
But the filename you try to write to is not prefixed with the '..', so try changing
```
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
```
to
```
$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';
```
or probably tidier:
```
$ourFileName = $dirToCreate . '/index.php';
```
You are probably getting the warning because the directory you are trying to write the file into does not exist
|
It could be a result of one of your php ini settings, or possibly an apache security setting.
Try creating the dir as only rwxr-x--- and see how that goes.
I recall a shared hosting setup where "safemode" was compiled in and this behaviour tended to occur, basically, if the files/dirs were writable by too many people they would magically stop being acessible.
Its probably doc'd in php, but ill have to check.
|
php: writing files
|
[
"",
"php",
"file-io",
""
] |
On my current project, I came across our master DB script. Taking a closer look at it, I noticed that all of our original primary keys have a data type of **numeric(38,0)**.
We are running SQL Server 2005 as our primary DB platform.
For a little context, we support both Oracle and SQL Server as our back-end. In Oracle, our primary keys have a data type of **number(38,0).**
Does anybody know of possible side-effects and performance impact of such implementation? I have always advocated and implemented *int* or *bigint* as primary keys and would love to know if numeric(38,0) is a better alternative.
|
Well, you *are* spending more data to store numbers that you will never really reach.
bigint goes up to 9,223,372,036,854,775,807 in 8 Bytes
int goes up to 2,147,483,647 in 4 bytes
A NUMERIC(38,0) is going to take, if I am doing the math right, 17 bytes.
Not a huge difference, but: smaller datatypes = more rows in memory (or fewer pages for the same # of rows) = fewer disk I/O to do lookups (either indexed or data page seeks). Goes the same for replication, log pages, etc.
For SQL Server: INT is an IEEE standard and so is easier for the CPU to compare, so you get a slight performance increase by using INT vs. NUMERIC (which is a packed decimal format). (Note in Oracle, if the current version matches the older versions I grew up on, ALL datatypes are packed so an INT inside is pretty much the same thing as a NUMERIC( x,0 ) so there's no performance difference)
So, in the grand scheme of things -- if you have lots of disk, RAM, and spare I/O, use whatever datatype you want. If you want to get a little more performance, be a little more conservative.
Otherwise at this point, I'd leave it as it is. No need to change things.
|
This is overly large because you are never going to have that many rows. The larger size will result in more storage space. This is not a big deal in itself but will also mean more disk reads to retrieve data from a table or index. It will mean less rows will fit into memory on the database server.
I don't think it's broken enough to be bothered fixing.
|
numeric(38,0) as primary key column; good, bad, who cares?
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
"primary-key",
""
] |
This is related to some other questions, such as: [this](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and some of my other questions.
In [this question](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and others, we see we can declare and initialise string arrays in one nice step, for example:
```
const char* const list[] = {"zip", "zam", "bam"}; //from other question
```
This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.
What I want to do is to have an array like this as as member of a class I am using, something like this:
```
class DataProvider : public SomethingElse
{
const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
public:
DataProvider();
~DataProvider();
char* GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
```
But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?
|
Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
```
class DataProvider : public SomethingElse
{
static const char* const mStringData[];
public:
DataProvider();
~DataProvider();
const char* const GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
```
In the .cpp file:
```
const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
```
|
This is not possible in C++. You cannot directly initialize the array. Instead you have to give it the size it will have (4 in your case), and you have to initialize the array in the constructor of DataProvider:
```
class DataProvider {
enum { SIZEOF_VALUES = 4 };
const char * values[SIZEOF_VALUES];
public:
DataProvider() {
const char * const v[SIZEOF_VALUES] = {
"one", "two", "three", "four"
};
std::copy(v, v + SIZEOF_VALUES, values);
}
};
```
Note that you have to give up on the const-ness of the pointers in the array, since you cannot directly initialize the array. But you need to later set the pointers to the right values, and thus the pointers need to be modifiable.
If your values in the array are const nevertheless, the only way is to use a static array:
```
/* in the header file */
class DataProvider {
enum { SIZEOF_VALUES = 4 };
static const char * const values[SIZEOF_VALUES];
};
/* in cpp file: */
const char * const DataProvider::values[SIZEOF_VALUES] =
{ "one", "two", "three", "four" };
```
Having the static array means all objects will share that array. Thus you will have saved memory too.
|
How do you declare arrays in a c++ header?
|
[
"",
"c++",
"arrays",
"header",
"initialization",
"constants",
""
] |
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.
I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.
I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?
```
MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...
```
|
Use the [KeyValuePair](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class for you Key and Value, then just serialize a [List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) to disk with an [XMLSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx).
That would be the simplest approach I feel. You wouldn't have to worry about traversing nodes. Calling the Deserialize function will do that for you. The user could edit the values in the file if they wish also.
|
If you're looking for a quick easy function and don't want to use .Net app\user config setting files or worry about serialization issues that sometimes occur of time.
The following static function can load a file formatted like `KEY=VALUE`.
```
public static Dictionary<string, string> LoadConfig(string settingfile)
{
var dic = new Dictionary<string, string>();
if (File.Exists(settingfile))
{
var settingdata = File.ReadAllLines(settingfile);
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx+1);
if (!dic.ContainsKey(skey))
{
dic.Add(skey, svalue);
}
}
}
}
return dic;
}
```
*Note: I'm using a Dictionary so keys must be unique, which is usually that case with setting.*
USAGE:
```
var settingfile = AssemblyDirectory + "\\mycustom.setting";
var settingdata = LoadConfig(settingfile);
if (settingdata.ContainsKey("lastrundate"))
{
DateTime lout;
string svalue;
if (settingdata.TryGetValue("lastrundate", out svalue))
{
DateTime.TryParse(svalue, out lout);
lastrun = lout;
}
}
```
|
Simplest possible key/value pair file parsing in .NET
|
[
"",
"c#",
".net",
"key-value",
""
] |
I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:
* application.py - holds the primary application class (most functional routines)
* gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.
* command.py - holds command line automation functions not dependent on data in the application class
* state.py - holds the state data persistence class
This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.
I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.
Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?
**EDIT I**
Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.
Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.
Thanks for the responses so far.
|
In the project [Wader](http://wader-project.org) we use [python gtkmvc](http://pygtkmvc.sourceforge.net/), that makes much easier to apply the MVC patterns when using pygtk and glade, you can see the file organization of our project in the [svn repository](http://trac.wader-project.org/browser/trunk/wader):
```
wader/
cli/
common/
contrib/
gtk/
controllers/
models/
views/
test/
utils/
```
|
"holds the primary application class (most functional routines)"
As in singular -- one class?
I'm not surprised that the **One Class Does Everything** design isn't working. It might not be what I'd call object-oriented. It doesn't sound like it follows the typical MVC design pattern if your functionality is piling up in a single class.
What's in this massive class? I suggest that you can probably refactor this into pieces. You have two candidate dimensions for refactoring your application class -- if, indeed, I've guessed right that you've put everything into a single class.
1. Before doing anything else, refactor into components that parallel the Real World Entities. It's not clear what's in your "state.py" -- wether this is a proper model of real-world entities, or just mappings between persistent storage and some murky data structure in the application. Most likely you'd move processing out of your application and into your model (possibly state.py, possibly a new module that is a proper model.)
Break your model into pieces. It will help organize the control and view elements. The most common MVC mistake is to put too much in control and nothing in the model.
2. Later, once your model is doing most of the work, you can look at refactor into components that parallel the GUI presentation. Various top-level frames, for example, should probably have separate cotrol objects. It's not clear what's in "GUI.py" -- this might be a proper view. What appears to be missing is a Control component.
|
How do I coherently organize modules for a PyGTK desktop application?
|
[
"",
"python",
"gtk",
"module",
"pygtk",
"organization",
""
] |
I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields.
This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this takes a considerable time (31s). I can improve this with ~50% by using the generic lists Find(Predicate) method.
```
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace ExperimentFW3
{
public class PropValue
{
public string Name;
public decimal Val;
public decimal Total;
}
public class Adjustment
{
public string PropName;
public decimal AdjVal;
}
class Program
{
static List<PropValue> propList;
static List<Adjustment> adjList;
public static void Main()
{
propList = new List<PropValue>{
new PropValue{Name = "Alfa", Val=2.1M},
new PropValue{Name = "Beta", Val=1.0M},
new PropValue{Name = "Gamma", Val=8.0M}
};
adjList = new List<Adjustment>{
new Adjustment{PropName = "Alfa", AdjVal=-0.1M},
new Adjustment{PropName = "Beta", AdjVal=3M}
};
foreach (var p in propList)
{
Adjustment a = adjList.SingleOrDefault(
av => av.PropName.Equals(p.Name)
);
if (a != null)
p.Total = p.Val + a.AdjVal;
else
p.Total = p.Val;
}
}
}
}
```
The desired result is: Alfa total=2,Beta total=4,Gamma total=8
But I wonder if this is possible to do even faster. Inner joining the two lists takes very little time, even when looping over 20k items in the resultset.
```
var joined = from p in propList
join a in adjList on p.Name equals a.PropName
select new { p.Name, p.Val, p.Total, a.AdjVal };
```
So my question is if it's possible to do something like I would do with T-SQL? An UPDATE from a left join using ISNULL(val,0) on the adjustment value.
|
That join should be fairly fast, as it will first loop through all of `adjList` to create a lookup, then for each element in `propList` it will just use the lookup. This is faster than your O(N \* M) method in the larger code - although that could easily be fixed by calling [`ToLookup`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx) (or [`ToDictionary`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx) as you only need one value) on `adjList` before the loop.
EDIT: Here's the modified code using `ToDictionary`. Untested, mind you...
```
var adjDictionary = adjList.ToDictionary(av => av.PropName);
foreach (var p in propList)
{
Adjustment a;
if (adjDictionary.TryGetValue(p.Name, out a))
{
p.Total = p.Val + a.AdjVal;
}
else
{
p.Total = p.Val;
}
}
```
|
If adjList might have duplicate names, you should group the items before pushing to dictionary.
```
Dictionary<string, decimal> adjDictionary = adjList
.GroupBy(a => a.PropName)
.ToDictionary(g => g.Key, g => g.Sum(a => a.AdjVal))
propList.ForEach(p =>
{
decimal a;
adjDictionary.TryGetValue(p.Name, out a);
p.Total = p.Val + a;
});
```
|
Better performance on updating objects with linq
|
[
"",
"c#",
"linq",
"performance",
"optimization",
"linq-to-objects",
""
] |
I try get the [mp3 flash player](http://flash-mp3-player.net/players/js/) to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.
After trying to find out I found this in the reference code:
```
<!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->
```
How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?
|
That syntax, with the <script> tag with the "event" and "for" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object. Here, it adds a FSCommand event handler to the myFlash object. This is needed because code running inside the Flash object may want to run JavaScript in the browser. To do this, the Flash object will invoke the FSCommand event handler, passing the JavaScript to run as the arguments to the event.
With this player, the name of a JS listener object is passed in the FlashVars param to the player. It then uses FSCommands from ActionScript to modify that listener object, with an occasional call to a method on that listener when it's other properties have been modified. I suppose that IE isn't able to run the JS code using this method until the FSCommand handler has been added to the Flash player object, which is why that code exists. Modify it to use the ID of your Flash object and you should be in good shape.
|
Maybe this is more about embedding flash dynamically.
I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, only document.write worked. But document.write can't really be used after the page has loaded, unless it is targeted in an iframe or some other devil worship mechanism.
What's good tho, is that IE doesn't distinguish between assigning an event handler in this bastard script tag or programatically. This means that:
```
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
```
in IE directly translates to:
```
function foo(command, args){
eval(args);
}
var ie_sucks = document.getElementById('myFlash');
ie_sucks.attachEvent("FSCommand", foo);
```
|
flash fscommands and javascript
|
[
"",
"javascript",
"jquery",
"flash",
"internet-explorer",
""
] |
ExtJS has Ext.each() function, but is there a map() also hidden somewhere?
I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.
Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:
```
Ext.map = function(arr, f) { ... };
```
But is this really the correct way to do this?
|
It appears, that my colleges here are using [ext-basex](http://code.google.com/p/ext-basex/), which extends Array.prototype with map() and other methods.
So I can just write:
```
[1, 2, 3].map( function(){ ... } );
```
Problem solved.
|
As of at least Ext4, Ext.Array.map is included.
<http://docs.sencha.com/extjs/5.0.1/#!/api/Ext.Array-method-map>
|
Is there a map() function in ExtJS?
|
[
"",
"javascript",
"dictionary",
"extjs",
""
] |
In the past people used to wrap HTML comment tags around blocks of JavaScript in order to prevent "older" browsers from displaying the script. Even Lynx is smart enough to ignore JavaScript, so why do some people keep doing this? Are there any valid reasons these days?
```
<script type="text/javascript">
<!--
//some js code
//-->
</script>
```
Edit: There is ONE situation I did encounter. Some code editors, such as Dreamweaver, get confused by quoted HTML inside a JavaScript string when in "design view" and try to display it as part of your page.
|
No, absolutely not. Any user agent, search engine spider, or absolutely anything else these days is smart enough to ignore Javascript if it can't execute it.
There was only a very brief period when this was at all helpful, and it was around 1996.
|
There isn't a good reason to do this anymore, as the browsers which required this have by and large disappeared from the web.
In fact, doing this can actually cause unintended problems with certain older browsers' attempts to interpret the page if it uses XHTML - from [developer.mozilla.org](http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents#Use_of_Comments_Inside_Inline_style_and_script):
> * Mozilla 1.1+/Opera 7
>
> Do not apply CSS or execute the JavaScript.
> * Netscape 7.0x/Mozilla 1.0.x
>
> Do not apply CSS but does execute the JavaScript.
> * Internet Explorer 5.5+
>
> Can not display the document.
That site also links to examples of the [several](http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents/Examples#Problem_2) [problems](http://developer.mozilla.org/en/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents/Examples#Problem_3) mentioned above.
|
Does it still make sense to use HTML comments on blocks of JavaScript?
|
[
"",
"javascript",
"html",
""
] |
Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was:
```
Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects
```
The developers assure me they had good reason for all the empty catch blocks, that sometimes the try with empty catch blocks are just there to ignore useless exceptions and keep the application from crashing. I feel this is a cop out and complete BS. Some of the examples I actually looked up were database calls where the record was being saved to the database, and in this case, if an exception was ignored, the user would get back an okay prompt, think everything was okay, and continue on with their work. In reality, their work was never saved. I think this is absolutely the most horrible kind of error. In this case, they are completely wrong in throwing that code in a try with an empty catch block. But my question is, "Is this EVER acceptable in ANY situation?" I think not, but I've been known to be wrong.
|
While there are some reasonable reasons for ignoring exceptions; however, generally it is only specific exceptions that you are able to safely ignore. As noted by [Konrad Rudolph](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204827), you might have to catch and swallow an error as part of a framework; and as noted by [osp70](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204873), there might be an exception generated by a framework that you know you can ignore.
In both of these cases though, you will likely know the exception type and if you know the type then you should have code similar to the following:
```
try {
// Do something that might generate an exception
} catch (System.InvalidCastException ex) {
// This exception is safe to ignore due to...
} catch (System.Exception ex) {
// Exception handling
}
```
In the case of your application, is sounds like something similar might apply in some cases; but the example you give of a database save returning an "OK" even when there is an exception is not a very good sign.
|
I don't catch exceptions unless I plan to do something about them. Ignoring them isn't doing something about them.
|
Is there any valid reason to ever ignore a caught exception
|
[
"",
"c#",
"exception",
""
] |
Situation:
* text: a string
* R: a regex that matches part of the string. This might be expensive to calculate.
I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:
```
import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
```
This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well.
|
```
import re
r = re.compile("[ab]")
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
replaced = []
pos = 0
for m in r.finditer(text):
matches.append(m.group(0))
replaced.append(text[pos:m.start()])
pos = m.end()
replaced.append(text[pos:])
print matches
print ''.join(replaced)
```
Outputs:
```
['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
cdedfe flijijie lifsjelifjl
```
|
What about this:
```
import re
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
ab_re = re.compile( "[ab]" )
def verboseTest( m ):
matches.append( m.group(0) )
return ''
textWithoutMatches = ab_re.sub( verboseTest, text )
print matches
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
print textWithoutMatches
# cdedfe flijijie lifsjelifjl
```
The 'repl' argument of the **re.sub** function can be a function so you can report or save the matches from there and whatever the function returns is what 'sub' will substitute.
The function could easily be modified to do a lot more too! Check out [the re module documentation](http://docs.python.org/library/re.html#module-contents) on docs.python.org for more information on what else is possible.
|
Capture the contents of a regex and delete them, efficiently
|
[
"",
"python",
"regex",
""
] |
I have a List of beans, each of which has a property which itself is a List of email addresses.
```
<c:forEach items="${upcomingSchedule}" var="conf">
<div class='scheduled' title="${conf.subject}" id="scheduled<c:out value="${conf.id}"/>">
...
</div>
</c:forEach>
```
This renders one `<div>` per bean in the List.
For the sublist, what I'd like to be able to do is to concatenate each of the entries in the list to form a single String, to be displayed as a part of the `<div>`'s `title` attribute. Why? Because we are using a javascript library (mootools) to turn this `<div>` into a floating tool tip, and the library turns the `title` into the text of the tooltip.
So, if `${conf.subject}` was "Subject", ultimately I'd like the `title` of the `<div>` to be "Subject: blah@blah.com, blah2@blah2.com, etc.", containing all of the email addresses of the sub-list.
How can I do this using JSP EL? I'm trying to stay away from putting scriptlet blocks in the jsp file.
|
Figured out a somewhat dirty way to do this:
```
<c:forEach items="${upcomingSchedule}" var="conf">
<c:set var="title" value="${conf.subject}: "/>
<c:forEach items="${conf.invitees}" var="invitee">
<c:set var="title" value="${title} ${invitee}, "/>
</c:forEach>
<div class='scheduled' title="${title}" id="scheduled<c:out value="${conf.id}"/>">
...
</div>
</c:forEach>
```
I just use `<c:set>` repeatedly, referencing it's own value, to append/concatenate the strings.
|
The "clean" way to do this would be to use a function. As the JSTL `join` function won't work on a `Collection`, you can write your own without too much trouble, and reuse it all over the place instead of cut-and-pasting a large chunk of loop code.
You need the function implementation, and a TLD to let your web application know where to find it. Put these together in a JAR and drop it into your WEB-INF/lib directory.
Here's an outline:
com/x/taglib/core/StringUtil.java
```
package com.x.taglib.core;
public class StringUtil {
public static String join(Iterable<?> elements, CharSequence separator) {
StringBuilder buf = new StringBuilder();
if (elements != null) {
if (separator == null)
separator = " ";
for (Object o : elements) {
if (buf.length() > 0)
buf.append(separator);
buf.append(o);
}
}
return buf.toString();
}
}
```
META-INF/x-c.tld:
```
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>x-c</short-name>
<uri>http://dev.x.com/taglib/core/1.0</uri>
<function>
<description>Join elements of an Iterable into a string.</description>
<display-name>Join</display-name>
<name>join</name>
<function-class>com.x.taglib.core.StringUtil</function-class>
<function-signature>java.lang.String join(java.lang.Iterable, java.lang.CharSequence)</function-signature>
</function>
</taglib>
```
While the TLD is a little verbose, knowing your way around one is a good skill for any developer working with JSP. And, since you've chosen a standard like JSP for presentation, there's a good chance you have tools that will help you out.
This approach has many advantages over the alternative of adding more methods to the underlying model. This function can be written once, and reused in any project. It works with a closed-source, third-party library. Different delimiters can be supported in different contexts, without polluting a model API with a new method for each.
Most importantly, *it supports a separation of view and model-controller development roles.* Tasks in these two areas are often performed by different people at different times. Maintaining a loose coupling between these layers minimizes complexity and maintenance costs. When even a trivial change like using a different delimiter in the presentation requires a programmer to modify a library, you have a very expensive and cumbersome system.
The `StringUtil` class is the same whether its exposed as a EL function or not. The only "extra" necessary is the TLD, which is trivial; a tool could easily generate it.
|
Concatenate strings in JSP EL?
|
[
"",
"java",
"jsp",
"el",
"taglib",
""
] |
Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a *Tell A Friend* with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.
I'm using PHP 4 and MySql 4.1.
|
If the column is a primary key or a unique index:
```
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
```
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email\_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
|
This works if you have a unique index or primary key on the column (EmailAddr in this example):
```
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test@test.com')
```
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
See the [MySql docs](http://dev.mysql.com/doc/refman/4.1/en/insert.html) for more information.
|
Is it possible to insert a row but only if a value does not already exist?
|
[
"",
"php",
"mysql",
""
] |
Given an HTML link like
```
<a href="urltxt" class="someclass" close="true">texttxt</a>
```
how can I isolate the url and the text?
**Updates**
I'm using Beautiful Soup, and am unable to figure out how to do that.
I did
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
links = soup.findAll('a')
for link in links:
print "link content:", link.content," and attr:",link.attrs
```
i get
```
*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ...
...
```
Why am i missing the content?
edit: elaborated on 'stuck' as advised :)
|
Use [Beautiful Soup](http://crummy.com/software/BeautifulSoup). Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.
**EDIT:**
I think you want:
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
```
By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.
**EDIT 2:**
This should show you all the links in a page:
```
import urlparse, urllib
from BeautifulSoup import BeautifulSoup
url = "http://www.example.com/index.html"
source = urllib.urlopen(url).read()
soup = BeautifulSoup(source)
for item in soup.fetchall('a'):
try:
link = urlparse.urlparse(item['href'].lower())
except:
# Not a valid link
pass
else:
print link
```
|
Here's a code example, showing getting the attributes and contents of the links:
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
for link in soup.findAll('a'):
print link.attrs, link.contents
```
|
Decomposing HTML to link text and target
|
[
"",
"python",
"html",
"regex",
"beautifulsoup",
""
] |
I wish to calculate the time it took for an API to return a value.
The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:
```
#include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
clock_t start;
double diff;
start = clock();
diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
cout<<"printf: "<< diff <<'\n';
return 0;
}
```
The above code gives the time in seconds. How do I get the same in nano seconds and with more precision?
|
What others have posted about running the function repeatedly in a loop is correct.
For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html).
```
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
```
For windows you want to use the [QueryPerformanceCounter](http://support.microsoft.com/kb/172338). And here is more on [QPC](http://msdn.microsoft.com/en-us/library/ms979201.aspx)
Apparently there is a known [issue](http://support.microsoft.com/kb/274323) with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a [problem](http://forum.beyond3d.com/showthread.php?t=47951). See the second post by sebbbi, where he states:
> QueryPerformanceCounter() and
> QueryPerformanceFrequency() offer a
> bit better resolution, but have
> different issues. For example in
> Windows XP, all AMD Athlon X2 dual
> core CPUs return the PC of either of
> the cores "randomly" (the PC sometimes
> jumps a bit backwards), unless you
> specially install AMD dual core driver
> package to fix the issue. We haven't
> noticed any other dual+ core CPUs
> having similar issues (p4 dual, p4 ht,
> core2 dual, core2 quad, phenom quad).
**EDIT 2013/07/16:**
It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in <http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx>
> ...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for
> multiple processors, bugs in the BIOS or drivers may result in these routines returning
> different values as the thread moves from one processor to another...
However this StackOverflow answer <https://stackoverflow.com/a/4588605/34329> states that QPC should work fine on any MS OS after Win XP service pack 2.
This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. <http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html> Synchronizing across processors is still an issue.
Other fine reading related to timers:
* <https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks>
* <http://lwn.net/Articles/209101/>
* <http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html>
* [QueryPerformanceCounter Status?](https://stackoverflow.com/questions/7287663/queryperformancecounter-status)
See the comments for more details.
|
This new answer uses C++11's `<chrono>` facility. While there are other answers that show how to use `<chrono>`, none of them shows how to use `<chrono>` with the `RDTSC` facility mentioned in several of the other answers here. So I thought I would show how to use `RDTSC` with `<chrono>`. Additionally I'll demonstrate how you can templatize the testing code on the clock so that you can rapidly switch between `RDTSC` and your system's built-in clock facilities (which will likely be based on `clock()`, `clock_gettime()` and/or `QueryPerformanceCounter`.
Note that the `RDTSC` instruction is x86-specific. `QueryPerformanceCounter` is Windows only. And `clock_gettime()` is POSIX only. Below I introduce two new clocks: `std::chrono::high_resolution_clock` and `std::chrono::system_clock`, which, if you can assume C++11, are now cross-platform.
First, here is how you create a C++11-compatible clock out of the Intel `rdtsc` assembly instruction. I'll call it `x::clock`:
```
#include <chrono>
namespace x
{
struct clock
{
typedef unsigned long long rep;
typedef std::ratio<1, 2'800'000'000> period; // My machine is 2.8 GHz
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<clock> time_point;
static const bool is_steady = true;
static time_point now() noexcept
{
unsigned lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return time_point(duration(static_cast<rep>(hi) << 32 | lo));
}
};
} // x
```
All this clock does is count CPU cycles and store it in an unsigned 64-bit integer. You may need to tweak the assembly language syntax for your compiler. Or your compiler may offer an intrinsic you can use instead (e.g. `now() {return __rdtsc();}`).
To build a clock you have to give it the representation (storage type). You must also supply the clock period, which must be a compile time constant, even though your machine may change clock speed in different power modes. And from those you can easily define your clock's "native" time duration and time point in terms of these fundamentals.
If all you want to do is output the number of clock ticks, it doesn't really matter what number you give for the clock period. This constant only comes into play if you want to convert the number of clock ticks into some real-time unit such as nanoseconds. And in that case, the more accurate you are able to supply the clock speed, the more accurate will be the conversion to nanoseconds, (milliseconds, whatever).
Below is example code which shows how to use `x::clock`. Actually I've templated the code on the clock as I'd like to show how you can use many different clocks with the exact same syntax. This particular test is showing what the looping overhead is when running what you want to time under a loop:
```
#include <iostream>
template <class clock>
void
test_empty_loop()
{
// Define real time units
typedef std::chrono::duration<unsigned long long, std::pico> picoseconds;
// or:
// typedef std::chrono::nanoseconds nanoseconds;
// Define double-based unit of clock tick
typedef std::chrono::duration<double, typename clock::period> Cycle;
using std::chrono::duration_cast;
const int N = 100000000;
// Do it
auto t0 = clock::now();
for (int j = 0; j < N; ++j)
asm volatile("");
auto t1 = clock::now();
// Get the clock ticks per iteration
auto ticks_per_iter = Cycle(t1-t0)/N;
std::cout << ticks_per_iter.count() << " clock ticks per iteration\n";
// Convert to real time units
std::cout << duration_cast<picoseconds>(ticks_per_iter).count()
<< "ps per iteration\n";
}
```
The first thing this code does is create a "real time" unit to display the results in. I've chosen picoseconds, but you can choose any units you like, either integral or floating point based. As an example there is a pre-made `std::chrono::nanoseconds` unit I could have used.
As another example I want to print out the average number of clock cycles per iteration as a floating point, so I create another duration, based on double, that has the same units as the clock's tick does (called `Cycle` in the code).
The loop is timed with calls to `clock::now()` on either side. If you want to name the type returned from this function it is:
```
typename clock::time_point t0 = clock::now();
```
(as clearly shown in the `x::clock` example, and is also true of the system-supplied clocks).
To get a duration in terms of floating point clock ticks one merely subtracts the two time points, and to get the per iteration value, divide that duration by the number of iterations.
You can get the count in any duration by using the `count()` member function. This returns the internal representation. Finally I use `std::chrono::duration_cast` to convert the duration `Cycle` to the duration `picoseconds` and print that out.
To use this code is simple:
```
int main()
{
std::cout << "\nUsing rdtsc:\n";
test_empty_loop<x::clock>();
std::cout << "\nUsing std::chrono::high_resolution_clock:\n";
test_empty_loop<std::chrono::high_resolution_clock>();
std::cout << "\nUsing std::chrono::system_clock:\n";
test_empty_loop<std::chrono::system_clock>();
}
```
Above I exercise the test using our home-made `x::clock`, and compare those results with using two of the system-supplied clocks: `std::chrono::high_resolution_clock` and `std::chrono::system_clock`. For me this prints out:
```
Using rdtsc:
1.72632 clock ticks per iteration
616ps per iteration
Using std::chrono::high_resolution_clock:
0.620105 clock ticks per iteration
620ps per iteration
Using std::chrono::system_clock:
0.00062457 clock ticks per iteration
624ps per iteration
```
This shows that each of these clocks has a different tick period, as the ticks per iteration is vastly different for each clock. However when converted to a known unit of time (e.g. picoseconds), I get approximately the same result for each clock (your mileage may vary).
Note how my code is completely free of "magic conversion constants". Indeed, there are only two magic numbers in the entire example:
1. The clock speed of my machine in order to define `x::clock`.
2. The number of iterations to test over. If changing this number makes your results vary greatly, then you should probably make the number of iterations higher, or empty your computer of competing processes while testing.
|
Timer function to provide time in nano seconds using C++
|
[
"",
"c++",
"c",
"timer",
""
] |
I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:
```
ofstream outFile("test.txt", std::ios::out | std::ios::binary);
wstring hello = L"hello";
outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t));
outFile.close();
```
Opening test.txt in for example Firefox with encoding set to UTF16 it will show as:
h�e�l�l�o�
Could anyone tell me why this happens?
**EDIT:**
Opening the file in a hex editor I get:
```
FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00
```
Looks like I get two extra bytes in between every character for some reason?
|
I suspect that sizeof(wchar\_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like.
That's easy enough to test (just print out sizeof(wchar\_t)) but I'm pretty sure it's what's going on.
To go from a UTF-32 wstring to UTF-16 you'll need to apply a proper encoding, as surrogate pairs come into play.
|
Here we run into the little used locale properties.
If you output your string as a string (rather than raw data) you can get the locale to do the appropriate conversion auto-magically.
**N.B.**This code does not take into account edianness of the wchar\_t character.
```
#include <locale>
#include <fstream>
#include <iostream>
// See Below for the facet
#include "UTF16Facet.h"
int main(int argc,char* argv[])
{
// construct a custom unicode facet and add it to a local.
UTF16Facet *unicodeFacet = new UTF16Facet();
const std::locale unicodeLocale(std::cout.getloc(), unicodeFacet);
// Create a stream and imbue it with the facet
std::wofstream saveFile;
saveFile.imbue(unicodeLocale);
// Now the stream is imbued we can open it.
// NB If you open the file stream first. Any attempt to imbue it with a local will silently fail.
saveFile.open("output.uni");
saveFile << L"This is my Data\n";
return(0);
}
```
The File: UTF16Facet.h
```
#include <locale>
class UTF16Facet: public std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type>
{
typedef std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type> MyType;
typedef MyType::state_type state_type;
typedef MyType::result result;
/* This function deals with converting data from the input stream into the internal stream.*/
/*
* from, from_end: Points to the beginning and end of the input that we are converting 'from'.
* to, to_limit: Points to where we are writing the conversion 'to'
* from_next: When the function exits this should have been updated to point at the next location
* to read from. (ie the first unconverted input character)
* to_next: When the function exits this should have been updated to point at the next location
* to write to.
*
* status: This indicates the status of the conversion.
* possible values are:
* error: An error occurred the bad file bit will be set.
* ok: Everything went to plan
* partial: Not enough input data was supplied to complete any conversion.
* nonconv: no conversion was done.
*/
virtual result do_in(state_type &s,
const char *from,const char *from_end,const char* &from_next,
wchar_t *to, wchar_t *to_limit,wchar_t* &to_next) const
{
// Loop over both the input and output array/
for(;(from < from_end) && (to < to_limit);from += 2,++to)
{
/*Input the Data*/
/* As the input 16 bits may not fill the wchar_t object
* Initialise it so that zero out all its bit's. This
* is important on systems with 32bit wchar_t objects.
*/
(*to) = L'\0';
/* Next read the data from the input stream into
* wchar_t object. Remember that we need to copy
* into the bottom 16 bits no matter what size the
* the wchar_t object is.
*/
reinterpret_cast<char*>(to)[0] = from[0];
reinterpret_cast<char*>(to)[1] = from[1];
}
from_next = from;
to_next = to;
return((from > from_end)?partial:ok);
}
/* This function deals with converting data from the internal stream to a C/C++ file stream.*/
/*
* from, from_end: Points to the beginning and end of the input that we are converting 'from'.
* to, to_limit: Points to where we are writing the conversion 'to'
* from_next: When the function exits this should have been updated to point at the next location
* to read from. (ie the first unconverted input character)
* to_next: When the function exits this should have been updated to point at the next location
* to write to.
*
* status: This indicates the status of the conversion.
* possible values are:
* error: An error occurred the bad file bit will be set.
* ok: Everything went to plan
* partial: Not enough input data was supplied to complete any conversion.
* nonconv: no conversion was done.
*/
virtual result do_out(state_type &state,
const wchar_t *from, const wchar_t *from_end, const wchar_t* &from_next,
char *to, char *to_limit, char* &to_next) const
{
for(;(from < from_end) && (to < to_limit);++from,to += 2)
{
/* Output the Data */
/* NB I am assuming the characters are encoded as UTF-16.
* This means they are 16 bits inside a wchar_t object.
* As the size of wchar_t varies between platforms I need
* to take this into consideration and only take the bottom
* 16 bits of each wchar_t object.
*/
to[0] = reinterpret_cast<const char*>(from)[0];
to[1] = reinterpret_cast<const char*>(from)[1];
}
from_next = from;
to_next = to;
return((to > to_limit)?partial:ok);
}
};
```
|
Writing utf16 to file in binary mode
|
[
"",
"c++",
"unicode",
"utf-16",
""
] |
A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.
ex:
ax 5 5
dx 3 acc
c ax bx
I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.
replacement example:
acc 5 5
dx 3 acc
c ax bx
or
c 5 5
dx 3 acc
c ax ax
Is there a way to do this with regexes? In Java? If so, which methods should I use?
|
I think this is the most clean solution for replacing a certain set of symbols from a string containing a superset of them.
appendreplacement is the key to this method.
one important caveat: do not include any unescped dollar characters ($) in your elements list. escape them by using "\$"
eventually use
.replaceall("\$","\\$");
on every string before adding it to the list.
see also the [javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer,%20java.lang.String)) in doubt about the $ signs.
```
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReplaceTokens {
public static void main(String[] args) {
List<String> elements = Arrays.asList("ax", "bx", "dx", "c", "acc");
final String patternStr = join(elements, "|"); //build string "ax|bx|dx|c|acc"
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher("ax 5 5 dx 3 acc c ax bx");
StringBuffer sb = new StringBuffer();
Random rand = new Random();
while (m.find()){
String randomSymbol = elements.get(rand.nextInt(elements.size()));
m.appendReplacement(sb,randomSymbol);
}
m.appendTail(sb);
System.out.println(sb);
}
/**
* this method is only needed to generate the string ax|bx|dx|c|acc in a clean way....
* @see org.apache.commons.lang.StringUtils.join for a more common alternative...
*/
public static String join(List<String> s, String delimiter) {
if (s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuffer buffer = new StringBuffer(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
```
|
To answer the first question: no.
Since you are doing a random replace, regex will not help you, nothing about regex is random. \* Since your strings are in an array, you don't need to find them with any pattern matching, so again regex isn't necessary.
\*\*Edit: the question has been edited so it no longer says the strings are in an array. In this case, assuming they are all in one big string, you might build a regex to find the parts you want to replace, as shown in other answers.\*
|
Java: Easiest way to replace strings with random strings
|
[
"",
"java",
"regex",
"replace",
""
] |
I have several strings in the rough form:
```
[some text] [some number] [some more text]
```
I want to extract the text in [some number] using the Java regex classes.
I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].
I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].
|
Full example:
```
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
```
Since you're looking for the first number, you can use such regexp:
```
^\D+(\d+).*
```
and `m.group(1)` will return you the first number. Note that signed numbers can contain a minus sign:
```
^\D+(-?\d+).*
```
|
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}
}
}
```
Output:
```
1234
789
2345
```
|
Using regular expressions to extract a value in Java
|
[
"",
"java",
"regex",
""
] |
The `equals()` method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same `String`. Is there a way to avoid this internet access?
|
Use [java.net.URI](http://docs.oracle.com/javase/8/docs/api/java/net/URI.html) instead of URL.
|
If you just want to compare the url strings, try
```
url1.toString().equals(url2.toString())
```
|
How to avoid, that URL.equals needs access to the internet in Java?
|
[
"",
"java",
"url",
"dns",
"equals",
"equality",
""
] |
Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?
|
Take a look at [quartz.net](http://quartznet.sourceforge.net/). It is a scheduling library for .net.
More specifically take a look [here](http://quartznet.sourceforge.net/tutorial/lesson_4.html).
|
I achieved this by doing the following...
1. Set up a timer that fires every 20 minutes (although the actual timing is up to you - I needed to run on several occasions throughout the day).
2. on each Tick event, check the system time. Compare the time to the scheduled run time for your method.
3. If the current time is less than the scheduled time, check a in some persistent storage to get the datetime value of the last time the method ran.
4. If the method last ran more than 24 hours ago, run the method, and stash the datetime of this run back to your data store
5. If the method last ran within the last 24 hours, ignore it.
HTH
\*edit - code sample in C# :: Note : untested...
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Timer t1 = new Timer();
t1.Interval = (1000 * 60 * 20); // 20 minutes...
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.AutoReset = true;
t1.Start();
Console.ReadLine();
}
static void t1_Elapsed(object sender, ElapsedEventArgs e)
{
DateTime scheduledRun = DateTime.Today.AddHours(3); // runs today at 3am.
System.IO.FileInfo lastTime = new System.IO.FileInfo(@"C:\lastRunTime.txt");
DateTime lastRan = lastTime.LastWriteTime;
if (DateTime.Now > scheduledRun)
{
TimeSpan sinceLastRun = DateTime.Now - lastRan;
if (sinceLastRun.Hours > 23)
{
doStuff();
// Don't forget to update the file modification date here!!!
}
}
}
static void doStuff()
{
Console.WriteLine("Running the method!");
}
}
}
```
|
Run once a day in C#
|
[
"",
"c#",
"scheduling",
""
] |
I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:
```
#someElement {
foo: 'bar';
}
```
I have managed to get its value with the currentStyle property in IE7:
```
var element = document.getElementById('someElement');
var val = element.currentStyle.foo;
```
But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3:
```
var val = getComputedStyle(element,null).foo;
```
...and it returns undefined. **Does anyone know a cross-browser way of retreiving a custom CSS property value?**
*(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)*
|
Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.
|
Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with
`:after`, `:before` etc. You can store JSON inside it:
```
#someElement {
content: '{"foo": "bar"}';
}
```
Then use code like this to retrieve it:
```
var CSSMetaData = function() {
function trimQuotes( str ) {
return str.replace( /^['"]/, "" ).replace( /["']$/, "" );
}
function fixFirefoxEscape( str ) {
return str.replace( /\\"/g, '"' );
}
var forEach = [].forEach,
div = document.createElement("div"),
matchesSelector = div.webkitMatchesSelector ||
div.mozMatchesSelector ||
div.msMatchesSelector ||
div.oMatchesSelector ||
div.matchesSelector,
data = {};
forEach.call( document.styleSheets, function( styleSheet ) {
forEach.call( styleSheet.cssRules, function( rule ) {
var content = rule.style.getPropertyValue( "content" ),
obj;
if( content ) {
content = trimQuotes(content);
try {
obj = JSON.parse( content );
}
catch(e) {
try {
obj = JSON.parse( fixFirefoxEscape( content ) );
}
catch(e2) {
return ;
}
}
data[rule.selectorText] = obj;
}
});
});
return {
getDataByElement: function( elem ) {
var storedData;
for( var selector in data ) {
if( matchesSelector.call( elem, selector ) ) {
storedData = data[selector];
if( storedData ) return storedData;
}
}
return null;
}
};
}();
var obj = CSSMetaData.getDataByElement( document.getElementById("someElement"));
console.log( obj.foo ); //bar
```
Note, this is only for modern browsers. Demo: <http://jsfiddle.net/xFjZp/3/>
|
Can I fetch the value of a non-standard CSS property via Javascript?
|
[
"",
"javascript",
"css",
""
] |
I have a user that keeps getting this error. Is there a tool that does window handle counting that i can use to figure out why he keeps getting this error.
System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Form.CreateHandle()
at System.Windows.Forms.Control.get\_Handle()
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
|
The best counter I know is Taskmgr.exe. View + Select Columns and check "User objects", "Handle count" and "GDI Objects".
The generic diagnostic is that you're leaking handles and consumed 10,000 of them. Beware of a handle leak bug in .NET 2.0 SP1 and .NET 3.5's Graphics.CopyFromScreen(), fixed in 3.5 SP1.
|
If the Form you are creating overrides WndProc(), be careful to ensure that it always calls base.WndProc() during the window creation process.
I inadvertently omitted a call to base.WndProc() in my override, and got your stack trace.
|
Window handle debugging in Winforms
|
[
"",
"c#",
"winforms",
"window",
""
] |
I am trying to gain a better understanding of tcp/ip sockets in c#, as i want to challenge myself to see if i can create a working MMO infrastructure (game world, map, players, etc) purely for educational purposes as i have no intention of being another one of those "OMGZ iz gonna make my r0x0r MMORPG that will be better than WoW!!!", you know what im talking about.
Anyway, i was wondering if anyone can shed some light as to how one might approach designing this kind of system and what kinds of things are required, and what i should watch out for?
My initial idea was to break up the system into seperate client/server connections with each connection (on its own port) performing a specific task, such as updating player/monster positions, sending and receiving chat messages, etc. which to me would make processing the data easier because you wouldn't always need to put a header on the data to know what information the packet contains.
Does that make sense and is useful or am i just way over complicating things?
your responses are very much appreciated.
|
If you are doing socket level programming, then regardless of how many ports you open for each message type, you still need to have a header of some sort. Even if it is just the length of the rest of the message. Having said that it is easy to add a simple header and tail structure to a message. I would think it is easier to only have to deal with one port on the client side.
I believe the modern MMORPGs (and maybe even the old ones) had two levels of servers. The login servers which verify you as a paying client. Once verified these pass you off to the game server which contain all the game world information. Even so this still only requires the client to have one socket open, but does not disallow having more.
Additionally most MMORPGS also encrypt all their data. If you are writing this as an exercise for fun, then this will not matter so much.
For designing/writing protocols in general here are the things I worry about:
**Endianess**
Are the client and server always guaranteed to have the same endianess. If not I need to handle that in my serialization code. There are multiple ways to handle endianess.
1. Ignore it - Obviously a bad choice
2. Specify the endianness of the protocol. This is what the older protocols did/do hence the term network order which was always big endian. It doesn't actually matter which endianess you specify just that you specify one or the other. Some crusty old network programmers will get up in arms if you don't use big endianess, but if your servers and most clients are little endian you really aren't buying yourself anything other than extra work by making the protocol big endian.
3. Mark the Endianess in each header - You can add a cookie which will tell you the endianess of the client/server and let each message be converted accordingly as needed. Extra work!
4. Make your protocol agnostic - If you send everything as ASCII strings, then endianess is irrelevant, but also a lot more inefficient.
Of the 4 I would usually choose 2, and specify the endianess to be that of the majority of the clients, which now days will be little endian.
**Forwards and Backwards Compatibility**
Does the protocol need to be forwards and backwards compatible. The answer should almost always be yes. In which case this will determine how I design the over all protocol in terms of versioning, and how each individual message is created to handle minor changes that really shouldn't be part of the versioning. You can punt on this and use XML, but you lose a lot of efficiency.
For the overall versioning I usually design something simple. The client sends a versioning message specifying that it speaks version X.Y, as long as the server can support that version it sends back a message acknowledging the version of the client and everything proceeds forward. Otherwise it nacks the client and terminates the connection.
For each message you have something like the following:
```
+-------------------------+-------------------+-----------------+------------------------+
| Length of Msg (4 bytes) | MsgType (2 bytes) | Flags (4 bytes) | Msg (length - 6 bytes) |
+-------------------------+-------------------+-----------------+------------------------+
```
The length obviously tells you how long the message is, not including the length itself. The MsgType is the type of the message. Only two bytes for this, since 65356 is plenty of messages types for applications. The flags are there to let you know what is serialized in the message. This field combined with the length is what gives you your forwards and backwards compatibility.
```
const uint32_t FLAG_0 = (1 << 0);
const uint32_t FLAG_1 = (1 << 1);
const uint32_t FLAG_2 = (1 << 2);
...
const uint32_t RESERVED_32 = (1 << 31);
```
Then your deserialization code can do something like the following:
```
uint32 length = MessageBuffer.ReadUint32();
uint32 start = MessageBuffer.CurrentOffset();
uint16 msgType = MessageBuffer.ReadUint16();
uint32 flags = MessageBuffer.ReadUint32();
if (flags & FLAG_0)
{
// Read out whatever FLAG_0 represents.
// Single or multiple fields
}
// ...
// read out the other flags
// ...
MessageBuffer.AdvanceToOffset(start + length);
```
This allows you to **add** new fields **to the end** of the messages without having to revision the entire protocol. It also ensures that old servers and clients will ignore flags they don't know about. If they have to use the new flags and fields, then you simply change the overall protocol version.
**Use a Frame Work or Not**
There are various network frameworks I would consider using for a business application. Unless I had a specific need to scratch I would go with a standard framework. In your case you want to learn socket level programming, so this is a question already answered for you.
If one does use a framework make sure it addresses the two concerns above, or at least does not get in your way if you need to customize it in those areas.
**Am I dealing with a third party**
In many cases you may be dealing with a third party server/client you need to communicate with. This implies a few scenarios:
* They already have a protocol defined - Simply use their protocol.
* You already have a protocol defined (and they are willing to use it) - again simple use the defined protocol
* They use a standard Framework (WSDL based, etc) - Use the framework.
* Neither party has a protocol defined - Try to determing the best solution based on all the factors at hand (all the ones I mentioned here), as well as their level of competencey (at least as far as you can tell). Regardless make sure both sides agree on and understand the protocol. From experience this can be painful or pleasant. It depends on who you are working with.
In either case you will not be working with a third party, so this is really just added for completeness.
I feel as if I could write much more about this, but it is already rather lengthy. I hopes this helps and if you have any specific questions just ask on Stackoverflow.
**An edit to answer knoopx's question:**
* <http://en.wikipedia.org/wiki/Protocol_Buffers>
* [http://en.wikipedia.org/wiki/Thrift\_(protocol)](http://en.wikipedia.org/wiki/Thrift_%28protocol%29)
* [http://en.wikipedia.org/wiki/Etch\_(protocol)](http://en.wikipedia.org/wiki/Etch_%28protocol%29)
* <http://en.wikipedia.org/wiki/Adaptive_Communication_Environment>
* <http://en.wikipedia.org/wiki/CORBA>
* And many more
|
I think you need to crawl before you walk and before you run. First get the design of the framework and connections right, then worry about scalability. If your goal is to learn C# and tcp/ip programming, then don't make this harder on yourself.
Go ahead with your initial thoughts and keep the data streams separate.
have fun and good luck
|
Multi-client, async sockets in c#, best practices?
|
[
"",
"c#",
"sockets",
"client-server",
""
] |
Is it possible to create a toggle button in C# WinForms? I know that you can use a CheckBox control and set it's Appearance property to "Button", but it doesn't look right. I want it to appear sunken, not flat, when pressed. Any thoughts?
|
I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.
|
You can just use a `CheckBox` and set its appearance to `Button`:
```
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Appearance = System.Windows.Forms.Appearance.Button;
```
|
ToggleButton in C# WinForms
|
[
"",
"c#",
"winforms",
"button",
""
] |
In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?
|
In python, [ElementTidy](http://pypi.python.org/pypi/elementtidy/1.0-20050212) parses tag soup and produces an element tree, which allows querying using XPath:
```
>>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB
>>> tb = TB()
>>> tb.feed("<p>Hello world")
>>> e= tb.close()
>>> e.find(".//{http://www.w3.org/1999/xhtml}p")
<Element {http://www.w3.org/1999/xhtml}p at 264eb8>
```
|
I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.
Here's how [you can parse HTML via XPATH using lxml](http://codespeak.net/lxml/xpathxslt.html).
```
>>> from lxml import etree
>>> doc = '<foo><bar></bar></foo>'
>>> tree = etree.HTML(doc)
>>> r = tree.xpath('/foo/bar')
>>> len(r)
1
>>> r[0].tag
'bar'
>>> r = tree.xpath('bar')
>>> r[0].tag
'bar'
```
|
Parse HTML via XPath
|
[
"",
"python",
"html",
"ruby",
"xpath",
"parsing",
""
] |
I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA\_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.
As per the comment below, CATALINA\_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.
|
Serhii's suggestion works and here is some more detail.
If you look in your installation's bin directory you will see catalina.sh
or .bat scripts. If you look in these you will see that they run a
setenv.sh or setenv.bat script respectively, if it exists, to set environment variables.
The relevant environment variables are described in the comments at the
top of catalina.sh/bat. To use them create, for example, a file
$CATALINA\_HOME/bin/setenv.sh with contents
```
export JAVA_OPTS="-server -Xmx512m"
```
For Windows you will need, in setenv.bat, something like
```
set JAVA_OPTS=-server -Xmx768m
```
Hope this helps,
Glenn
|
Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.
The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another instance.
Probably your configuration app has created the setenv script and thats why tomcat is ignoring the environment variables.
|
How to tune Tomcat 5.5 JVM Memory settings without using the configuration program
|
[
"",
"java",
"tomcat",
"memory",
"jvm",
""
] |
I got an image with which links to another page using `<a href="..."> <img ...> </a>`.
How can I make it make a post like if it was a button `<input type="submit"...>`?
|
```
<input type="image" name="your_image_name" src="your_image_url.png" />
```
This will send the `your_image_name.x` and `your_image_name.y` values as it submits the form, which are the x and y coordinates of the position the user clicked the image.
|
More generic approatch using **[JQuery](http://jquery.com/)** library [closest](http://api.jquery.com/closest/)() and [submit](http://api.jquery.com/submit/)() buttons.
Here you do not have to specify whitch form you want to submit, submits the form it is in.
```
<a href="#" onclick="$(this).closest('form').submit()">Submit Link</a>
```
|
How to make a submit out of a <a href...>...</a> link?
|
[
"",
"javascript",
"html",
"form-submit",
"url-link",
""
] |
In a table I have the following schema
```
table1:
playerID int primary key,
nationalities nvarchar
table2:
playerID int,
pubVisited nvarchar
```
Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this?
|
Tested on SQL Server 2005
```
update table2 set pubVisited = NULL
from
table1 t1
inner join
table2 t2
on (t1.playerID = t2.playerID and t1.nationalities = 'England')
```
|
Judging by the *nvarchar* type, you're using MSSQL. Now, in MySQL you could use a subselect in the update .. where clause but MSSQL has its own update .. from clause:
```
UPDATE table2
SET
table2.pubVisited = null
FROM table1
WHERE
table2.playerID = table1.playerID and table1.nationalities = 'England'
```
Haven't tested it though, so it might not work.
|
Update data in different tables in SQL Server
|
[
"",
"sql",
"sql-server",
""
] |
```
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
```
I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.
I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer `count` to be 0 (or NULL) if there are no rows, and the name still returns.
*Edit:* I'd like to be able to sort by the `count` descending. (or `name` ASC) is that possible?
|
This should work for you:
```
SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`
FROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`
GROUP BY `t1`.`id`
```
Left join ensures you have all rows from t1, and COUNT(`t2`.`id`) makes it count only records where t2.id is not null (that is - those that really exist in t2)
|
This sorts descending by COUNT, and within same counts ascending by `name`. Names with no rows in `t2` will return with a count of 0.
```
SELECT
`t1`.`name`,
COUNT(`t2`.`id`) AS `count`
FROM
`t1`
LEFT JOIN `t2` ON`t2`.`id` = `t1`.`id`
GROUP BY
`t1`.`name`
ORDER BY
COUNT(`t2`.`id`) DESC,
`t1`.`name`
```
Modify the ORDER BY to your needs.
|
MySQL Cross-Table Count(*) Query Help
|
[
"",
"sql",
"mysql",
""
] |
I have to deal with very large text files (2 GBs), it is mandatory to read/write them line by line. To write 23 millions of lines using ofstream is really slow so, at the beginning, I tried to speed up the process writing large chunks of lines in a memory buffer (for example 256 MB or 512 MB) and then write the buffer into the file. This did not work, the performance is more or less the same. I have the same problem reading the files. I know the I/O operations are buffered by the STL I/O system and this also depends on the disk scheduler policy (managed by the OS, in my case Linux).
Any idea about how to improve the performance?
PS: I have been thinking about using a background child process (or a thread) to read/write the data chunks while the program is processing data but I do not know (mainly in the case of the subprocess) if this will be worthy.
|
A 2GB file is pretty big, and you need to be aware of all the possible areas that can act as bottlenecks:
* The HDD itself
* The HDD interface (IDE/SATA/RAID/USB?)
* Operating system/filesystem
* C/C++ Library
* Your code
I'd start by doing some measurements:
* How long does your code take to read/write a 2GB file,
* How fast can the '[dd](http://en.wikipedia.org/wiki/Dd_%28Unix%29#Benchmarking_drive_performance)' command read and write to disk? Example...
`dd if=/dev/zero bs=1024 count=2000000 of=file_2GB`
* How long does it take to write/read using just big fwrite()/fread() calls
Assuming your disk is capable of reading/writing at about 40Mb/s (which is probably a realistic figure to start from), your 2GB file can't run faster than about 50 seconds.
How long is it actually taking?
> Hi Roddy, using fstream read method
> with 1.1 GB files and large
> buffers(128,255 or 512 MB) it takes
> about 43-48 seconds and it is the same
> using fstream getline (line by line).
> cp takes almost 2 minutes to copy the
> file.
In which case, your're hardware-bound. *cp* has to read and write, and will be seeking back and forth across the disk surface like mad when it does it. So it will (as you see) be more than twice as bad as the simple 'read' case.
To improve the speed, the first thing I'd try is a faster hard drive, or an SSD.
You haven't said what the disk interface is? SATA is pretty much the easiest/fastest option. Also (obvious point, this...) make sure the disk is physically on the same machine your code is running, otherwise you're network-bound...
|
I would also suggest memory-mapped files but if you're going to use boost I think [boost::iostreams::mapped\_file](http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/classes/mapped_file.html#mapped_file) is a better match than boost::interprocess.
|
When to build your own buffer system for I/O (C++)?
|
[
"",
"c++",
"linux",
"performance",
"io",
"buffer",
""
] |
We currently have a web application loading a Spring application context which instantiates a stack of business objects, DAO objects and Hibernate. We would like to share this stack with another web application, to avoid having multiple instances of the same objects.
We have looked into several approaches; exposing the objects using JMX or JNDI, or using EJB3.
The different approaches all have their issues, and we are looking for a lightweight method.
Any suggestions on how to solve this?
Edit: I have received comments requesting me to elaborate a bit, so here goes:
The main problem we want to solve is that we want to have only one instance of Hibernate. This is due to problems with invalidation of Hibernate's 2nd level cache when running several client applications working with the same datasource. Also, the business/DAO/Hibernate stack is growing rather large, so not duplicating it just makes more sense.
First, we tried to look at how the business layer alone could be exposed to other web apps, and Spring offers JMX wrapping at the price of a tiny amount of XML. However, we were unable to bind the JMX entities to the JNDI tree, so we couldn't lookup the objects from the web apps.
Then we tried binding the business layer directly to JNDI. Although Spring didn't offer any method for this, using JNDITemplate to bind them was also trivial. But this led to several new problems: 1) Security manager denies access to RMI classloader, so the client failed once we tried to invoke methods on the JNDI resource. 2) Once the security issues were resolved, JBoss threw IllegalArgumentException: object is not an instance of declaring class. A bit of reading reveals that we need stub implementations for the JNDI resources, but this seems like a lot of hassle (perhaps Spring can help us?)
We haven't looked too much into EJB yet, but after the first two tries I'm wondering if what we're trying to achieve is at all possible.
To sum up what we're trying to achieve: One JBoss instance, several web apps utilizing one stack of business objects on top of DAO layer and Hibernate.
Best regards,
Nils
|
Are the web applications deployed on the same server?
I can't speak for Spring, but it is straightforward to move your business logic in to the EJB tier using Session Beans.
The application organization is straight forward. The Logic goes in to Session Beans, and these Session Beans are bundled within a single jar as an Java EE artifact with a ejb-jar.xml file (in EJB3, this will likely be practically empty).
Then bundle you Entity classes in to a seperate jar file.
Next, you will build each web app in to their own WAR file.
Finally, all of the jars and the wars are bundled in to a Java EE EAR, with the associated application.xml file (again, this will likely be quite minimal, simply enumerating the jars in the EAR).
This EAR is deployed wholesale to the app server.
Each WAR is effectively independent -- their own sessions, there own context paths, etc. But they share the common EJB back end, so you have only a single 2nd level cache.
You also use local references and calling semantic to talk to the EJBs since they're in the same server. No need for remote calls here.
I think this solves quite well the issue you're having, and its is quite straightforward in Java EE 5 with EJB 3.
Also, you can still use Spring for much of your work, as I understand, but I'm not a Spring person so I can not speak to the details.
|
What about spring parentContext?
Check out this article:
<http://springtips.blogspot.com/2007/06/using-shared-parent-application-context.html>
|
What's the best way to share business object instances between Java web apps using JBoss and Spring?
|
[
"",
"java",
"hibernate",
"spring",
"jboss",
"ejb-3.0",
""
] |
When I ran [ReSharper](http://en.wikipedia.org/wiki/ReSharper) on my code, for example:
```
if (some condition)
{
Some code...
}
```
ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:
```
if (!some condition) return;
Some code...
```
I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".
|
A return in the middle of the method is not necessarily bad. It might be better to return immediately if it makes the intent of the code clearer. For example:
```
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};
```
In this case, if `_isDead` is true, we can immediately get out of the method. It might be better to structure it this way instead:
```
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
```
I've picked this code from the [refactoring catalog](http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html). This specific refactoring is called: Replace Nested Conditional with Guard Clauses.
|
**It is not only aesthetic**, but it also reduces the [maximum nesting level](http://codebetter.com/patricksmacchia/2008/03/07/a-simple-trick-to-code-better-and-to-increase-testability/) inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, [many](http://www.ndepend.com/Metrics.aspx#ILNestingDepth) [static](http://www.scitools.com/documents/metricsList.php?metricGroup=complex#MaxNesting) [analysis](http://www.aivosto.com/project/help/pm-complexity.html) [tools](http://www.semdesigns.com/products/metrics/CSharpMetrics.html) provide a measure of this as one of the indicators of code quality).
On the other hand, it also makes your method have multiple exit points, something that another group of people believes is a no-no.
Personally, I agree with ReSharper and the first group (in a language that has exceptions I find it silly to discuss "multiple exit points"; almost anything can throw, so there are numerous potential exit points in all methods).
**Regarding performance**: both versions *should* be equivalent (if not at the IL level, then certainly after the jitter is through with the code) in every language. Theoretically this depends on the compiler, but practically any widely used compiler of today is capable of handling much more advanced cases of code optimization than this.
|
Invert "if" statement to reduce nesting
|
[
"",
"c#",
"resharper",
""
] |
Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday).
I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.
|
using Fluent DateTime <https://github.com/FluentDateTime/FluentDateTime>
```
var dateTime = DateTime.Now.AddBusinessDays(4);
```
|
```
public DateTime AddBusinessDays(DateTime dt, int nDays)
{
int weeks = nDays / 5;
nDays %= 5;
while(dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
dt = dt.AddDays(1);
while (nDays-- > 0)
{
dt = dt.AddDays(1);
if (dt.DayOfWeek == DayOfWeek.Saturday)
dt = dt.AddDays(2);
}
return dt.AddDays(weeks*7);
}
```
|
Adding Days to a Date but Excluding Weekends
|
[
"",
"c#",
"f#",
"date",
""
] |
I know about using a -vsdoc.js file for [IntelliSense](http://en.wikipedia.org/wiki/IntelliSense), and the one for jQuery is easy to find. What other JavaScript, Ajax, and DHTML libraries have them and where can I find those files? Also, is there a document which outlines the specifications for -vsdoc.js files?
|
An excellent blog posting from Betrand LeRoy on IntelliSense format for JavaScript:
*[The format for JavaScript doc comments](http://weblogs.asp.net/bleroy/archive/2007/04/23/the-format-for-javascript-doc-comments.aspx)*.
In a nutshell:
Summary - used to describe a function/method or event. Syntax:
```
<summary locid="descriptionID">Description</summary>
```
Parameter - describe a parameter to a function/method. Syntax:
```
<param name="parameterName"
mayBeNull="true|false" optional="true|false"
type="ParameterType" parameterArray="true|false"
integer="true|false" domElement="true|false"
elementType="ArrayElementType" elementInteger="true|false"
elementDomElement="true|false"
elementMayBeNull="true|false">Description</param>
```
The param tag is used to describe the parameters of a method or constructor. The param tags should be in the same order as the method or constructor's parameters and have the same names.
Function return type - syntax:
```
<returns
type="ValueType" integer="true|false" domElement="true|false"
mayBeNull="true|false" elementType="ArrayElementType"
elementInteger="true|false" elementDomElement="true|false"
elementMayBeNull="true|false">Description</returns>
```
Value type - describes a property (shouldnt use 'summary' for a prop) - syntax:
```
<value
type="ValueType" integer="true|false" domElement="true|false"
mayBeNull="true|false" elementType="ArrayElementType"
elementInteger="true|false" elementDomElement="true|false"
elementMayBeNull="true|false"
locid="descriptionID">Description</value>
```
Field - used to describe a field in a JavaScript class - syntax:
```
<field name="fieldName" type="FieldType"
integer="true|false" domElement="true|false" mayBeNull="true|false"
elementType="ArrayElementType" elementInteger="true|false"
elementDomElement="true|false" elementMayBeNull="true|false"
locid="descriptionID">Description</field>
```
How to include IntelliSense for an external JavaScript file, the following syntax as the first line(s) in a JavaScript file:
```
<reference path="path/to/the/script/reference.js"
assembly="Assembly.Name" name="ScriptResourceName.js"/>
```
|
I wrote on article to sum up (from investigation) what parts of vsdoc are used to help Intellisense in VS 2010 : <http://www.scottlogic.co.uk/2010/08/vs-2010-vs-doc-and-javascript-intellisense/>
|
IntelliSense for Ajax and JavaScript libraries in Visual Studio
|
[
"",
"javascript",
"visual-studio",
""
] |
I'm probably going to be using Tomcat and the Apache Axis webapp plugin, but I'm curious as to any other potential lightweight solutions.
The main goal of this is to connect to MySQL database for doing some demos.
Thanks,
Todd
|
Define lightweight? (What DOES that mean anyway nowadays??)
With JAX-WS/Metro you need to simply make a boiler plate change to the web.xml, and then annotate a POJO with @WebService, and, tada, instant web service.
The distribution has several jars in it (around a dozen I think, but they're all in the install -- you don't have to go crawling the web for them), however, but the implementation is top notch and the "simple" stuff simply works.
Edit: JAX-WS can be readily deployed in Tomcat and Jetty, and comes "for free" in Glassfish and Glassfish V3 Prelude.
|
[Jetty](http://www.mortbay.org/jetty/) is a lightweight servlet container that you might want to look into.
|
Looking for lightweight java stack for creating SOAP based web services
|
[
"",
"java",
"web-services",
"soap",
""
] |
I want to use the [php simple HTML DOM parser](http://simplehtmldom.sourceforge.net/manual_api.htm) to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set\_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?
I guess im wondering why I use this, and what does it do as I have never come across a callback function before!
|
Here's a basic callback function example:
```
<?php
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
```
You can call a function that has its name stored in a variable like this: **$variable()**.
So, in the above example, we pass the name of the **thisFuncGetsCalled** function to **thisFuncTakesACallback()** which then calls the function passed in.
|
A callback function will use that function on whatever data is returned by a particular method.
I'm not sure how this particular library works, but it could be something as simple as:
```
$html = file_get_html('http://example.com');
$html->set_callback('make_bold');
$html->find('#title'); // returns an array
function make_bold($results) {
// make the first result bold
return '<b>'.$results[0].'</b>';
}
```
ie, The function "`make_bold()`" will be run on any data found. Again, I'm not sure how this particular library works (ie, what methods the callback function will get called on)
|
What is a callback function and how do I use it with OOP
|
[
"",
"php",
"oop",
"dom",
"callback",
"function-calls",
""
] |
Ok. I'm having an issue with the following bit of code:
```
StreamReader arrComputer = new StreamReader(FileDialog.FileName);
```
My first question had been answered already now my second question focuses on the tail end of this code.
I'm reading a text file `StreamReader` that the user selects with a button event using `OpenFileDialog`
```
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.InitialDirectory = @"C:\";
fileDialog.Filter = "Text|*.txt|All|*.*";
if (fileDialog.ShowDialog() == DialogResult.OK) ;
textBox1.Text = fileDialog.FileName;
buttonRun.Enabled = true;
}
```
The later in the code the user will click a "Run" button to execute some code against each item in the list.
I'm having problems using StreamReader to parse the list using the following code:
```
private void buttonRun_Click(object sender, EventArgs e)
{
StreamReader arrComputer = new StreamReader(FileDialog.FileName);
}
```
This is the error I receive from my coding:
```
"An object reference is required for the non-static field, method, or property 'System.Windows.Forms.FileDialog.FileName.get' "
```
I think I understand the problem but I'm having a hard time working it out.
|
Looks to me like you're creating a new OpenFileDialog object in your button1\_Click method, and storing the only reference to that object in a local variable, fileDialog.
Then, in your buttonRun\_Click method, it looks like you wanted to get the file name from the dialog you created in the previous method. That's not what you're doing, though. The compiler interprets your code as an attempt to read the FileName property of the FileDialog class as though it were a static member. There are other problems in your code, but the problem that's causing the compiler error you've cited is likely the FileDialog.FileName issue.
You mean to read the FileName property from the OpenFileDialog instance you created in the first method, but that object is only stored in a local variable. You have no access to it outside that first method. But since you've also stored the file name in the text box, you can read the file name out of that text box, so you don't need access to the OpenFileDialog object.
|
Don't you think you need to use textBox1.Text?
```
StreamReader arrComputer = new StreamReader(textBox1.Text);
```
|
An object reference is required for the non-static field, method, or property
|
[
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.
When I receive these emails, I wish to decode the name. but there are other names which are
not base64. How can I differentiate whether a string is base64 or not, using the **jython** programming language?
Ie.
First attachment:
```
------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="Copy of Book1.xls"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Copy of Book1.xls"
```
second attachment:
```
------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
```
Please note both "**Content-Transfer-Encoding**" have base64
|
> Please note both `Content-Transfer-Encoding` have base64
Not relevant in this case, the `Content-Transfer-Encoding` only applies to the body payload, not to the headers.
```
=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=
```
That's an **RFC2047**-encoded header atom. The stdlib function to decode it is `email.header.decode_header`. It still needs a little post-processing to interpret the outcome of that function though:
```
import email.header
x= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?='
try:
name= u''.join([
unicode(b, e or 'ascii') for b, e in email.header.decode_header(x)
])
except email.Errors.HeaderParseError:
pass # leave name as it was
```
However...
```
Content-Type: application/vnd.ms-excel;
name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
```
This is simply wrong. What mailer created it? RFC2047 encoding can only happen in atoms, and a quoted-string is not an atom. RFC2047 §5 explicitly denies this:
> * An 'encoded-word' MUST NOT appear within a 'quoted-string'.
The accepted way to encode parameter headers when long string or Unicode characters are present is **RFC2231**, which is a whole new bag of hurt. But you should be using a standard mail-parsing library which will cope with that for you.
So, you could detect the `'=?'` in filename parameters if you want, and try to decode it via RFC2047. However, the strictly-speaking-correct thing to do is to take the mailer at its word and really call the file `=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=`!
|
The header value tells you this:
```
=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=
"=?" introduces an encoded value
"gb2312" denotes the character encoding of the original value
"B" denotes that B-encoding (equal to Base64) was used (the alternative
is "Q", which refers to something close to quoted-printable)
"?" functions as a separator
"uLG..." is the actual value, encoded using the encoding specified before
"?=" ends the encoded value
```
So splitting on "?" actually gets you this (JSON notation)
```
["=", "gb2312", "B", "uLGxvmhlbrixsb5nLnhscw==", "="]
```
In the resulting array, if "B" is on position 2, you face a base-64 encoded string on position 3. Once you decoded it, be sure to pay attention to the encoding on position 1, probably it would be best to convert the whole thing to UTF-8 using that info.
|
how to tell if a string is base64 or not
|
[
"",
"python",
"jython",
"base64",
"mime",
""
] |
One of the frequent causes of memory leaks in .Net are event handlers which are never removed from their source objects.
Will this WCF code cause a memory leak, or will the lambda go out of scope too, allowing both the proxy class and the handler to be GCed?
```
void AMethod()
{
WCFClient proxy;
proxy = new WCFClient();
proxy.RemoteOperationCompleted += (sender, e) => proxy.Close();
proxy.Open();
proxy.RemoteOperationAsync();
}
```
|
Here's my test - note the explicit `proxy` set to `null` in the lambda - without it the `WeakReference` lives and therefore a leak is likely:
```
public class Proxy
{
private bool _isOpen;
public event EventHandler Complete;
public void Close()
{
_isOpen = false;
}
public void Open()
{
_isOpen = true;
}
public void RemoteOperationAsync()
{
if (!_isOpen)
throw new ApplicationException();
Thread.Sleep(1000);
if (Complete != null)
Complete(this, EventArgs.Empty);
}
}
public static class Program
{
public static void Main()
{
WeakReference wr = null;
{
var proxy = new Proxy();
proxy.Complete += (sender, e) =>
{
proxy.Close();
wr = new WeakReference(proxy);
proxy = null;
};
proxy.Open();
proxy.RemoteOperationAsync();
}
GC.Collect(GC.GetGeneration(wr));
GC.WaitForPendingFinalizers();
Console.WriteLine("[LAMBDA] Is WeakReference alive? " + wr.IsAlive);
}
}
```
|
Don't forget that the proxy's don't correctly implement IDisposable. If an error occurs the code above will not clean up the connection and the handle will remain until the parent process is closed.
|
Will this WCF client side code cause a memory leak?
|
[
"",
"c#",
".net",
"wcf",
"lambda",
""
] |
> **Possible Duplicate:**
> [Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents)
I want to use STL with the current program I'm working on and the vendor doesn't support what I feel is a reasonable STL, working is not my idea of reasonable. I have been unable to find a C++ Standard or an STL standard that is not just an API that leaves me wondering if my interpretation is correct or if the vendor interpretation is correct. I've already spent a great deal of time at [SGI's site](http://www.sgi.com/tech/stl/table_of_contents.html). Any reccomendations? Also, is there any document that's not an API that would be considered the standard?
|
Information on where to get the current standard document:
[Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-x-standard#83763)
Other responses in that question have information on downloads of various drafts of the standards which can be obtained free (the actual ratified standards cannot be obtained free).
|
The draft of the current C++0x standard is available from [this page](http://www.research.att.com/~bs/C++.html) and the official homepage of the C++ standards committee is [here](http://www.open-std.org/jtc1/sc22/wg21/).
|
Where can I look at the C++ standard
|
[
"",
"c++",
"stl",
""
] |
My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every second, checks the mouse position, adds and/or updates the count of the mouse position on this List.
I would like to have a similar running thread (again, I think System.Timers.Timer is a good choice) which would again raise an event once a second to automatically Refresh() the DataGridView so that the user can see the data on the screen update. (like TaskManager does.)
Unfortunately, calling the DataGridView.Refresh() method results in VS2005 stopping execution and noting that I've run into a cross-threading situation.
If I'm understanding correctly, I have 3 threads now:
* Primary UI thread
* MousePos List thread (Timer)
* DataGridView Refresh thread (Timer)
To see if I could Refresh() the DataGridView on the primary thread, I added a button to the form which called DataGridView.Refresh(), but this (strangely) didn't do anything. I found a topic which seemed to indicate that if I set DataGridView.DataSource = null and back to my List, that it would refresh the datagrid. And indeed this worked, but only thru the button (which gets handled on the primary thread.)
---
So this question has turned into a two-parter:
1. Is setting DataGridView.DataSource to null and back to my List an acceptable way to refresh the datagrid? (It seems inefficient to me...)
2. How do I safely do this in a multi-threaded environment?
---
Here's the code I've written so far (C#/.Net 2.0)
```
public partial class Form1 : Form
{
private static List<MousePos> mousePositionList = new List<MousePos>();
private static System.Timers.Timer mouseCheck = new System.Timers.Timer(1000);
private static System.Timers.Timer refreshWindow = new System.Timers.Timer(1000);
public Form1()
{
InitializeComponent();
mousePositionList.Add(new MousePos()); // ANSWER! Must have at least 1 entry before binding to DataSource
dataGridView1.DataSource = mousePositionList;
mouseCheck.Elapsed += new System.Timers.ElapsedEventHandler(mouseCheck_Elapsed);
mouseCheck.Start();
refreshWindow.Elapsed += new System.Timers.ElapsedEventHandler(refreshWindow_Elapsed);
refreshWindow.Start();
}
public void mouseCheck_Elapsed(object source, EventArgs e)
{
Point mPnt = Control.MousePosition;
MousePos mPos = mousePositionList.Find(ByPoint(mPnt));
if (mPos == null) { mousePositionList.Add(new MousePos(mPnt)); }
else { mPos.Count++; }
}
public void refreshWindow_Elapsed(object source, EventArgs e)
{
//dataGridView1.DataSource = null; // Old way
//dataGridView1.DataSource = mousePositionList; // Old way
dataGridView1.Invalidate(); // <= ANSWER!!
}
private static Predicate<MousePos> ByPoint(Point pnt)
{
return delegate(MousePos mPos) { return (mPos.Pnt == pnt); };
}
}
public class MousePos
{
private Point position = new Point();
private int count = 1;
public Point Pnt { get { return position; } }
public int X { get { return position.X; } set { position.X = value; } }
public int Y { get { return position.Y; } set { position.Y = value; } }
public int Count { get { return count; } set { count = value; } }
public MousePos() { }
public MousePos(Point mouse) { position = mouse; }
}
```
|
**UPDATE!** -- I *partially* figured out the answer to **part #1** in the book "Pro .NET 2.0 Windows Forms and Customer Controls in C#"
I had originally thought that **Refresh()** wasn't doing anything and that I needed to call the **Invalidate()** method, to tell Windows to repaint my control at it's leisure. (which is usually right away, but if you need a guarantee to repaint it *now*, then follow up with an immediate call to the Update() method.)
```
dataGridView1.Invalidate();
```
But, it turns out that the **Refresh()** method is merely an alias for:
```
dataGridView1.Invalidate(true);
dataGridView1.Update(); // <== forces immediate redraw
```
The only glitch I found with this was that if there was no data in the dataGridView, no amount of invalidating would refresh the control. I had to reassign the datasource. Then it worked fine after that. But only for the amount of rows (or items in my list) -- If new items were added, the dataGridView would be unaware that there were more rows to display.
So it seems that when binding a source of data (List or Table) to the Datasource, the dataGridView counts the items (rows) and then sets this internally and never checks to see if there are new rows/items or rows/items deleted. This is why re-binding the datasource repeatedly was working before.
Now to figure out how to update the number of rows to display in dataGridView without having to re-bind the datasource... fun, fun, fun! :-)
---
After doing some digging, I think I have my answer to **part #2** of my question (aka. safe Multi-threading):
Rather than using *System.Timers.Timer*, I found that I should be using **System.Windows.Forms.Timer** instead.
The event occurs such that the method that is used in the Callback automatically happens on the primary thread. No cross-threading issues!
The declaration looks like this:
```
private static System.Windows.Forms.Timer refreshWindow2;
refreshWindow2 = new Timer();
refreshWindow2.Interval = 1000;
refreshWindow2.Tick += new EventHandler(refreshWindow2_Tick);
refreshWindow2.Start();
```
And the method is like this:
```
private void refreshWindow2_Tick(object sender, EventArgs e)
{
dataGridView1.Invalidate();
}
```
|
You have to update the grid on the main UI thread, like all the other controls. See control.Invoke or Control.BeginInvoke.
|
How do I safely populate with data and Refresh() a DataGridView in a multi-threaded application?
|
[
"",
"c#",
".net",
"multithreading",
"datagridview",
"delegates",
""
] |
I'm trying to put a Message back into an MSMQ when an exception is thrown. The following code appears to work but the Message is not put back in the queue?
```
Message msg = null;
try
{
MessageQueue MQueue = new MessageQueue(txtMsgQPath.Text);
msg = MQueue.ReceiveById(txtQItemToRead.Text);
lblMsgRead.Text = msg.Body.ToString(); // This line throws exception
}
catch (Exception ex)
{
lblMsgRead.Text = ex.Message;
if (msg != null)
{
MessageQueue MQ = new MessageQueue(txtMsgQPath.Text);
MQ.Send(msg);
}
}
```
|
Couple of points: The best way to do this would be using a transaction spanning both queues; that way you'll know you won't lose a message.
The second part of it is to be careful about how the queues are created and how you submit messages to the second queue. In particular, MSMQ sometimes appears to "fail silently" when sending a message (though in reality an error message is recorded elsewhere in the dead letter queues), particularly if the transactional options of the send don't match the transactional nature of the target queue.
|
Is it really your intention to send that message back to the originator? Sending it back to yourself is very dangerous, you'll just bomb again, over and over.
|
Resend to MSMQ after exception
|
[
"",
"c#",
".net",
"msmq",
""
] |
Im trying to find a best practice to load usercontrols using Ajax.
My first approach where simply using an UpdatePanel and popuplating it with LoadControl() on ajax postbacks but this would rerender other loaded usercontrols in the same UpdatePanel. Also I cannot have a predefined set of UpdatePanels since the number of UserControls I need to load will vary.
Is there any best practice for this type of scenario?
If needed I could implement a framework or some type of custom controls if that would be a solution but I would love to do this with ASP.NET 3.5 and the AjaxControlToolkit if possible.
|
Probably dozens of high-brow reasons for not doing it this way, but simply initalizing a page, adding the usercontrol, then executing and dump the resulting HTML wherever it may behoove you, is (in my simpleminded view) so mind-numbingly fast & fun that I just have to mention it...
Skip the UpdatePanels, just use a Label, a plain old span, or how about an acronym...
Using JQuery on the client side:
```
$('#SomeContainer').Load("default.aspx?What=GimmeSomeSweetAjax");
```
ServerSide:
```
if(Request.QueryString["What"]==GimmeSomeSweetAjax)
{
Page page = new Page();
Control control = (Control)LoadControl("~/.../someUC.ascx");
StringWriter sw = new StringWriter();
page.Controls.Add(control);
Server.Execute(page, sw, false);
Response.Write(sw.ToString());
Response.Flush();
Response.Close();
}
```
Nothing else executes, and the page's lifecycle has a real Kevorkian moment ;-)
|
I'm not sure, but maybe [this tutorial by Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx) could be useful.
|
Load usercontrols using Ajax
|
[
"",
"c#",
"asp.net",
"ajax",
""
] |
This loop is slower than I would expect, and I'm not sure where yet. See anything?
I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before they are put into the ostringstream buffer.
```
void LoadRecordsetIntoStream(_RecordsetPtr& pRs, ostringstream& ostrm)
{
ADODB::FieldsPtr pFields = pRs->Fields;
char buf[80];
::SYSTEMTIME sysTime;
_variant_t var;
while(!pRs->EndOfFile) // loop through rows
{
for (long i = 0L; i < nColumns; i++) // loop through columns
{
var = pFields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
ostrm << (const char*) (_bstr_t) var;
}
else if (V_VT(&var) == VT_I4
|| V_VT(&var) == VT_UI1
|| V_VT(&var) == VT_I2
|| V_VT(&var) == VT_BOOL)
{
ostrm << itoa(((int)var),buf,10);
}
else if (V_VT(&var) == VT_DATE)
{
::VariantTimeToSystemTime(var,&sysTime);
_stprintf(buf, _T("%4d-%02d-%02d %02d:%02d:%02d"),
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
ostrm << buf;
}
}
pRs->MoveNext();
}
}
```
EDIT: After more experimentation...
I know now that about half the time is used by this line:
var = pFields->GetItem(i)->GetValue();
If I bypass the Microsoft generated COM wrappers, will my code be faster? My guess is no.
The othe half of the time is spent in the statements which convert data and stream it into the ostringstream.
I don't know right now as I write this whether it's the conversions or the streaming that is taking more time.
Would it be faster if I didn't use ostringstream and instead managed my own buffer, with my own logic to grow the buffer (re-alloc, copy, delete)? Would it be faster if my logic made a pessimistic guesstimate and reserved a lot of space for the ostringstream buffer up front? These might be experiments worth trying.
Finally, the conversions themselves. None of the three stand out in my timings as being bad. One answer says that my itoa might be slower than an alternative. Worth checking out.
|
Try commenting out the code in the for loop and comparing the time. Once you have a reading, start uncommenting various sections until you hit the bottle-neck.
|
I can't tell from looking at your code, someone more familiar with COM/ATL may have a better answer.
By trial n error I would find the slow code by commenting out inner loop operations out until you see perf spike, then you have your culprit and should focus on that.
|
What do you think is making this C++ code slow? (It loops through an ADODB recordset, converts COM types to strings, and fills an ostringstream)
|
[
"",
"c++",
"com",
"stl",
"adodb",
""
] |
I was wondering peoples opinions on the naming of ID columns in database tables.
If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.
Where I am workind current they have called all ID columns ID.
So they would do the following:
```
Select
i.ID
, il.ID
From
Invoices i
Left Join InvoiceLines il
on i.ID = il.InvoiceID
```
Now, I see a few problems here:
1. You would need to alias the columns on the select
2. ID = InvoiceID does not fit in my brain
3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?
What are other peoples thoughts on the topic?
|
ID is a SQL Antipattern.
See <http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&field-keywords=sql+antipatterns&sprefix=sql+a>
If you have many tables with ID as the id you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requiring you to use aliases to differentiate on the report itself.
Further if someone is foolish enough to use a natural join in a database where they are available, you will join to the wrong records.
If you would like to use the USING syntax that some dbs allow, you cannot if you use ID.
If you use ID you can easily end up with a mistaken join if you happen to be copying the join syntax (don't tell me that no one ever does this!)and forget to change the alias in the join condition.
So you now have
```
select t1.field1, t2.field2, t3.field3
from table1 t1
join table2 t2 on t1.id = t2.table1id
join table3 t3 on t1.id = t3.table2id
```
when you meant
```
select t1.field1, t2.field2, t3.field3
from table1 t1
join table2 t2 on t1.id = t2.table1id
join table3 t3 on t2.id = t3.table2id
```
If you use tablenameID as the id field, this kind of accidental mistake is far less likely to happen and much easier to find.
|
I always prefered ID to TableName + ID for the id column and then TableName + ID for a foreign key. That way all tables have a the same name for the id field and there isn't a redundant description. This seems simpler to me because all the tables have the same primary key field name.
As far as joining tables and not knowing which Id field belongs to which table, in my opinion the query should be written to handle this situation. Where I work, we always prefece the fields we use in a statement with the table/table alias.
|
Naming of ID columns in database tables
|
[
"",
"sql",
"naming-conventions",
""
] |
I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)
|
For those of not crazy about VB, here it is in c#:
Note, you have to add a reference to *Microsoft Shell Controls and Automation* from the COM tab of the References dialog.
```
public static void Main(string[] args)
{
List<string> arrHeaders = new List<string>();
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder objFolder;
objFolder = shell.NameSpace(@"C:\temp\testprop");
for( int i = 0; i < short.MaxValue; i++ )
{
string header = objFolder.GetDetailsOf(null, i);
if (String.IsNullOrEmpty(header))
break;
arrHeaders.Add(header);
}
foreach(Shell32.FolderItem2 item in objFolder.Items())
{
for (int i = 0; i < arrHeaders.Count; i++)
{
Console.WriteLine(
$"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
}
}
}
```
|
# Solution 2016
Add following NuGet packages to your project:
* `Microsoft.WindowsAPICodePack-Shell` by Microsoft
* `Microsoft.WindowsAPICodePack-Core` by Microsoft
### Read and Write Properties
```
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
string filePath = @"C:\temp\example.docx";
var file = ShellFile.FromFilePath(filePath);
// Read and Write:
string[] oldAuthors = file.Properties.System.Author.Value;
string oldTitle = file.Properties.System.Title.Value;
file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
file.Properties.System.Title.Value = "Example Title";
// Alternate way to Write:
ShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();
propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
propertyWriter.Close();
```
**Important:**
The file must be a valid one, created by the specific assigned software. Every file type has specific extended file properties and not all of them are writable.
If you right-click a file on desktop and cannot edit a property, you wont be able to edit it in code too.
Example:
* Create txt file on desktop, rename its extension to docx. You can't
edit its `Author` or `Title` property.
* Open it with Word, edit and save
it. Now you can.
So just make sure to use some `try` `catch`
Further Topic:
[Microsoft Docs: Implementing Property Handlers](https://learn.microsoft.com/en-us/windows/win32/properties/building-property-handlers)
|
Read/Write 'Extended' file properties (C#)
|
[
"",
"c#",
"extended-properties",
""
] |
How do I enable double-buffering of a control using C# (Windows forms)?
I have a panel control which I am drawing stuff into and also an owner-drawn tab control. Both suffer from flicker, so how can I enable double-buffering?
|
In the constructor of your control, set the DoubleBuffered property, and/or ControlStyle appropriately.
For example, I have a simple DoubleBufferedPanel whose constructor is the following:
```
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.ContainerControl |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor
, true);
```
|
some info here:
[How to double buffer .NET controls on a form?](https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form)
|
How do I enable double-buffering of a control using C# (Windows forms)?
|
[
"",
"c#",
".net",
"winforms",
"doublebuffered",
"ownerdrawn",
""
] |
What's the best .NET PDF editing library available, and why?
It needs to be used on an IIS web-server.
Specifically, I need to edit a PDF which was generated by reporting services.
Factors I'm interested in:
1. Speed
2. Memory Consumption
3. Price
4. Quality of documentation
5. Library stability
6. Size of library
7. Whatever else you think is important
|
Have a look at [iTextSharp](http://itextsharp.sourceforge.net/). iTextSharp is a port of the [iText](http://www.lowagie.com/iText/) , a free Java-Pdf library.
To quote iText:
You can use iText to:
* Serve PDF to a browser
* Generate dynamic documents from XML files or databases
* Use PDF's many interactive features
* Add bookmarks, page numbers, watermarks, etc.
* Split, concatenate, and manipulate PDF pages
* Automate filling out of PDF forms
* Add digital signatures to a PDF file
* And much more...
|
[Syncfusion Essential PDF](https://www.syncfusion.com/products/file-formats/pdf) is the best. I have been using it for years. Also, Syncfusion provides a best support compared to other vendors.
|
Best Server-side .NET PDF editing library
|
[
"",
"c#",
".net",
"asp.net",
"vb.net",
"pdf",
""
] |
What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just
```
String content = new File("test.txt").readFully();
```
|
Use the [Apache Commons IOUtils](http://commons.apache.org/io/description.html) package. In particular the `IOUtils` class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.
e.g.
```
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
```
|
I think using a Scanner is quite OK with regards to conciseness of Java on-board tools:
```
Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());
```
Also, it's quite flexible, too (e.g. regular expressions support, number parsing).
|
Most concise way to read the contents of a file/input stream in Java?
|
[
"",
"java",
""
] |
I have one user who gets an error message when he closes his browser. This only happens when he has visited a page which contains my applet. It seems to have been registered as a bug at Sun but that was many years ago. He is using Java 1.6 and IE7.
Has anyone seen this before and know a solution or work-around?
```
java.lang.NullPointerException: null pData
at sun.awt.windows.WComponentPeer.hide(Native Method)
at java.awt.Component.removeNotify(Unknown Source)
at java.awt.Container.removeNotify(Unknown Source)
at java.awt.Container.removeNotify(Unknown Source)
at java.awt.Container.removeAll(Unknown Source)
at sun.plugin.viewer.frame.IExplorerEmbeddedFrame.windowClosed(Unknown Source)
at java.awt.Window.processWindowEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
```
**UPDATE** The user removed Google Desktop and the problem has not occured since. So there you go... Thanks everyone!
|
I used to get that error a lot for just about every applet that was loaded in the browser. I never figured out *how*, but Google Desktop was breaking java in some way. After uninstalling google desktop the error went away.
|
I don't know a solution but I know a prevention of this problem.
If javascript is enabled in your web browser then place this code in a script tag inside your head tag of the html file from which applet is opened:
```
<SCRIPT language = "JavaScript">
window.onunload = function() { document.body.innerHTML = ""; }
</script>
```
|
Applet - 'java.lang.NullPointerException: null pData' when browser closed
|
[
"",
"java",
"applet",
"nullpointerexception",
""
] |
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?
Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...
|
I ended up writing a python parser myself. I managed to do it by following the spec here:
<http://www.w3.org/TR/wbxml/>
And then taking the code tables from the horde.org cvs.
The open mobile alliance's site and documentation are terrible, this was a very trying project :(
|
Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.
Those <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loaded. WBXML represents tags by an index number to avoid transmitting the same tag name hundreds of times, and the table that maps index numbers to tag names has to be supplied separately from the WBXML document itself. From a vague glance at [the libwbxml source](http://libwbxml.aymerick.com/browser/wbxml2/trunk/src/wbxml_tables.c) it seems like libwbxml has a bunch of tag tables hard coded. It has tables for SyncML 1.0-1.2; I think my Nokia E71 sends SyncML 1.3 (if so, your N95 probably does too), which it looks like libwbxml doesn't support yet.
Getting it to work might be as simple as adding a SyncML 1.3 table to libwbxml. That said, last time I tried, pywbxml doesn't compile against the vanilla libwbxml source, so you have to apply some patches first... so "simple" may be a relative term.
|
Decoding a WBXML SyncML message from an S60 device
|
[
"",
"python",
"s60",
"syncml",
"wbxml",
""
] |
In eclipse 3.4 I'm trying to do some performance tests on a large product, one of the included libraries is the vecmath.jar (javax.vecmath package) from the Java3D project. Everything was working fine and then when trying to run it yesterday I get this exception/error not long after starting it up:
```
java.lang.UnsupportedClassVersionError: javax/vecmath/Point2f (Unsupported major.minor version 49.0)
```
Which I believe means that I'm trying to load a java 1.5 class file into a 1.4 jvm which is unsupported. However when I went to the class file to check this I saw this in the eclipse class file viewer:
```
Compiled from Point2f.java (version 1.2 : 46.0, super bit)
```
So the class loader says it is version 49.0 but the class file says its 46.0. I've tried cleaning and fully rebuilding the project, I've confirmed that the compiler version for the project is 1.4, the JRE is 1.4 and for the run configuration the 1.4 jvm is selected. I'm totally stuck on this, does anyone have any idea what might be causing this?
Thanks
===EDIT===
It turns out that a version of java3d which was incompatible with java 1.4.2 had been installed in C:\Program Files\java\j2re1.4.2\_18\lib\ext. I installed a newer version of Java3D to play around with in java6 and i guess it installed the libs in all my JREs even the ones which were incompatible.
|
Could there be another javax.vecmath.Point2f on your classpath?
|
I believe JRE 1.5 is required for the latest version of Java3D.
|
Eclipse class version bug
|
[
"",
"java",
"eclipse",
"class",
"classpath",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.