Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
As an easter egg for a part of one of my sites, I have in my footer #left tag a "Easter" egg that changes each time you click it, revealing funny messages:
```
$('#left').append(" <span><a href='#' id='dontclick1'>Don't click.</a></span>");
// time for some fun
$('#dontclick1').click(function () {
$('#left span').html("<a href='#' id='dontclick2'>I told you not to click.</a>");
return false;
});
$('#dontclick2').click(function () {
$('#left span').html('<a href="#" id="dontclick3">Now you will suffer.</a>');
return false;
});
$('#dontclick3').click(function () {
$('#left span').html('<a href="#" id="dontclick4">Shame!</a>');
return false;
});
$('#dontclick4').click(function () {
$('#left span').html('<a href="#" id="dontclick5">You shouldn\'t click.</a > ');
return false;
});
$('#dontclick5').click(function () {
$('#left span').html('<a href="#" id="dontclick6">But you did. Sigh.</a>');
return false;
});
```
In my footer, the append adds the message dynamically so people without JavaScript won't see something unclickable. However, the first time it's clicked, it changes to the second message, but it won't work after that.
What am I doing wrong? Is it because of the `return false` inside there? Without it, it jumps to the top of the page. I'm confused. | You can use `live()` as others have mentioned. For an alternative let me suggest a little more elegant solution using an array of messages and a single `click` handler.
```
$('#left').append(" <a href='#' id='dontclick'>Don't click.</a>");
// time for some fun
var messageNumber = 0;
$("#dontclick").click(function() {
var messages = [
"I told you not to click.",
"Now you will suffer.",
"Shame!",
"You shouldn't click.",
"But you did. Sigh."
];
$(this).text(messages[messageNumber]);
// Cycle to the next message unless we're already there.
if (messageNumber < messages.length - 1) {
messageNumber += 1;
}
return false;
});
```
I've changed it so you just create the `<a id='dontclick'>` once, and it doesn't need a number any more. The `click` handler is only registered once and each time it's called it displays a different message in the `#dontclick` link. The `$(this)` in the `$(this).text(...)` line, by the way, refers to `$("#dontclick")`. It's just a little shorter to write `$(this)`. | Err... that's a pretty horrible way of doing what you want, but you will fix it by replacing all the `.click` with `.live('click'` - at the time of you appending the events to all the elements, `dontclick2`, `3`, etc. do not yet exist. Read up on [live](http://docs.jquery.com/Events/live) for more, or search around this site as this problem comes up quite often.
**EDIT**:
I couldn't resist. While John's answer provides a decent way for doing what you want, I am not a huge fan of mixing the Javascript with the markup like this. Whenever you want to add new funny messages and such you will have to be messing around with Javascript arrays and such which is kind of uncool.
The *best* way to do this (at least in my humble opinion) would be to have markup like this in your page:
```
<ul id="easter_messages" style="display: none;">
<li>Don't click</li>
<li>I told you not to click.</li>
<li>Now you will suffer.</li>
<li>Shame!</li>
<li>You shouldn't click.</li>
<li>But you did. Sigh.</li>
</ul>
```
This would be a semantically correct representation of what you have. You could use CSS like this on it:
```
#easter_messages ul, #easter_messages li { margin: 0; padding: 0; }
#easter_messages li { cursor: pointer; list-style-type: none; display: inline; }
```
And finally, use this jQuery code:
```
$('#easter_messages').show().find('li').hide().click(function() {
var $li = $(this).next('li');
if($li.length == 1) {
$(this).hide();
$li.show();
}
}).filter(':first').show();
```
This code would essentially show the list, bind a click handler that finds the next list element relative to the one being clicked on, if it finds one it hides itself and shows that one, and then outside the click we show the first one to get things started.
[And this is an example of it in action](http://jsbin.com/aloqo). | jQuery won't replace anymore after the first time | [
"",
"javascript",
"jquery",
"html",
"scripting",
""
] |
Is it possible to speed up this snippet?
**firstSample** and **lastSample** is the part of the array I'm interested in this iteration. It's when this interval reaches > 3000 that I get a noticeable slowdown. The **\_average** array can contain 6-60 million int values.
**minY** and **maxY** is the result I use after this calculation is completed.
```
int minY = Int32.MaxValue;
int maxY = Int32.MinValue;
int Y = 0;
int sample = firstSample + 1;
while (sample <= lastSample)
{
Y = _average[sample];
minY = Math.Min(Y, minY);
maxY = Math.Max(Y, maxY);
sample++;
}
``` | The \_average[sample] expression is a huge bottleneck, since it contains an implicit bounds check on each iteration. Use a pointer to the "\_average" array (and the unsafe keyword). Then avoid calling any functions, so get rid of the Math.Min/Max calls and do that checks yourself.
Without any compiler at my hands right now, I think this is how it should look:
```
unsafe
{
fixed ( int* paverage = _average )
{
int* p = paverage + firstSample + 1;
for ( int sample = firstSample+1 ; sample <= lastSample ; sample++ )
{
if ( *p < minY )
minY = *p;
if ( *p > maxY )
maxY = *p;
p++;
}
}
}
```
Then finally, since "sample" is not actually used in the loop, you can change it to a loop variable that counts down to zero, so that the loop termination check is done against a constant (zero) instead of a variable. | You wrote the following in a comment:
> I'm not sorting. Only finding the max and min of an interval. And the interval moves every 20ms
It seems that you actually want a *moving minimum* and *moving maximum*.
I believe that this can be done more efficiently than to re-search the entire interval each time, assuming that the interval moves only in one direction, and that there is significant overlap between subsequent intervals.
One way would be to keep a special queue, where every new element copies its value to every element in the queue that is bigger (for the moving minimum), e.g.:
```
(5 8 4 7 7 0 7 0 4 4 3 4 0 9 7 9 5 4 2 0) ; this is the array
(4 4 4 4) ; the interval is 4 elements long, and initialized to the minimum
; of the first 4 elements
(4 4 4 7) ; next step, note that the current minimum is always the first element
(4 7 7 0) ; now something happens, as 0 is smaller than the value before
(4 7 0 0) ; there are still smaller values ...
(4 0 0 0) ; and still ...
(0 0 0 0) ; done for this iteration
(0 0 0 7)
(0 0 0 0) ; the 0 again overwrites the fatties before
(0 0 0 4)
(0 0 4 4)
(0 3 3 3) ; the 3 is smaller than the 4s before,
; note that overwriting can be cut short as soon as a
; value not bigger than the new is found
(3 3 3 4)
(0 0 0 0) ; and so on...
```
If you move by more than 1 element each time, you can first calculate the minimum of all new values and use that for the back-overwriting.
Worst case for this algorithm is when the array is sorted descendingly, then it is O(nm), where m is the interval length and n the array length. Best case is when it is sorted descendingly, then it's O(n). For the average case, I conject O(n log(m)). | Help me optimize this average calculation snippet | [
"",
"c#",
".net",
"algorithm",
"optimization",
""
] |
I currently have a little script that downloads a webpage and extracts some data I'm interested in. Nothing fancy.
Currently I'm downloading the page like so:
```
import commands
command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx'
status, text = commands.getstatusoutput(command)
```
Although this works perfectly, I thought it'd make sense to remove the dependency on wget. I thought it should be trivial to convert the above to urllib2, but thus far I've had zero success. The Internet is full urllib2 examples, but I haven't found anything that matches my need for simple username and password HTTP authentication with a HTTPS server. | The [requests](http://www.python-requests.org/en/latest/) module provides a modern API to HTTP/HTTPS capabilities.
```
import requests
url = 'https://www.someserver.com/toplevelurl/somepage.htm'
res = requests.get(url, auth=('USER', 'PASSWORD'))
status = res.status_code
text = res.text
``` | [this](http://mail.python.org/pipermail/python-list/2003-July/213402.html) says, it should be straight forward
> [as] long as your local Python has SSL support.
If you use just HTTP Basic Authentication, you must set different handler, as described [here](http://www.voidspace.org.uk/python/articles/authentication.shtml).
Quoting the example there:
```
import urllib2
theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'
# a great password
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for urls
# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.
pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us
```
If you do Digest, you'll have to set some additional headers, but they are the same regardless of SSL usage. [Google](http://www.google.com/search?q=python+urllib2+http+digest) for python+urllib2+http+digest.
Cheers, | HTTPS log in with urllib2 | [
"",
"python",
"authentication",
"https",
"urllib2",
""
] |
A TimeSheetActivity class has a collection of Allocations. An Allocation is a value object that is used by other objects in the domain as well, looking something like this:
```
public class Allocation : ValueObject
{
public virtual StaffMember StaffMember { get; private set; }
public virtual TimeSheetActivity Activity { get; private set; }
public virtual DateTime EventDate { get ... }
public virtual TimeQuantity TimeSpent { get ... }
}
```
Duplicate allocations for the same Allocation.EventDate are not allowed. So when a client attempts to make an allocation to an activity, a check is made to see if there is already an Allocation in the collection for the same Allocation.EventDate. If not, then the new Allocation is added to the collection, but if so, the existing Allocation is replaced by the new one.
I am currently using a Dictionary to maintain the collection, with the Allocation.EventDate as the key. It works fine for the domain but I'm wondering if the fact that the key is already part of the value isn't itself a 'bad smell'.
I also have no reason to persist anything but the dictionary values. Because I'm using NHibernate, I may need to write some custom type do that, and I'm wondering if that also is a clue that I should be using a different type of collection. (That's also the reason for the the virtual properties in the Allocation class).
The primary alternative I'm thinking of would be a HashSet with a dedicated EqualityComparer.
What do you think?
Cheers,
Berryl | If you use an external comparer to do a `HashSet<Allocation>`, you would have to be very careful not to change the date without re-keying the value in the dictionary. You have this problem either way, but it is exacerbated by mutability (at least with `Dictionary<,>` it will still be able to track its own keys and values). With a mutable value as part of the key you risk never seeing the value again...
When I've worked on schedule systems in the past I've actually used `SortedList<,>` for this - similar, but useful if you generally want the data in sequence, and allows binary search if the data is fairly uniform. | I don't think the fact that the key is part of the value is necessarily a problem. In my experience that's quite frequently the case for dictionaries. A `HashSet` with an appropriate equality comparer would certainly work, so long as you never needed to get at the current object with a particular `EventDate`. That seems like a useful thing to be able to do, potentially...
Are you currently just concerned in a somewhat vague way, or do you have a concrete suspicion as to how this might bite you? | Collection lookups; alternative to Dictionary | [
"",
"c#",
"collections",
"dictionary",
"nhibernate-mapping",
"hashset",
""
] |
I've got some code here that works great on IPv4 machines, but on our build server (an IPv6) it fails. In a nutshell:
```
IPHostEntry ipHostEntry = Dns.GetHostEntry(string.Empty);
```
The documentation for GetHostEntry says that passing in string.Empty will get you the IPv4 address of the localhost. This is what I want. The problem is that it's returning the string "::1:" on our IPv6 machine, which I believe is the IPv6 address.
Pinging the machine from any other IPv4 machine gives a good IPv4 address... and doing a **"ping -4 machinename"** from itself gives the correct IPv4 address.... but pinging it regularly from itself gives "::1:".
How can I get the IPv4 for this machine, from itself? | Have you looked at [all the addresses](http://msdn.microsoft.com/en-us/library/system.net.iphostentry.addresslist(VS.80).aspx) in the return, discard the ones of [family InterNetworkV6](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.addressfamily(VS.80).aspx) and retain only the IPv4 ones? | To find all local IPv4 addresses:
```
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
```
or use `Array.Find` or `Array.FindLast` if you just want one. | Get IPv4 addresses from Dns.GetHostEntry() | [
"",
"c#",
".net",
"dns",
"ipv6",
"ipv4",
""
] |
What are the advantages and disadvantages of using one instead of the other in C++? | If you want to know the true answer, you should read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19422-01/819-3693/ncg_goldberg.html).
In short, although `double` allows for **higher precision** in its representation, for certain calculations it would produce **larger errors**. The "right" choice is: **use as much precision as you need but not more** and **choose the right algorithm**.
Many compilers do extended floating point math in "non-strict" mode anyway (i.e. use a wider floating point type available in hardware, e.g. 80-bits and 128-bits floating), this should be taken into account as well. In practice, you can **hardly see any difference in speed** -- they are natives to hardware anyway. | Unless you have some specific reason to do otherwise, use double.
Perhaps surprisingly, it is double and not float that is the "normal" floating-point type in C (and C++). The standard math functions such as **sin** and **log** take doubles as arguments, and return doubles. A normal floating-point literal, as when you write **3.14** in your program, has the type double. Not float.
On typical modern computers, doubles can be just as fast as floats, or even faster, so performance is usually not a factor to consider, even for large calculations. (And those would have to be *large* calculations, or performance shouldn't even enter your mind. My new i7 desktop computer can do six billion multiplications of doubles in one second.) | Should I use double or float? | [
"",
"c++",
"types",
"floating-point",
"double-precision",
""
] |
In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.
hasattr returns true regardless of whether the attribute is an instance method or not.
Any suggestions?
---
For example:
```
class Test(object):
testdata = 123
def testmethod(self):
pass
test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true
``` | ```
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
``` | You can use the `inspect` module:
```
class A(object):
def method_name(self):
pass
import inspect
print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True
``` | How to test if a class attribute is an instance method | [
"",
"python",
"methods",
"attributes",
"instance",
""
] |
Are there any howtos for using the PHP command line interactively?
I found a lot about running scripts that are in text files, but not really about the shell with the prompt where I type in commands:
```
$ php -a
Interactive shell
php > echo "hello world";
hello world
php > $a = 1;
php > echo $a;
1
php > exit;
$
```
When I go to the Linux shell and run `php -a` I get the PHP shell. Can I load classes that live in files? What are the rules here? | The rules aren't any different to a normal PHP script - just think of it like reading from a very slow disk... The only real difference is that it can't read ahead, so you have to define functions before you use them.
You can use include or require as normal to load classes. | Instructions to install phpsh in Ubuntu 10.04 Server edition.
Get phpsh source and extract
```
wget http://github.com/facebook/phpsh/zipball/master
sudo apt-get install unzip
mkdir temp
mv facebook-phpsh-8438f3f.zip temp
cd temp
unzip facebook-phpsh-8438f3f.zip
```
phpsh uses python, install dependencies
```
sudo apt-get install python-setuptools
sudo apt-get install linux-headers-$(uname -r)
sudo apt-get install build-essential
sudo apt-get install python-dev
sudo apt-get install sqlite3 libsqlite3-dev
sudo easy_install pysqlite
sudo apt-get install libncurses5-dev
sudo easy_install readline
```
Setup phpsh, run and see that is works
```
sudo python setup.py install
phpsh
$a = array("a"=>1,"b"=>2);
print_r($a)
``` | How to use the PHP command line interactively? | [
"",
"php",
"shell",
""
] |
I am downright annoyed because the Quartz release I'm importing does not have a proper POM file deployed ([maven repo](http://repo1.maven.org/maven2/opensymphony/quartz/1.6.3/)).
Therefore maven dutifully tries to download it on *every build*.
```
Downloading: http://repo1.maven.org/maven2/opensymphony/quartz/1.6.3/quartz-1.6.3.pom
```
I'd like to skip this step but *without going completely offline* since that is useful.
Ideas? | Add an additional repository, with this artifact and make sure the POM is correct. This way the main repo POM will be overridden. You can run repository manager such as [artifactory](http://www.jfrog.org/products.php) or [nexus](http://nexus.sonatype.org/) locally | If its a transitive dependency that isn't actually required, then you can use the [`<exclude />`](http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html) element to achieve this. | Disable download for a single dependency | [
"",
"java",
"maven-2",
"quartz-scheduler",
""
] |
I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email? | What you want is [turbomail](http://www.python-turbomail.org/). In documentation you have an entry where is explains how to integrate it with Pylons. | Can't you just use standard Python library modules, `email` to prepare the mail and `smtp` to send it? What extra value beyond that are you looking for from the "built-in feature"? | Sending an email from Pylons | [
"",
"python",
"pylons",
""
] |
I need to transfer files to my web server for processing and I'd like to do it in a generic way if possible.
I need to be able to transfer files from the following protocols at a minimum (with more to follow eventually):
HTTP
FTP
SCP
I'd really like to be able to send files to SMTP also
So my question, is there a toolkit available that does this already? If so, it must be open source as this is part of an open source project.
If there isn't a toolkit that already does this, what is the best way to structure an interface that will handle most file transfers?
I've thought about something like this:
```
public interface FileTransfer {
public void connect(URL url, String userid, String password);
public void disconnect();
public void getFile(String sourceFile, File destFile);
public void putFile(File sourceFile, File destFile);
}
```
And then a Factory that takes the source URL or protocol and instantiates the correct file handler. | [Apache commons VFS](http://commons.apache.org/vfs/) speaks to this problem, although a quick check didn't show that it will do SCP or SMTP. [Commons NET](http://commons.apache.org/net/) does SMTP, but I don't know that you could get the common interface out of the box. For [SCP](https://stackoverflow.com/questions/199624/scp-via-java), here are some possibilities.
The bottom line seems to be to check out the VFS implementation and see if it does something for you, perhaps you can extend it for different protocols. If it isn't appropriate, regarding your interface, you are probably going to want all remote file references to be Strings rather than File objects, and specifically a string representing a URI pointing to the remote location and telling you what protocol to use. | I'm working at a problem very similar to yours, I couldn't find any open source solution so I'm trying to sketch a solution myself. This is what I've come up with.
I think you should represent inputSources and outputSources as different things, like
```
public interface Input{
abstract InputStream getFileInputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for Blob on db etc)
public interface Output{
abstract OutputStream getOutputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for mailing the file etc)
```
Then you should have a Movement to describe which input should go to which output.
```
class Movement{
String inputId;
String outputId;
}
```
A class to describe the list of Movement to make.
```
class MovementDescriptor{
public addMovement(Movement a);
public Movement[] getAllMovements();
}
```
And then a class to perform the work itself.
```
class FileMover{
HashMap<String,Input> inputRegistry;
HashMap<String,Output> outputRegistry;
addInputToRegistry(Input a ){
inputRegistry.put(a.getId(),a);
}
addOutputToRegistry(Output a){
outputRegistry.put(a.getId(),a);
}
transferFiles(MovementDescriptor movementDescriptor){
Movement[] movements =movementDescriptor.getAllMovements();
foreach (Movement movement: movements){
//get the input Id
//find it in the registry and retrieve the associated InputStream
//get the output Id
//find it in the registry and retrieve the associated OutputStream
//copy the stream from the input to the output (you may want to use a temporary file in between)
}
}
}
```
The code that would use this would operate like this:
```
FileMover fm=new FileMover();
//Register your sources and your destinations
fm.addInputToRegistry(input);
fm.addOutputToRegistry(output)
// each time you have to make a movement create a MovementDescriptor and call
fm.transferFiles(movementDescriptor)
```
If you would like to exchange by mail our views on the subject, just send me an e mail at (my nickname)@gmail dot com.
NOTE: The code is just a sketch :-) | Java File Transfer API | [
"",
"java",
"file-io",
""
] |
I am using `boost::any` to store pointers and was wondering if there was
a way to extract a polymorphic data type.
Here is a simple example of what ideally I'd like to do, but currently doesn't work.
```
struct A {};
struct B : A {};
int main() {
boost::any a;
a = new B();
boost::any_cast< A* >(a);
}
```
This fails because a is storing a B\*, and I'm trying to extract an A\*. Is there a way to accomplish this?
Thanks. | The other way is to store an `A*` in the `boost::any` and then `dynamic_cast` the output. Something like:
```
int main() {
boost::any a = (A*)new A;
boost::any b = (A*)new B;
A *anObj = boost::any_cast<A*>(a);
B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL
anObj = boost::any_cast<A*>(b);
anotherObj = dynamic_cast<B*>(anObj); // <- this one works!
return 0;
}
``` | Boost.DynamicAny is a vairant on Boost.Any which provides more flexible dynamic casting of the underlying type. Whereas retreiving a value from Boost.Any requires that you know the exact type stored within the Any, Boost.DynamicAny allows you to dynamically cast to either a base or derived class of the held type.
<https://github.com/bytemaster/Boost.DynamicAny> | Boost::any and polymorphism | [
"",
"c++",
"polymorphism",
"boost-any",
""
] |
I'm looking for a way to restart a thread that has been stopped by Abort()..
```
public partial class MyProgram : Form
{
private Thread MyThread = new Thread(MyFunction);
private System.Windows.Forms.Button startStopBtn = new System.Windows.Forms.Button();
public MyProgram()
{
MyThread.Start();
startStopBtn += new EventHandler(doStop);
startStopBtn.Text = "Stop";
}
private static void MyFunction()
{
// do something
}
private void doStop(object sender, EventArgs e)
{
MyThread.Abort();
startStopBtn -= new EventHandler(doStop);
startStopBtn += new EventHandler(doStart);
startStopBtn.Text = "Start";
}
private void doStart(object sender, EventArgs e)
{
MyThread.Start(); // << Error returned when clicking the button for 2nd time
startStopBtn -= new EventHandler(doStart);
startStopBtn += new EventHandler(doStop);
startStopBtn.Text = "Stop";
}
}
```
Any idea? | Simply add `MyThread = new Thread(MyFunction)` before calling `MyThread.Start()` in `doStart()`. Do not create the thread outside of your methods, the space there is thought for declarations.
**Please note that killing a thread with thread.Abort() can be very dangerous, as it might cause [unexpected behavior](https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort) or might not correctly dispose resources owned by the thread. You should try to accomplish clean multi threading, like Groo described in [his answer](https://stackoverflow.com/a/1054956/130060).** | Once you have aborted your thread, you cannot start it again.
But your actual problem is that you are **aborting** your thread. You should [never use Thread.Abort()](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation).
If your thread should be paused and continued several times, you should consider using other mechanisms (like [AutoResetEvent](http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx), for example).
**[EDIT]**
The simplest solution to abort a thread, as mentioned by [Ian Griffiths](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) in the link above, is:
> The approach I always recommend is dead simple. Have a `volatile bool` field that is visible both to your worker thread and your UI thread. If the user clicks cancel, **set** this flag. Meanwhile, on your worker thread, **test** the flag from time to time. If you see it get set, stop what you're doing.
The only thing that you need to do to make it work properly, is to rearrange your background method so that it runs **in a loop** - so that you can periodically check if your flag has been set by a different thread.
If you need to have pause and resume functionality for the same worker thread, instead of the simple `volatile bool` flag approach, you could go for a slightly more complex approach, a synchronizing construct such as `AutoResetEvent`. These classes also provide a way to put the worker thread to sleep for a specified (or indefinite) amount of time between signals from the non-worker thread.
[This thread](https://stackoverflow.com/questions/142826/is-there-a-way-to-indefinitely-pause-a-thread/143153#143153) contains a concrete example with Start, Pause, Resume and Stop methods. Note how Brannon's example **never** aborts the thread. It only fires an event, and then waits until the thread finishes gracefully. | Restarting a thread in .NET (using C#) | [
"",
"c#",
"multithreading",
""
] |
I'm working in a LAMP environment, so PHP is the language; at least i can use python.
As the title said i have two unordered integer arrays.
```
$array_A = array(13, 4, 59, 38, 9, 69, 72, 93, 1, 3, 5)
$array_B = array(29, 72, 21, 3, 6)
```
I want to know how many integers these array have in common; in the example as you see the result is 2. I'm not interested in what integers are in common, like (72, 3).
I need a faster method than take every element of array B and check if it's in array A ( O(nxm) )
Arrays can be sorted through asort or with sql ordering (they came from a sql result).
An idea that came to me is to create a 'vector' for every array where the integer is a position who gets value 1 and integers not present get 0.
So, for array A (starting at pos 1)
```
(1, 0, 1, 1, 1, 0, 0, 0, 1, 0, ...)
```
Same for array B
```
(0, 0, 1, 0, 0, 1, ...)
```
And then compare this two vectors with one cycle. The problem is that in this way the vector length is about 400k. | The simplest way would be:
```
count(array_intersect($array_A, $array_B));
```
if I understand what you're after.
Should be fast. | Depending on your data (size) you might want to use [array\_intersect\_key()](http://php.net/array_intersect_key) instead of array\_intersect(). Apparently the implementation of array\_intersect (testing php 5.3) does not use any optimization/caching/whatsoever but loops through the array and compares the values one by one for each element in array A. The hashtable lookup is incredibly faster than that.
```
<?php
function timefn($fn) {
static $timer = array();
if ( is_null($fn) ) {
return $timer;
}
$x = range(1, 120000);
$y = range(2, 100000);
foreach($y as $k=>$v) { if (0===$k%3) unset($y[$k]); }
$s = microtime(true);
$fn($x, $y);
$e = microtime(true);
@$timer[ $fn ] += $e - $s;
}
function fnIntersect($x, $y) {
$z = count(array_intersect($x,$y));
}
function fnFlip($x, $y) {
$x = array_flip($x);
$y = array_flip($y);
$z = count(array_intersect_key($x, $y));
}
for ($i=0; $i<3; $i++) {
timefn( 'fnIntersect' );
timefn( 'fnFlip' );
}
print_r(timefn(null));
```
prints
```
Array
(
[fnIntersect] => 11.271192073822
[fnFlip] => 0.54442691802979
)
```
which means the array\_flip/intersect\_key method is ~20 times faster on my notebook.
(as usual: this is an ad hoc test. If you spot an error, tell me ...I'm expecting that ;-) ) | I have two unordered integer arrays, and i need to know how many integers these arrays have in common | [
"",
"php",
"arrays",
"sorting",
""
] |
I'm trying to use a feature of the Microsoft WinHttp library that has been exposed by the developers of Win32com. Unfortunately most of the library does not seem to be documented and there are no example of the correct way to use the win32inet features via the win32com library.
This is what I have so far:
```
import win32inet
hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0)
# Does not work!!!
proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 )
```
As you can see, all I am trying to do is use the win32inet feature to find out which proxy is the appropriate one to use for a given URL, int his case foo.com.
Can you help me correct the syntax of the last line? MSN has some [good documentation for the function being wrapped](http://msdn.microsoft.com/en-us/library/aa384097(VS.85).aspx) but the args do not seem to map the to those of the python library perfectly.
The fixed version of this script should:
* Be able to look up which proxy to use
for any given URL.
* It should always do exactly what Internet Explorer would do (i.e. use the same proxy)
* It should be valid on any valid Windows XP set-up. That means it should work with an explicitly configured proxy and also no proxy at all.
* It only needs to work on Windows XP 32bit with Python 2.4.4. It can use any official released version of win32com.
I'm using Python2.4.4 with Win32Com on Windows XP.
UPDATE 0:
OR... can you give me an alternative implementation in cTypes? As long as I can make it work I'm happy! | Here is the code which creates HINTERNET session and uses that to get proxy details, using ctypes to directly access winhttp DLL.
It works without any error but I have no proxy set on my machine, you may have to tweak few constants to get it right. Go thru the msdn links in code, from where I have seen the API.
```
import ctypes
import ctypes.wintypes
winHttp = ctypes.windll.LoadLibrary("Winhttp.dll")
# http://msdn.microsoft.com/en-us/library/aa384098(VS.85).aspx
# first get a handle to HTTP session
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY=0
WINHTTP_NO_PROXY_NAME=WINHTTP_NO_PROXY_BYPASS=0
WINHTTP_FLAG_ASYNC=0x10000000
HINTERNET = winHttp.WinHttpOpen("PyWin32", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC)
print HINTERNET
# now get proxy using HTTP session
# http://msdn.microsoft.com/en-us/library/aa384097(VS.85).aspx
"""
BOOL WinHttpGetProxyForUrl(
__in HINTERNET hSession,
__in LPCWSTR lpcwszUrl,
__in WINHTTP_AUTOPROXY_OPTIONS *pAutoProxyOptions,
__out WINHTTP_PROXY_INFO *pProxyInfo
);
"""
# create C structure for WINHTTP_AUTOPROXY_OPTIONS
#http://msdn.microsoft.com/en-us/library/aa384123(VS.85).aspx
"""
typedef struct {
DWORD dwFlags;
DWORD dwAutoDetectFlags;
LPCWSTR lpszAutoConfigUrl;
LPVOID lpvReserved;
DWORD dwReserved;
BOOL fAutoLogonIfChallenged;
} WINHTTP_AUTOPROXY_OPTIONS;
"""
class WINHTTP_AUTOPROXY_OPTIONS(ctypes.Structure):
_fields_ = [("dwFlags", ctypes.wintypes.DWORD),
("dwAutoDetectFlags", ctypes.wintypes.DWORD),
("lpszAutoConfigUrl", ctypes.wintypes.LPCWSTR),
("lpvReserved", ctypes.c_void_p ),
("dwReserved", ctypes.wintypes.DWORD),
("fAutoLogonIfChallenged",ctypes.wintypes.BOOL),]
WINHTTP_AUTOPROXY_AUTO_DETECT = 0x00000001;
WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001;
WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002;
options = WINHTTP_AUTOPROXY_OPTIONS()
options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT
options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP|WINHTTP_AUTO_DETECT_TYPE_DNS_A
options.lpszAutoConfigUrl = 0
options.fAutoLogonIfChallenged = False
# create C structure for WINHTTP_AUTOPROXY_OPTIONS
# http://msdn.microsoft.com/en-us/library/aa383912(VS.85).aspx
"""
struct WINHTTP_PROXY_INFO {
DWORD dwAccessType;
LPWSTR lpszProxy;
LPWSTR lpszProxyBypass;
};
"""
class WINHTTP_PROXY_INFO(ctypes.Structure):
_fields_ = [("dwAccessType", ctypes.wintypes.DWORD),
("lpszProxy", ctypes.wintypes.LPCWSTR),
("lpszProxyBypass", ctypes.wintypes.LPCWSTR),]
info = WINHTTP_PROXY_INFO()
ret = winHttp.WinHttpGetProxyForUrl(HINTERNET, "http://www.google.com", ctypes.pointer(options), ctypes.pointer(info) )
print "proxy success?",ret
if not ret:
# some error lets see what is that?
import win32api
import win32con
errorCode = win32api.GetLastError()
print "win32 Error:",errorCode
s = ""
print win32api.FormatMessage(errorCode)
print info.dwAccessType, info.lpszProxy, info.lpszProxyBypass
``` | Unless there is a strong reason for using `win32inet` (which is messy in this area due to limitations of `SWIG`), I recommend that you use `ctypes` instead. | What's the correct way to use win32inet.WinHttpGetProxyForUrl | [
"",
"python",
"windows",
"com",
"32-bit",
"winhttp",
""
] |
The below does not compile:
```
Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1);
```
> Local variable 'fac' might not be
> initialized before accessing
How can you make a recursive function with lambdas?
**[Update]**
Here are also two links that I found interesting to read:
1. [Eric Lippert's "Why does a recursive lambda cause a definite assignment error?"](http://blogs.msdn.com/ericlippert/archive/2006/08/18/why-does-a-recursive-lambda-cause-a-definite-assignment-error.aspx)
2. [Anonymous Recursion in C#](http://blogs.msdn.com/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx) | This particular style of function is not supported by C# as a single line declaration. You have to separate out the declaration and definition into 2 lines
```
Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);
``` | You'll have to create `fac` first und assign it later (which is pretty unfunctional because it depends on multiple assignment) or use so called [`Y-combinators`](http://blogs.msdn.com/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx).
Example:
```
delegate Func<TIn, TOut> FixedPointFunction<TIn, TOut>(Func<TIn, TOut> f);
static Func<T, TRes> Fix<T, TRes>(FixedPointFunction<T, TRes> f) {
return f(x => Fix(f)(x));
}
static void Main(string[] args) {
var fact = Fix<int, int>(f => x => (x <= 1) ? x : x * f(x - 1));
Console.WriteLine(fact(5));
}
```
But note that this might be somewhat hard to read/understand. | C#: Recursive functions with Lambdas | [
"",
"c#",
"recursion",
"lambda",
"factorial",
""
] |
I've a asp.net datagrid which shows customer order details.
Pagination at the bottom of the grid is done using datalist and asp.net Linkbutton controls.
Here is the code:
```
<asp:DataList ID="DataList2" runat="server" CellPadding="1" CellSpacing="1"
OnItemCommand="DataList2_ItemCommand"
OnItemDataBound="DataList2_ItemDataBound" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" runat="server"
CommandArgument='<%# Eval("PageIndex") %>'
CommandName="lnkbtnPaging"
Text='<%# Eval("PageText") %>' />
<asp:Label runat="server" ID="lblPageSeparator" Text=" | " name=></asp:Label>
</ItemTemplate>
</asp:DataList>
```
When the user clicks on any page number(ie.Link button), I need to set focus on top of the page.
How do i do this?
Thanks! | I think the default behaviour would be for the page scroll position to be set back to the top of the page. Is there anything else in your page that might be overriding this behaviour?
For example:
1. Is your DataList inside an UpdatePanel? In that case the current scroll position will be maintained over a (partial) post-back. You would therefore need to reset the scroll position to the top of the page yourself. One way to do this would be to implement a handler for the PageRequestManager's EndRequest client-side event which would set the scroll position - this thread explains [how](https://stackoverflow.com/questions/616210/reset-scroll-position-after-async-postback-asp-net)
2. Is the Page MaintainScrollPositionOnPostBack property set to true? | You could try setting a named anchor at the top of the page. Here is an article that explains it <http://www.w3schools.com/HTML/html_links.asp> | Setting focus on top of the page on click of asp.net link button | [
"",
"c#",
"asp.net",
""
] |
Since Python 2.6, it seems the documentation is in the new [reStructuredText](http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx) format, and it doesn't seem very easy to build a [Texinfo Info](http://en.wikipedia.org/wiki/Info_(Unix)) file out of the box anymore.
I'm an Emacs addict and prefer my documentation installed in Info.
Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?
I know I can use w3m or [haddoc](http://furius.ca/haddoc/) to view the html docs - I really want them in Info.
I've played with [Pandoc](http://johnmacfarlane.net/pandoc/) but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!
## Two good answers
Highlighting two answers below, because SO won't allow me to accept both answers:
* @wilfred-hughes: [Installing from MELPA](https://stackoverflow.com/a/18847967/17221) is the quickest way to get pre-build info into Emacs
* @alioth: [Building it yourself](https://stackoverflow.com/a/42739005/17221) looks like it's a lot easier than when I asked this question in 2009 | I've packaged up the [Python docs as a texinfo file](https://github.com/wilfred/python-info).
If you're using Emacs with MELPA, you can simply install this with `M-x package-install python-info`. | Jon Waltman <http://bitbucket.org/jonwaltman/sphinx-info> has forked sphinx and written a texinfo builder, it can build the python documentation (I've yet done it). It seems that it will be merged soon into sphinx.
Here's the quick links for the downloads (temporary):
* <http://dl.dropbox.com/u/1276730/python.info>
* <http://dl.dropbox.com/u/1276730/python.texi>
Steps to generate python doc in texinfo format:
Download the python source code
Download and install the [sphinx-info](http://bitbucket.org/jonwaltman/sphinx-info) package (in a virtualenv)
Enter in the Python/Doc directory from the python sources
Edit the Makefile, to the `build` target replace `$(PYTHON) tools/sphinx-build.py` with `sphinx-build`, then add this target to the makefile, pay attention, the space before echo is a TAB:
```
texinfo: BUILDER = texinfo
texinfo: build
@echo
@echo "Build finished. The Texinfo files are in _build/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
```
Edit the Python/Doc/conf.py adding:
```
texinfo_documents = [
('contents', 'python', 'Python Documentation', 'Georg Brandl',
'Python', 'The Python Programming Language', 'Documentation tools',
1),
]
```
Then run `make texinfo` and it should produce the texifile in the build/texinfo directory.
To generate the info file run `makeinfo python.texi` | How do you get Python documentation in Texinfo Info format? | [
"",
"python",
"emacs",
"restructuredtext",
"texinfo",
""
] |
Let's say I have a DataTable:
```
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Country", typeof(string)));
dt.Columns.Add(new DataColumn("State", typeof(string)));
```
Now I populate it
```
DataRow dn = dt.NewRow();
dn["Country"] = "1";
dn["State"] == "2";
// Add it
dt.Rows.Add(dn);
```
That works fine. Now if Country and State are zero, I don't want it to add to the table. For example:
```
dn["Country"] = "0";
dn["State"] = "0";
if (dn["Country"].ToString() != "0" &&
dn["State"].ToString() != "0")
dt.Rows.Add(dn);
```
That doesn't work. What am I doing wrong there? I've tried setting type to int and that didn't help much either...
Thanks,
Jim
**Update**:
This is more like what I'm doing:
```
dn["Country"] = (from c in db.Country where c.Zone == 3 select c.Code).Count();
```
Now if that were to return Zero, the row should not be added to the DataTable. What instead happens is that if the count is greater than 0, its not added either.
**Update 2**
Got it to work with Any() for now, as suggested by Jon Skeet below. Thanks everyone! | By "that doesn't work" do you mean the row gets added anyway? That sounds very odd - do you have a short but complete program which demonstrates the problem?
Here's a short but complete program which *does* work:
```
using System;
using System.Data;
class Test
{
static void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Country", typeof(string)));
dt.Columns.Add(new DataColumn("State", typeof(string)));
DataRow dn = dt.NewRow();
dn["Country"] = "0";
dn["State"] = "0";
if (dn["Country"].ToString() != "0" &&
dn["State"].ToString() != "0")
{
Console.WriteLine("Broken");
dt.Rows.Add(dn);
}
else
{
Console.WriteLine("Working");
}
}
}
```
It's hard to tell exactly what you're doing based on snippets, but is it possible that you're changing the values of a row which is *already* in the `DataTable`, instead of one which hasn't been added yet?
EDIT: This is a pretty strange line of code you've got:
```
dn["Country"] = (from c in db.Country where c.Zone == 3 select c.Code).Count();
```
Why would you set the *country* to a *count*? Furthermore, if you only care about the *count* why are you bothering with the projection?
Finally, I'd probably just use a local variable instead of putting it in the datarow to start with:
```
int count = db.Country.Where(c => c.Zone == 3).Count();
if (count != 0)
{
// Use count, add the row etc
}
```
Oh, and if you don't really need the count, but just need to know whether it's non-zero, use `Any`:
```
if (db.Country.Any(c => c.Zone == 3))
{
// ...
}
``` | Your populate code is wrong, i don't know if this is a typo or directly from your source.
You wrote
```
//the "==" won't assign anything to the dn["State"] column
dn["State"] == "2";
```
where you actually need
```
//the "=" will
dn["State"] = "2";
```
Because the State column never gets populated your if condition won't work.
```
if (dn["Country"].ToString() != "0"
&& dn["State"].ToString() != "0")
//this will always be false because dn["State"] was never assigned to
```
Another point is that if the column hasn't had a value specified the value will be DBNull. You should perhaps modify your check to also see if the values are DBNull, you can do this using the [IsNull](http://msdn.microsoft.com/en-us/library/system.data.datarow.isnull.aspx) method.
I hope this helps :-) | Peculiar problem | [
"",
"c#",
"asp.net",
""
] |
Is the multiple inheritance in Java and Perl the same? | There is no multiple inheritance in Java, but single inheritance + multiple interface implementation, while Perl does have multiple inheritance. | Don't know about Perl, but Java only allows multiple inheritance of interface. Only single-inheritance is allowed for implementation. | Is multiple inheritance in Perl and Java the same? | [
"",
"java",
"perl",
"inheritance",
""
] |
Using the STL C++ hash\_map...
```
class MyKeyObject
{
std::string str1;
std::string str2;
bool operator==(...) { this.str1 == that.str1 ... }
};
class MyData
{
std::string data1;
int data2;
std::string etcetc;
};
```
like this...
```
MyKeyObject a = MyKeyObject(...);
MyData b = MyData(...);
stdext::hash_map <MyKeyObject, MyData> _myDataHashMap;
_myDataHashMap[ a ] = b;
```
I get a whole load of errors. Here are the first three...
> Error 1 error C2784: 'bool
> std::operator <(const
> std::\_Tree<\_Traits> &,const
> std::\_Tree<\_Traits> &)' : could not
> deduce template argument for 'const
> std::\_Tree<\_Traits> &' from 'const
> MyKeyObject' c:\program files\microsoft
> visual studio
> 8\vc\include\functional 143
>
> Error 2 error C2784: 'bool
> std::operator <(const
> std::basic\_string<\_Elem,\_Traits,\_Alloc>
> &,const \_Elem \*)' : could not deduce
> template argument for 'const
> std::basic\_string<\_Elem,\_Traits,\_Alloc>
> &' from 'const
> Tasking::MyKeyObject' c:\program
> files\microsoft visual studio
> 8\vc\include\functional 143
>
> Error 3 error C2784: 'bool
> std::operator <(const \_Elem \*,const
> std::basic\_string<\_Elem,\_Traits,\_Alloc>
> &)' : could not deduce template
> argument for 'const \_Elem \*' from
> 'const MyDataObject' c:\program
> files\microsoft visual studio
> 8\vc\include\functional 143
>
> ...
If I set the key to something simple like an int all is well.
What am I doing wrong?! Maybe I need to do something with templates?
Is there a better (quicker?) way of accessing data using a custom key object like this? | Try the following, worked for me in VS 2005. This is a solution for both VS2005 built-in hash\_map type in stdext namespace as well as the boost unordered\_map (preferred). Delete whichever you don't use.
```
#include <boost/unordered_map.hpp>
#include <hash_map>
class HashKey
{
public:
HashKey(const std::string& key)
{
_key=key;
}
HashKey(const char* key)
{
_key=key;
}
// for boost and stdext
size_t hash() const
{
// your own hash function here
size_t h = 0;
std::string::const_iterator p, p_end;
for(p = _key.begin(), p_end = _key.end(); p != p_end; ++p)
{
h = 31 * h + (*p);
}
return h;
}
// for boost
bool operator==(const HashKey& other) const
{
return _key == other._key;
}
std::string _key;
};
// for boost
namespace boost
{
template<>
class hash<HashKey>
{
public :
std::size_t operator()(const HashKey &mc) const
{
return mc.hash();
}
};
}
// for stdext
namespace stdext
{
template<>
class hash_compare<HashKey>
{
public :
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
size_t operator()(const HashKey &mc) const
{
return mc.hash();
}
bool operator()(const HashKey &mc1, const HashKey &mc2) const
{
return (mc1._key < mc2._key);
}
};
}
int _tmain(int argc, _TCHAR* argv[])
{
{
stdext::hash_map<HashKey, int> test;
test["one"] = 1;
test["two"] = 2;
}
{
boost::unordered_map<HashKey, int> test(8); // optional default initial bucket count 8
test["one"] = 1;
test["two"] = 2;
}
return 0;
}
``` | To use a hash table, you need to specify a hash function. You need to create a function object which represents a function that takes a `MyKeyObject` object and returns a `size_t`. Then you pass the functor as the second argument after the initial size:
```
hash_map <MyKeyObject, MyData> _myDataHashMap(initial_size, YourHashFunctor());
```
Alternately, you can write your hash function as the template specialization of the `hash<T>` functor for your type; that way you don't need to pass in a custom hash function.
I don't know why you are getting those errors specifically. Perhaps it's trying to use the your object as the hash code or something? In any case it should not work without a hash function. Hash functions are pre-defined for the integer types and strings. | How to use stdext::hash_map where the key is a custom object? | [
"",
"c++",
"stl",
"hashmap",
""
] |
I'm trying to create a very simple message board (author, text, and date written) that will auto-update every few moments to see if a new message has arrived, and if it has, auto load the latest message(s).
I'm proficient in PHP, but my knowledge in AJAX is lacking.
The way I see it, I would have to create a PHP file called `get_messages.php` that would connect to a database and get through a `$_GET` variable return all posts beyond date `X`, and then I would somehow through jquery call this PHP file every few minutes with `$_GET=current time`?
Does this sound correct?
How would I got about requesting and returning the data to the web page asynchronously? | You're pretty close, you'll need a PHP script that can query the database for your results. Next, you'll want to transfigure those results into an array, and [json\_encode()](https://www.php.net/json_encode) them:
```
$results = getMyResults();
/* Assume this produce the following Array:
Array(
"id" => "128","authorid" => "12","posttime" => "12:53pm",
"comment" => "I completely agree! Stackoverflow FTW!"
);
*/
print json_encode($results);
/* We'll end up with the following JSON:
{
{"id":"128"},{"authorid":"12"},{"posttime":"12:53pm"},
{"comment":"I completely agree! Stackoverflow FTW!"}
}
*/
```
Once these results are in JSON format, you can better handle them with javascript. Using jQuery's [ajax functionality](http://docs.jquery.com/Ajax), we can do the following:
```
setInterval("update()", 10000); /* Call server every 10 seconds */
function update() {
$.get("serverScript.php", {}, function (response) {
/* 'response' is our JSON */
alert(response.comment);
}, "json");
}
```
Now that you've got your data within javascript ('response'), you are free to use the information from the server. | Ignore the ASP.NET stuff, this link is a good start:
<http://www.aspcode.net/Timed-Ajax-calls-with-JQuery-and-ASPNET.aspx>
What you're going to use is a javascript function called setTimeout, which asynchronously calls a javascript function on an interval. From there, jQuery has a fancy function called "load" that will load the results of an AJAX call into a DIV or whatever element you're looking for. There are also numerous other ways to get jQuery to do alter the DOM the way you'd like.
There are a hundred ways to do this, but I'd say avoid writing plain Javascript to save yourself the headache of cross-browser functionality when you can. | AJAX calling a PHP code and getting a response every few minutes | [
"",
"php",
"ajax",
"wxwidgets",
""
] |
I'm including a PHP script that changes the URL.
```
// index.php
ob_start();
include "script.php";
// This script redirects using header("Location:");
$out = ob_get_clean();
// I use the $out data for calculations
echo $out;
```
Is there a simple way to counter or undo this unwanted redirect? How about:
```
header("Location: index.php"); // redirect back to self
```
But this causes an endless redirect loop... any ideas?
Or is there a way to strip out the header() calls from the $out buffer, preventing it from ever reaching the client? | Just for future references. As of PHP 5.3 there's a new function called [header\_remove()](http://www.php.net/manual/en/function.header-remove.php) which helps dealing with such situations. | You could try to overwrite that header field with an invalid value, such as:
```
header('Location: ', true);
```
But I don’t know how the clients react on that. | How do I prevent an included PHP script from changing the Location URL? | [
"",
"php",
"url",
"redirect",
"location",
""
] |
What is the proper way to implement assignment by value for a reference type? I want to perform an assignment, but not change the reference.
Here is what I'm talking about:
```
void Main()
{
A a1 = new A(1);
A a2 = new A(2);
a1 = a2; //WRONG: Changes reference
a1.ValueAssign(a2); //This works, but is it the best way?
}
class A
{
int i;
public A(int i)
{
this.i = i;
}
public void ValueAssign(A a)
{
this.i = a.i;
}
}
```
Is there some sort of convention I should be using for this? I feel like I'm not the first person that has encountered this. Thanks.
EDIT:
Wow. I think I need to tailor my question more toward the actual problem I'm facing. I'm getting a lot of answers that do not meet the requirement of not changing the reference. Cloning is not the issue here. The problem lies in ASSIGNING the clone.
I have many classes that depend on A - they all share a reference to the same object of class A. So, whenever one classes changes A, it's reflected in the others, right? That's all fine and well until one of the classes tries to do this:
```
myA = new A();
```
In reality I'm not doing `new A()` but I'm actually retrieving a serialized version of A off the hard drive. But anyways, doing this causes myA to receive a NEW REFERENCE. It no longer shares the same A as the rest of the classes that depend on A. This is the problem that I am trying to address. I want all classes that have the instance of A to be affected by the line of code above.
I hope this clarifies my question. Thank you. | I wish there was a "second best" answer option, because anyone who mentioned Observer deserves it. The observer pattern would work, however it is not necessary and in my opinion, is overkill.
If multiple objects need to maintain a reference to the same object ("MyClass", below) and you need to perform an *assignment* to the referenced object ("MyClass"), the easiest way to handle it is to create a ValueAssign function as follows:
```
public class MyClass
{
private int a;
private int b;
void ValueAssign(MyClass mo)
{
this.a = mo.a;
this.b = mo.b;
}
}
```
Observer would only be necessary if *other* action was required by the dependent objects at the time of assignment. If you wish to only maintain the reference, this method is adequate. This example here is the same as the example that I proposed in my question, but I feel that it better emphasizes my intent.
Thank you for all your answers. I seriously considered all of them. | It sounds like you're talking about cloning. Some objects will support this (via [`ICloneable`](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx)) but most won't. In many cases it doesn't make sense anyway - what does it mean to copy a `FileStream` object? `ICloneable` is generally regarded as a bad interface to use, partly because it doesn't specify the depth of the clone.
It's better to try to change your way of thinking so this isn't necessary. My guess is that you're a C++ programmer - and without wishing to cast any judgements *at all*: don't try to write C# as if it's C++. You'll end up with unidiomatic C# which may not work terrible well, may be inefficient, and may be unintuitive for C# developers to understand.
One option is to try to make types immutable where possible - at that point it doesn't *matter* whether or not there's a copy, as you wouldn't be able to change the object anyway. This is the approach that `String` takes, and it works very well. It's just a shame that there aren't immutable collections in the framework (yet).
In your case, instead of having the `ValueAssign` method, you would have `WithValue` which would return a *new* instance with just the value changed. (Admittedly that's the only value available in your case...) I realise that this sort of copying (of all but the property that's about to change) goes against what I was saying about copying being somewhat unidiomatic in C#, but it's within the class rather than an outside body deciding when to copy.
I suspect I'm not explaining this terribly well, but my general advice is to design around it rather than to try to explicitly copy all over the place. | Value assignment for reference type in C# | [
"",
"c#",
".net",
""
] |
Are there any HashMap implementations that expose hook methods for profiling the performance of the Map (average chain length, best / worst / average access time, #rehashes, etc.).
It seems quite common to use HashMap and "hope for the best" with regards to ~O(1) access time, without analysing whether this is really the case but I'd like to measure the performance at runtime (at least during development), so anything that hooks into JMX or profiling software would also be good.
Also, Is anyone aware of HashMap implementations where the chains are based on binary trees instead of linked lists?
Thanks in advance. | There's a new Java profiler that goes some way towards doing what you're after. **CollectionSpy** ([www.collectionspy.com](http://www.collectionspy.com)) tracks the number of internal rehashes of any hashing container, and also has a graph visualization of the bucket list lenghts. Doesn't (yet) provide any timing info though. | On the second part of your question, if you're looking for a fast Hashmap implementation with some decent real-time guarantees have a look at [Javolution](http://javolution.org/). It's fast, reliable and goes into a decent amount of detail on performance. | HashMap profiling | [
"",
"java",
"algorithm",
"data-structures",
""
] |
I think what I want to do is a fairly common task but I've found no reference on the web. I have text with punctuation, and I want a list of the words.
```
"Hey, you - what are you doing here!?"
```
should be
```
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
```
But Python's `str.split()` only works with one argument, so I have all words with the punctuation after I split with whitespace. Any ideas? | A case where regular expressions are justified:
```
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
``` | [re.split()](http://docs.python.org/library/re.html#re.split)
> re.split(pattern, string[, maxsplit=0])
>
> Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.)
```
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
``` | Split Strings into words with multiple word boundary delimiters | [
"",
"python",
"string",
"split",
""
] |
The code below allows the user to enter in a phrase in plain English, which is then added to a database as "$site". If the user enters in an apostrophe, the phrase is stored with a backslash in front of the apostrophe. How can I get the variable "$site" to be added to the database without backslashes in front of apostrophes?
```
print "<div class=\"siteadd\">
<form action='process.php?find=$find1' method='post'>
Add a book to this topic: <input name='site' type='text' size='50'>
<input type='submit' value='Submit'>
</form>
</div>";
```
Then, in process.php:
```
$site = str_replace($remove_array, "", $_POST['site']);
$site = strtolower($site);
$site = mysql_real_escape_string($site);
$illegal = array("/", "\"");
$site = str_replace($illegal, '', $site);
mysql_query("INSERT INTO `$find` VALUES (NULL, '$site',1,0)");
``` | I assume the backslash is added by PHP for security reasons. Read more about [magic quotes](http://pl.php.net/magic_quotes). And since you’re using the proper function to escape strings passed to mysql queries, you don’t have to rely on PHP’s dummy escaping.
At the beginning of the script, check if `magic_quotes` are on, and if so, remove the slashes:
```
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
```
BTW, in your code, `$find` variable comes from an untrusted source and should be escaped/filtered as well. | The call to `mysql_real_escape_string()` is probably the reason (<https://www.php.net/mysql_real_escape_string>), but you might also have Magic Quotes enabled on your server (<http://php.net/manual/en/security.magicquotes.php>). | Removing a backslash from an apostrophe in PHP | [
"",
"php",
""
] |
I'd like to update a page based upon the results of multiple ajax/json requests. Using jQuery, I can "chain" the callbacks, like this very simple stripped down example:
```
$.getJSON("/values/1", function(data) {
// data = {value: 1}
var value_1 = data.value;
$.getJSON("/values/2", function(data) {
// data = {value: 42}
var value_2 = data.value;
var sum = value_1 + value_2;
$('#mynode').html(sum);
});
});
```
However, this results in the requests being made serially. I'd much rather a way to make the requests in parallel, and perform the page update after all are complete. Is there any way to do this? | Try this solution, which can support any specific number of parallel queries:
```
var done = 4; // number of total requests
var sum = 0;
/* Normal loops don't create a new scope */
$([1,2,3,4,5]).each(function() {
var number = this;
$.getJSON("/values/" + number, function(data) {
sum += data.value;
done -= 1;
if(done == 0) $("#mynode").html(sum);
});
});
``` | jQuery [$.when()](http://api.jquery.com/jQuery.when/) and [$.done()](http://api.jquery.com/deferred.done/) are exactly what you need:
```
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
``` | Parallel asynchronous Ajax requests using jQuery | [
"",
"javascript",
"jquery",
"ajax",
""
] |
is there a best way to deploy to the GAC?
is dragging the dll to the GAC sufficient? | Read [How to install an assembly into the Global Assembly Cache in Visual C#](http://support.microsoft.com/kb/815808).
Your assembly needs a strong name, but basically dragging the DLL to the GAC is sufficient. | The way to deploy to the GAC is to use a Setup project. | deploying to the GAC | [
"",
"c#",
"visual-studio",
"gac",
""
] |
I want to create a new business application using the Django framework. Any suggestions as to what I can use as a reporting framework? The application will need to generate reports on various business entities including summaries, totals, grouping, etc. Basically, is there a Crystal reports-like equivalent for Django/Python? | There is a grid on djangopackages.com which may be of use evaluating options:
<https://www.djangopackages.com/grids/g/reporting/> | I made [django-report-builder](https://github.com/burke-software/django-report-builder). It lets you build ORM queries with a gui and generate spreadsheet reports. It can't do templates, that would be a great feature to add though. | Django Reporting Options | [
"",
"python",
"django",
"reporting",
""
] |
I have a site which uses AJAX and preloaders. Now I would like to see the impact of these preoloaders before deploying the site online.
The "problem" is that localhost doesn't have loading time and the response is immediate, so that I can't see my preloaders.
How can I simulate loading or limited bandwidth (with Firefox, Rails or whatever else)? | I don't have a rails app in front of me right now but why don't you just add a delay to the appropriate controller?
i.e.
```
def index
# ...
sleep 2 # sleeps for 2 seconds
# ...
end
```
Alternatively, use a debugger and place a breakpoint in the controller code. This should mean that your preloader will show until execution is continued. | If on windows, download [Fiddler](http://www.fiddler2.com/fiddler2/) and set it to act like you are on a modem:
Tools-->Performance-->Simulate Modem Speeds
[edit]
Since you said you are now on a MAC, you have Charles which has [throttling](http://www.charlesproxy.com/documentation/using-charles/throttling/)
[/edit] | Simulate loading on localhost | [
"",
"javascript",
"ruby-on-rails",
"preload",
"image-preloader",
""
] |
I have an application which supports multiple types and versions of some devices. It can connect to these devices and retrieve various information.
Depending on the type of the device, I have (among other things) a class which can contain various properties. Some properties are common to all devices, some are unique to a particular device.
This data is serialized to xml.
What would be a preferred way to implement a class which would support future properties in future versions of these devices, as well as be backwards compatible with previous application versions?
I can think of several ways, but I find none of them great:
* Use a collection of name-value pairs:
+ **pros**: good backward compatibility (both xml and previous versions of my app) and extensibility,
+ **cons**: no type safety, no intellisense, requires implementation of custom xml serialization (to handle different `value` objects)
* Create derived properties class for each new device:
+ **pros**: type safety
+ **cons**: have to use `XmlInclude` or custom serialization to deserialize derived classes, no backward compatibility with previous xml schema (although by implementing custom serialization I *could* skip unknown properties?), requires casting for accessing properties in derived classes.
* Another way to do it?
I am using C#, by the way. | How about something similar to a [PropertyBag](http://www.codeproject.com/KB/recipes/propertybag.aspx) ? | If you're not limited to interoperability with an external schema, then you should use Runtime Serialization and the SoapFormatter. The pattern for runtime serialization permits derived classes to specify which of their properties need to be serialized and what to do with them when deserialized.
The XML Serializer requires XmlInclude because, in effect, it needs to define the schema to use. | Creating an extensible properties class (OOP) | [
"",
"c#",
"oop",
"inheritance",
"xml-serialization",
""
] |
I'm trying to find out how to programmatically (I'm using C#) determine the name (or i.p.) of servers to which my workstation has current maps. In other words, at some point in Windows Explorer I mapped a network drive to a drive letter (or used "net use w: " to map it). I know how to get the network drives on the system:
```
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Network)
{
}
}
```
But the DriveInfo class does not have properties that tell me what server and shared folder the mapped drive is associated with. Is there somewhere else I should be looking? | Have you tried to use WMI to do it?
```
using System;
using System.Management;
using System.Windows.Forms;
public static void Main()
{
try
{
var searcher = new ManagementObjectSearcher(
"root\\CIMV2",
"SELECT * FROM Win32_MappedLogicalDisk");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_MappedLogicalDisk instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Access: {0}", queryObj["Access"]);
Console.WriteLine("Availability: {0}", queryObj["Availability"]);
Console.WriteLine("BlockSize: {0}", queryObj["BlockSize"]);
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("Compressed: {0}", queryObj["Compressed"]);
Console.WriteLine("ConfigManagerErrorCode: {0}", queryObj["ConfigManagerErrorCode"]);
Console.WriteLine("ConfigManagerUserConfig: {0}", queryObj["ConfigManagerUserConfig"]);
Console.WriteLine("CreationClassName: {0}", queryObj["CreationClassName"]);
Console.WriteLine("Description: {0}", queryObj["Description"]);
Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
Console.WriteLine("ErrorCleared: {0}", queryObj["ErrorCleared"]);
Console.WriteLine("ErrorDescription: {0}", queryObj["ErrorDescription"]);
Console.WriteLine("ErrorMethodology: {0}", queryObj["ErrorMethodology"]);
Console.WriteLine("FileSystem: {0}", queryObj["FileSystem"]);
Console.WriteLine("FreeSpace: {0}", queryObj["FreeSpace"]);
Console.WriteLine("InstallDate: {0}", queryObj["InstallDate"]);
Console.WriteLine("LastErrorCode: {0}", queryObj["LastErrorCode"]);
Console.WriteLine("MaximumComponentLength: {0}", queryObj["MaximumComponentLength"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
Console.WriteLine("NumberOfBlocks: {0}", queryObj["NumberOfBlocks"]);
Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);
if(queryObj["PowerManagementCapabilities"] == null)
Console.WriteLine("PowerManagementCapabilities: {0}", queryObj["PowerManagementCapabilities"]);
else
{
UInt16[] arrPowerManagementCapabilities = (UInt16[])(queryObj["PowerManagementCapabilities"]);
foreach (UInt16 arrValue in arrPowerManagementCapabilities)
{
Console.WriteLine("PowerManagementCapabilities: {0}", arrValue);
}
}
Console.WriteLine("PowerManagementSupported: {0}", queryObj["PowerManagementSupported"]);
Console.WriteLine("ProviderName: {0}", queryObj["ProviderName"]);
Console.WriteLine("Purpose: {0}", queryObj["Purpose"]);
Console.WriteLine("QuotasDisabled: {0}", queryObj["QuotasDisabled"]);
Console.WriteLine("QuotasIncomplete: {0}", queryObj["QuotasIncomplete"]);
Console.WriteLine("QuotasRebuilding: {0}", queryObj["QuotasRebuilding"]);
Console.WriteLine("SessionID: {0}", queryObj["SessionID"]);
Console.WriteLine("Size: {0}", queryObj["Size"]);
Console.WriteLine("Status: {0}", queryObj["Status"]);
Console.WriteLine("StatusInfo: {0}", queryObj["StatusInfo"]);
Console.WriteLine("SupportsDiskQuotas: {0}", queryObj["SupportsDiskQuotas"]);
Console.WriteLine("SupportsFileBasedCompression: {0}", queryObj["SupportsFileBasedCompression"]);
Console.WriteLine("SystemCreationClassName: {0}", queryObj["SystemCreationClassName"]);
Console.WriteLine("SystemName: {0}", queryObj["SystemName"]);
Console.WriteLine("VolumeName: {0}", queryObj["VolumeName"]);
Console.WriteLine("VolumeSerialNumber: {0}", queryObj["VolumeSerialNumber"]);
}
}
catch (ManagementException ex)
{
MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
}
}
```
to make it a little easier to get started download [WMI Code Creater](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en) | You could use WMI to enumerate and query mapped drives. The following code enumerates mapped drives, extracts the server name portion, and prints that out.
```
using System;
using System.Text.RegularExpressions;
using System.Management;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"select * from Win32_MappedLogicalDisk");
foreach (ManagementObject drive in searcher.Get()) {
Console.WriteLine(Regex.Match(
drive["ProviderName"].ToString(),
@"\\\\([^\\]+)").Groups[1]);
}
}
}
}
}
```
You can find the documentaiton of the Win32\_MappedLogicalDisk class [here](http://msdn.microsoft.com/en-us/library/aa394194(VS.85).aspx). An intro for accessing WMI from C# is [here](http://www.geekpedia.com/tutorial73_An-introduction-in-retrieving-WMI-in-Csharp.html). | How to programmatically discover mapped network drives on system and their server names? | [
"",
"c#",
".net",
"windows",
""
] |
I'm trying to put a small animation on a page. I've got 2 divs side by side, the second of which has its content called via Ajax, so the div height varies without page refresh.
```
<div id="number1" style="float:left; padding-bottom:140px">Static content, 200px or so</div>
<div id="number2" style="float:left">AJAX content here</div>
<div style="clear:left"></div>
<img src="image" margin-top:-140px" />
```
This basically gives me a 2 column layout, and the image nests up underneath the left hand column no matter what the height. All good!
The thing I'm trying to do though is animate the transition of the image when the page height changes thanks to incoming Ajax content. At present the image jerks around up and down, I'd quite like to have it smoothly glide down the page.
Is this possible? I'm not really into my JavaScript, so I'm not sure how to do this. I'm using the jQuery library on the site, so could that be a way forward? | OK, I've just put together a very quick and dirty example.
Here's the HTML:
```
<body>
<a href="####" id="addContent">Add content</a>
<div id="outerContainer">
<div id="left" class="col">
<p>Static content</p>
<img src="images/innovation.gif" width="111px" height="20px">
</div>
<div id="right" class="col">
<p>Ajax content</p>
</div>
</div>
</body>
```
The jQuery used is here
```
jQuery(function($){
var addedHTML = "<p class='added'>Lorem ipsum dolor sit amet, Nunc consectetur, magna quis auctor mattis, lorem neque lobortis massa, ac commodo massa sem sed nunc. Maecenas consequat consectetur dignissim. Aliquam placerat ullamcorper tristique. Sed cursus libero vel magna bibendum luctus. Nam eleifend volutpat neque, sed tincidunt odio blandit luctus. Morbi sit amet metus elit. Curabitur mollis rhoncus bibendum. Phasellus eget metus eget mi porttitor lacinia ac et augue. Nulla facilisi. Nam magna turpis, auctor vel vehicula vitae, tincidunt eget nisl. Duis posuere diam lacus.</p>";
$("#addContent").click(function(e){
$("#right").append(addedHTML);
var rightHeight = $("#right").height();
//Animate the left column to this height
$("#left").animate({
height: rightHeight
}, 1500);
});});
```
And CSS:
```
#outerContainer {
position: relative;
border: 1px solid red;
margin: 20px auto 0;
overflow: hidden;
width: 400px;}
.col {
width: 180px;
display: inline;
padding: 0 0 40px;}
#left {
float: left;
border: 1px solid cyan;
position: relative;}
#left img {
position: absolute;
bottom: 0;
left: 0;}
#right {
position: absolute;
top: 0;
left: 180px;
border: 1px solid green;}
#addContent {
text-align: center;
width: 100px;
margin: 20px auto 0;
display: block;}
```
I have added a button just to add some 'Ajax' content. When you do this it grabs the new height of the div and animates to that height. You could add some easing to the animation / change the speed to make it a little more polished.
I hope this helps. | Maybe you could use a container around the content divs (with overflow hidden) and resize that one according to the height of the contents, thus achieving what you're trying to do? | JavaScript animate resizing div | [
"",
"javascript",
"jquery",
"animation",
"resize",
""
] |
> **Possible Duplicate:**
> [Why should I use templating system in PHP?](https://stackoverflow.com/questions/436014/why-should-i-use-templating-system-in-php)
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine? | Not only does this practice make the code **look** cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller), this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like [Zend](http://www.zend.com), the learning curve is much greater than some other ones.
I have found that [Code Igniter](http://codeigniter.com/) is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!! | Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
*Edit*
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
* isolate the code that is the *brain* of your application from the code that is the *face*, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
* isolate 80% of bugs in 20% of your code
* create reusable components: you could assign different presentation code to the same business code, and vice versa;
* separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
* use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
* use a single controller php file, which receives all requests via a .httpdaccess file;
* the controller decides what business and presentation code to use, depending on the request
* the controller then uses an include statement to include the business php file
* the business code does it's magic, and then includes the presentation php file | PHP: Separating Business logic and Presentational logic, is it worth it? | [
"",
"php",
"html",
"templates",
""
] |
Which distributed lock service would you use?
Requirements are:
1. A mutual exclusion (lock) that can be seen from different processes/machines
2. lock...release semantics
3. Automatic lock release after a certain timeout - if lock holder dies, it will automatically be freed after X seconds
4. Java implementation
5. Nice to have: .Net implementation
6. If it's free: Deadlock detection / mitigation
7. Easy deployment, see note below.
I'm not interested in answers like "it can be done over a database", or "it can be done over JavaSpaces" - I know. I'm interested in a ready, out-of-the-box, proven implementation. | [Teracotta](http://www.terracotta.org/web/display/enterprise/Products), including the Open Source edition, has distributed locking semantics by using either `synchronized` or the `java.util.concurrent.ReentrantReadWriteLock` - the latter apparently fitting your requirements.
---
**Update**
Since the question now added the requirement of 'mixing' with GigaSpaces, I'm going to say *don't* mix them. It's just going to add more complexity to your technological stack, and the effort of:
* integrating, in terms of both code and infrastructure;
* managing synchronisation between them;
* learning/tuning/debugging Teracotta.
will be better spent creating or implementing a locking solution based on GigaSpaces. | A newer kid on the block is [hazelcast](http://www.hazelcast.com/). I've been playing with it and it is amazingly simple to use and configure.
As far as I can see there shouldn't be any conflict between Gigaspaces and hazelcast as hazelcast doesn't have any dependencies i.e. no jgroups.jar etc
**Hazelcast**:
1. A mutual exclusion (lock), yep implementation of `java.util.concurrency.locks.Lock`
2. Automatic lock release after a certain timeout, yep all locks are released if a member leaves the cluster
3. Java implementation, yep
4. Nice to have: .Net implementation, nope is a pure java solution, might be possible to port to j#
5. If it's free: Deadlock detection / mitigation, nope no effort is made my Hazelcast to handle this
6. Easy deployment, it's a single jar with a single config file, deployed as part of your application, no additional processes are required | Distributed Lock Service | [
"",
"java",
"timeout",
"locking",
"distributed-lock",
""
] |
With PHP, I'd like to use a preg\_replace() filter for passwords such that the only characters available for passwords are US ASCII typable, minus control codes and NULL.
What's the RegEx to achieve that which I can plugin to preg\_replace()?
**EDIT:**
I've been advised to edit this question since I "get it" now and won't be doing this terribly unpopular technique and will permit any typable character even ones I might not have on my keyboard, just as long as they aren't control codes. | As others have said, don't restrict the set of characters that are allowed in passwords. Just because *your* keyboard doesn't have ä, å, or ö on it is no reason to stop those of us who do have them (or know how to type them anyhow) from using those letters. You're going to be storing the password as a cryptographic hash anyhow (or at least as an encrypted string), aren't you? If so, then it doesn't matter whether your database can successfully/safely store the actual characters in the password anyhow, only the characters output by your crypto algorithm. (And if not, then storing passwords in plaintext is a *far* bigger problem than what characters the passwords may or may not contain - don't do that!)
Your apparent intent to enforce your character set restrictions by silently stripping the characters you dislike rather than by telling the user "Try again and, this time, only use these characters: a, e, i, o, u." makes your proposed method truly atrocious, as it means that if I attempt to use, say, the password `fäîry` (not incredibly secure, but should hold up against lightweight dictionary attacks), my actual password, unknown to me, will be `fry` (if your password is a three-letter word, straight out of the dictionary and in common use, you may as well not even bother). Ouch! | Personally, I've always found it highly disturbing when a web site or service tried to force me to use passwords that follow a certain (usually downright stupid) limitation.
Isn't it the whole point of passwords that they are not too easily guessable? Why would you want them to be less complex than your users want them to be? I can't imagine a technical limitation that would require the use of "ASCII only" for passwords.
Let your users use any password they like, hash them and store them as Base64 strings. These are ASCII only. | preg_replace Filter for Passwords | [
"",
"php",
"regex",
"filter",
"passwords",
"preg-replace",
""
] |
I'm a little confused as to what's going on, i'm playing with some programs from "Accelerated C++", and have hit a problem with one of the early programs (page 35, if you happen to have a copy nearby).
It uses this snippet:
```
while (cin >> x) {
++count;
sum += x;
}
```
("count" is an integer, "x" is a double)
It works as intended, allowing me to enter several values and add them together, but i can't work out what's going wrong with "End-of-file" signalling. The book says the loop will keep running until the program encounters an end of file signal, which is ctrl+z in windows.
This is all fine, and works, but then my program won't let me use cin again. I usually just set up a program to wait for some random variable in order to stop the console closing immediately after executing (is there a better way to do that, by the way?) which is how i noticed this, and i'm wondering if there's a solution. I've done a bunch of searching, but found little that doesn't say what's already said in the book (press ctrl+z, or enter a non-compatible type of input etc.)
I'm using Visual studio 2008 express to compile. | From one point of view, once you've hit the end of an input stream then by definition there's nothing left in the stream so trying to read again from it doesn't make sense.
However, in the case of 'end-of-stream' actually being caused be a special character like Ctrl-Z on windows, we know that there is the possibility that we could read again from `cin`. However, the failed read will have caused the `eof` flag on the stream to be set.
To clear this flag (and all the other failure flags) you can use the `clear` method.
```
std::cin.clear();
```
After calling this, you can attempt another read. | EOF means that `STDIN` (otherwise known as `cin`) has been closed. Closed means it can't be used again.
That said, I think it's possible to open another stream to the input, but the better, and more normal solution is to do better input/output processing, and allow your user to input some token that says 'stop accepting input'. | while (cin >> x) and end-of-file issues | [
"",
"c++",
"loops",
""
] |
**Edit**
Since there were many downvotes and people who didn't understand what I'm asking for, I'll rephrase:
How do I find out at runtime what is the class that foo was generified from?
```
public boolean doesClassImplementList(Class<?> genericClass)
{
// help me fill this in
// this method should return true if genericClass implements List
// I can't do this because it doesn't compile:
return genericClass instanceof List;
}
``` | `Class.isAssignableFrom` | you cannot in Java ([type erasure](http://java.sun.com/docs/books/tutorial/java/generics/erasure.html)) | Is the T class in generic Class<T> assignable from another class? | [
"",
"java",
"generics",
"class",
""
] |
I'm reading my Deitel, Java How to Program book and came across the term *shadowing*. If shadowing is allowed, what situation or what purpose is there for it in a Java class?
Example:
```
public class Foo {
int x = 5;
public void useField() {
System.out.println(this.x);
}
public void useLocal() {
int x = 10;
System.out.println(x);
}
}
``` | The basic purpose of shadowing is to decouple the local code from the surrounding class. If it wasn't available, then consider the following case.
A Class Foo in an API is released. In your code you subclass it, and in your subclass use a variable called bar. Then Foo releases an update and adds a protected variable called Bar to its class.
Now your class won't run because of a conflict you could not anticipate.
However, don't do this on purpose. Only let this happen when you really don't care about what is happening outside the scope. | It can be useful for setters where you don't want to have to create a separate variable name just for the method parameter eg:
```
public void setX(int x) {
this.x = x;
}
```
Apart from that I'd avoid them. | What is variable shadowing used for in a Java class? | [
"",
"java",
"shadowing",
""
] |
Constants are beautiful people - they can hold in a unique place a value that is used everywhere in your code. Changing that value requires only one simple modification.
Life is cool.
Well, this is the promise. Reality is sometime different :
* You change the `LogCompleteFileName` constant value from `L:\LOGS\MyApp.log` to `\\Traces\App208.txt` and you get two files : `\\traces\App208.txt` for the traces and `\\traces\App208.txt.log` for the logs...
* You change `TransactionTimeout` from 2 to 4 minutes and you still get a timeout after 2 minutes (after spending the day, you find out that you also have to change the timeout of the DBMS and the timeout of the transaction manager...).
* You replace `SleepTimeInMinutes` from `1` to `10` and you see no change (after an hour or so, you find out that the constant's name was misleading : the granularity is not the minute but the millisecond...).
* Even more subtle: you change `CompanyName` from, say `Yahoo` to `Microsoft` but automated mail alerts are still sent to `alert@yahoo.com`...
Creating a constant is a contract. You are telling your readers that whenever they change the value, it will still works the way they think it should be.
Nothing less.
Of course, you need to test that you are not misleading your readers. You have to make sure that the implied contract is right.
How do you achieve that with TDD? I'm just stuck with that. The only way I can test a change for a constant (!) value is to make that constant an application setting... Should I have to conclude that the `const` keyword should be avoided when I think that the value can and will change?
How are you testing your (so called) constants using TDD?
Many thanks in advance :) | > The only way I can test a change for a constant (!) value is to make that constant an application setting
All of the uses you listed in the question sound like application settings, not constants, to me. A constant is a value that is, well, constant, such as:
```
const decimal LITERS_PER_HOGSHEAD = 238.480942392;
```
Edited to add: Hopefully this is more helpful than my flippant answer. I usually create an AppSettings class. Some of the properties in this class are pulled from the config file, some are settings that I don't expect to change, and some could be constants.
```
public class AppSettings
{
public const decimal GILLS_PER_HOMER = 1859.771248601;
public string HelpdeskPhone
{
get { // pulled from config and cached at startup }
}
public int MaxNumberOfItemsInAComboBox
{
get { return 3; }
}
}
``` | There are two kinds of constants:
## 1) Constants for Convenience/Readability
When writing code using TDD, each line of production code should exists because first there was a failing test that required that code to be written. And as you refactor the code, some magic values will get promoted into constants. Some of these might also be good as application settings, but for convenience (less code) they have been configured in code instead of an external configuration file.
In that case, the way that I write tests, both production and test code will use the same constants. The tests will specify that the constants are used as expected. But the tests won't repeat the value of a constant, such as in "`assert MAX_ITEMS == 4`", because that would be duplicated code. Instead, the tests will check that some behaviour uses the constants correctly.
For example, [here](http://github.com/orfjackal/longcat/) is an example application (written by me) which will print a [Longcat](http://encyclopediadramatica.com/Longcat) of specified length. As you can see, the Longcat is defined as a series of constants:
```
public class Longcat {
// Source: http://encyclopediadramatica.com/Longcat
public static final String HEAD_LINES = "" +
" /\\___/\\ \n" +
" / \\ \n" +
" | # # | \n" +
" \\ @ | \n" +
" \\ _|_ / \n" +
" / \\______ \n" +
" / _______ ___ \\ \n" +
" |_____ \\ \\__/ \n" +
" | \\__/ \n";
public static final String BODY_LINE = "" +
" | | \n";
public static final String FEET_LINES = "" +
" / \\ \n" +
" / ____ \\ \n" +
" | / \\ | \n" +
" | | | | \n" +
" / | | \\ \n" +
" \\__/ \\__/ \n";
...
```
The tests verify that the constants are used correctly, but they do not duplicate the value of the constant. If I change the value of a constant, all the tests will automatically use the new value. (And whether the Longcat ASCII art looks right, it needs to be verified manually. Although you could even automate that with an acceptance test, which would be recommendable for a larger project.)
```
public void test__Longcat_with_body_size_2() {
Longcat longcat = factory.createLongcat(2);
assertEquals(Longcat.BODY_LINE + Longcat.BODY_LINE, longcat.getBody());
}
public void test__Fully_assembled_longcat() {
Longcat longcat = factory.createLongcat(2);
assertEquals(Longcat.HEAD_LINES + longcat.getBody() + Longcat.FEET_LINES, longcat.toString());
}
```
## 2) Universal Constants
The same application has also some constants which are never expected to be changed, such as the ratio between meters and feet. Those values can/should be hard coded into the test:
```
public void test__Identity_conversion() {
int feet1 = 10000;
int feet2 = FEET.from(feet1, FEET);
assertEquals(feet1, feet2);
}
public void test__Convert_feet_to_meters() {
int feet = 10000;
int meters = METERS.from(feet, FEET);
assertEquals(3048, meters);
}
public void test__Convert_meters_to_feet() {
int meters = 3048;
int feet = FEET.from(meters, METERS);
assertEquals(10000, feet);
}
```
And the production code looks like:
```
public enum LengthUnit {
METERS("m", 1.0), FEET("ft", 0.3048), PETRONAS("petronas", 451.9), LINES("lines", 0.009);
private final String name;
private final double lengthInMeters;
...
public int from(int length, LengthUnit unit) {
return (int) (length * unit.lengthInMeters / this.lengthInMeters);
}
}
```
Notice that I did not write any tests for the height of the [Petronas Twin Towers](http://en.wikipedia.org/wiki/Petronas_Twin_Towers), because that information is declarative (and declarative data rarely gets broken) and I had already written tests for the conversion logic (see above). If more similar constants are added (Eiffel Tower, Empire State Building etc.), they will be automatically located by the application and will work as expected. | TDD : Any pattern for constant testing? | [
"",
"c#",
"testing",
"tdd",
"constants",
""
] |
The JavaScript code window.print() can print the current HTML page.
If I have a div in an HTML page (for example, a page rendered from an [ASP.NET MVC](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework) view), then I want to print the div only.
Is there any jQuery [unobtrusive JavaScript](https://en.wikipedia.org/wiki/Unobtrusive_JavaScript) or normal JavaScript code to implement this request?
Making it more clear, suppose the rendered HTML page is like:
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head" runat="server">
<title>
<asp:ContentPlaceHolder runat="server" ID="TitleContent" />
</title>
</head>
<body>
<div id="div1" class="div1">....</div>
<div id="div2" class="div2">....</div>
<div id="div3" class="div3">....</div>
<div id="div4" class="div4">....</div>
<div id="div4" class="div4">....</div>
<p>
<input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
</p>
</body>
</html>
```
Then I want to click on the Print button, only printing div3. | I would go about it somewhat like this:
```
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
``` | Along the same lines as some of the suggestions you would need to do at least the following:
* Load some CSS dynamically through JavaScript
* Craft some print-specific CSS rules
* Apply your fancy CSS rules through JavaScript
An example CSS could be as simple as this:
```
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
```
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
```
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
```
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to [load the CSS dynamically like in this answer](https://stackoverflow.com/questions/1071962/how-to-print-part-of-rendered-html-page-in-javascript/1072151#1072151).
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Print Portion Example</title>
<style type="text/css">
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
``` | How do I print part of a rendered HTML page in JavaScript? | [
"",
"javascript",
"jquery",
""
] |
What is the meaning of the OVER clause in Oracle? | The `OVER` clause specifies the partitioning, ordering and window "over which" the analytic function operates.
**Example #1: calculate a moving average**
```
AVG(amt) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
date amt avg_amt
===== ==== =======
1-Jan 10.0 10.5
2-Jan 11.0 17.0
3-Jan 30.0 17.0
4-Jan 10.0 18.0
5-Jan 14.0 12.0
```
It operates over a moving window (3 rows wide) over the rows, ordered by date.
**Example #2: calculate a running balance**
```
SUM(amt) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
date amt sum_amt
===== ==== =======
1-Jan 10.0 10.0
2-Jan 11.0 21.0
3-Jan 30.0 51.0
4-Jan 10.0 61.0
5-Jan 14.0 75.0
```
It operates over a window that includes the current row and all prior rows.
Note: for an aggregate with an `OVER` clause specifying a sort `ORDER`, the default window is `UNBOUNDED PRECEDING` to `CURRENT ROW`, so the above expression may be simplified to, with the same result:
```
SUM(amt) OVER (ORDER BY date)
```
**Example #3: calculate the maximum within each group**
```
MAX(amt) OVER (PARTITION BY dept)
dept amt max_amt
==== ==== =======
ACCT 5.0 7.0
ACCT 7.0 7.0
ACCT 6.0 7.0
MRKT 10.0 11.0
MRKT 11.0 11.0
SLES 2.0 2.0
```
It operates over a window that includes all rows for a particular dept.
SQL Fiddle: <http://sqlfiddle.com/#!4/9eecb7d/122> | You can use it to transform some aggregate functions into analytic:
```
SELECT MAX(date)
FROM mytable
```
will return `1` row with a single maximum,
```
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
```
will return all rows with a running maximum. | OVER clause in Oracle | [
"",
"sql",
"oracle",
"window-functions",
""
] |
I have a JavaScript function code where I want to alert.
```
function msg(x,y)
{
tempstr = x.value
if(tempstr.length>y)
{
alert(c_AcknowledgementText);
x.value = tempstr.substring(0,y);
}
}
```
Now I have an xml with below format:
```
<?xml version="1.0" encoding="utf-8" ?>
<root>
<key name="c_ContactUsHeading">Contact Us</key>
<key name="c_AcknowledgementText">Comments can not be more than 250 characters.</key>
</root>
```
I want the JavaScript code so that the message shown in above alert can be read from above xml key name "c\_AcknowledgementText".
I hope it is clear about my problem. | Basically, you want to use XMLHttpRequest. Not sure what you're trying to do with tempstr, etc., though.
```
function msg(x,y)
{
tempstr = x.value;
if(tempstr.length>y)
{
var req = new XMLHttpRequest();
req.open('GET', '/file.xml', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
{
var keys = req.responseXML.getElementsByTagName("key");
for(var i = 0; i < keys.length; i++)
{
var key = keys[i];
if(key.getAttribute("name") == "c_AcknowledgementText")
{
alert(key.textContent);
break;
}
}
}
else
alert("Error loading page\n");
}
};
req.send(null);
x.value = tempstr.substring(0,y);
}
}
``` | First step is to get a DOM reference to the XML document. One way to do that is with Ajax. In this case, the server needs to respond with the Content-Type: text/xml header.
```
$.ajax({
type: "GET",
url: "/path/to/my.xml",
dataType: "xml",
success: function(doc){
var keys = doc.getElementsByTagName('key');
if (keys.length > 0) {
for (var i=0; i<keys.length; i++) {
if (keys[i].getAttribute('name') == 'c_AcknowledgementText') {
alert(keys[i].innerHTML);
}
}
}
}
});
```
You may need some additional error-handling, etc. | reading javascript alert value from xml | [
"",
"javascript",
"xml",
""
] |
I am developing a library that uses one or more helper executable in the course of doing business. My current implementation requires that the user have the helper executable installed on the system in a known location. For the library to function properly the helper app must be in the correct location and be the correct version.
I would like to removed the requirement that the system be configured in the above manner.
Is there a way to bundle the helper executable in the library such that it could be unpacked at runtime, installed in a temporary directory, and used for the duration of one run? At the end of the run the temporary executable could be removed.
I have considered automatically generating an file containing an unsigned char array that contains the text of the executable. This would be done at compile time as part of the build process. At runtime this string would be written to a file thus creating the executable.
Would it be possible to do such a task without writing the executable to a disk (perhaps some sort of RAM disk)? I could envision certain virus scanners and other security software objecting to such an operation. Are there other concerns I should be worried about?
The library is being developed in C/C++ for cross platform use on Windows and Linux. | You can use [`xxd`](http://linuxcommand.org/man_pages/xxd1.html) to convert a binary file to a C header file.
```
$ echo -en "\001\002\005" > x.binary
$ xxd -i x.binary
unsigned char x_binary[] = {
0x01, 0x02, 0x05
};
unsigned int x_binary_len = 3;
```
`xxd` is pretty standard on \*nix systems, and it's available on Windows with Cygwin or MinGW, or Vim includes it in the standard installer as well. This is an extremely cross-platform way to include binary data into compiled code.
Another approach is to use [`objcopy`](http://www.linuxjournal.com/content/embedding-file-executable-aka-hello-world-version-5967) to append data on to the end of an executable -- IIRC you *can* obtain `objcopy` and use it for PEs on Windows.
One approach I like a little better than that is to just append raw data straight onto the end of your executable file. In the executable, you seek to the end of the file, and read in a number, indicating the size of the attached binary data. Then you seek backwards that many bytes, and `fread` that data and copy it out to the filesystem, where you could treat it as an executable file. This is incidentally [the way that many, if not all, self-extracting executables are created](http://benjisimon.blogspot.com/2009/08/hack-of-day-creating-windows-self.html).
If you append the binary data, it works with both Windows PE files and \*nix ELF files -- neither of them read past the "limit" of the executable.
Of course, if you need to append multiple files, you can either append a tar/zip file to your exe, or you'll need a slightly more advance data structure to read what's been appended.
You'll also probably want to [UPX](http://upx.sourceforge.net/) your executables before you append them.
You might also be interested in the [LZO library](http://www.oberhumer.com/opensource/lzo/#minilzo), which is reportedly one of the fastest-decompressing compression libraries. They have a MiniLZO library that you can use for a very lightweight decompressor. However, the LZO libraries are GPL licensed, so that *might* mean you can't include it in your source code unless your code is GPLed as well. On the other hand, there are commercial licenses available. | > "A clever person solves a problem. A
> wise person avoids it." — Albert Einstein
In the spirit of this quote I recommend that you simply bundle this executable along with the end-application.
Just my 2 cents. | Unpacking an executable from within a library in C/C++ | [
"",
"c++",
"c",
"cross-platform",
"filesystems",
"iterable-unpacking",
""
] |
Our application has a service layer and a DAO layer, written as Spring beans.
While testing the Service Layer- I do not want to depend upon a real database so I am mocking that by creating a 'Mock' Impl for the DAO layer
So when I am testing the Service layer- I chain the Service layer beans to the Mock DAO beans
And in Production- will chain the Service layer to the 'real' DAO beans
Is that a good idea ?
Any alternate suggestion on how to mock the database layer ?
Clarification:This question is about testing the Service Layer and not the DAO layer.
While testing the service layer- I assume that either the DAO layer has already been tested or doesn't need testing.
The main thing is- how do we test service layer- without being dependent upon the DAO implementation- hence I am mocking the DAO layer | This is a technique we've been using for many years now. Note that when it comes to mocking the DAO interfaces you have some choices:
* Create mock instances as real Java classes
* Use a dynamic mocking framework such as [jMock](http://www.jmock.org/) (my preference) or EasyMock
Dynamic mocking frameworks allow you to stub out a variety of circumstances (no data, 1 row, many rows, exception throwing) without having to create complex classes to stub out the behavior you wish to test | That's a great way to use mocking to test the database. I don't think any alternative suggestion is necessary; I think you've got the right technique already! | Test Cases: Mocking Database using Spring beans | [
"",
"java",
"unit-testing",
"spring",
"junit",
"mocking",
""
] |
After checking out code for the first time from a repository into Eclipse using the Subclipse plugin, I've found that I am not able to run Java applications anymore. Usually when I right click in the text editor window and select "Run As", I see the option to "Run as Java Application". Now, however, all I see is "Run on server." Is there another way to run it as a Java application or is there some option that I need to re-configure? | I actually figured it out - I checked out the wrong directory. Because the src directory was a sub-directory, it wasn't being recognized as a package and thus wasn't allowing the .java files to be run as Java apps. Once I checked out the right directory, it worked. | Does the class you're trying to run have a `public static void main(String[] args)` method signature? | Subclipse problem: running .java file as Java application | [
"",
"java",
"eclipse",
"subclipse",
""
] |
Assuming that I have a `CronTriggerBean` similar to
```
<bean id="midMonthCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="reminderJobDetail" />
<property name="cronExpression" value="0 0 6 15W * ?" />
</bean>
```
What is the best way to test that this bean will actually trigger at its specified date, *i.e.* on the weekday closest to the 15th of each month at 6 AM?
---
**Update**: This is supposed to be an unit test, so I'm not going to fire up a VM or change the system time. | Well firstly, there's no point in testing `CronTriggerBean` itself. It's part of the spring framework, and has already been tested.
A better test might be to test that your cron expression is what you expect. One option here is to use Quartz's `CronExpression` class. Given a `CronExpression` object, you can call `getNextValidTimeAfter(Date)`, which returns the next time after the given Date when the expression will fire. | I used CronMaker only to be sure if my cron expression is well formed, check it out:
<http://www.cronmaker.com/> | Testing Quartz CronTrigger trigger | [
"",
"java",
"unit-testing",
"spring",
"quartz-scheduler",
""
] |
While searching for a proper way to trim non-breaking space from parsed HTML, I've first stumbled on Java's spartan definition of `String.trim()` which is at least properly documented. I wanted to avoid explicitly listing characters eligible for trimming, so I assumed that using Unicode backed methods on the *Character* class would do the job for me.
That's when I discovered that [Character.isWhitespace(char)](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isWhitespace%28char%29) explicitly excludes non-breaking spaces:
> It is a Unicode space character (`SPACE_SEPARATOR`, `LINE_SEPARATOR`, or `PARAGRAPH_SEPARATOR`) **but is not also a non-breaking space** (`'\u00A0'`, `'\u2007'`, `'\u202F'`).
Why is that?
The implementation of [corresponding .NET equivalent](http://msdn.microsoft.com/en-us/library/t809ektx.aspx) is less discriminating. | `Character.isWhitespace(char)` is old. Really old. Many things done in the early days of Java followed conventions and implementations from C.
Now, more than a decade later, these things seem erroneous. Consider it evidence how far things have come, even between the first days of Java and the first days of .NET.
Java strives to be 100% backward compatible. So even if the Java team thought it would be good to fix their initial mistake and add non-breaking spaces to the set of characters that returns true from Character.isWhitespace(char), they can't, because there almost certainly exists software that relies on the current implementation working exactly the way it does. | Since Java 5 there is also an [`isSpaceChar(int)`](http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isSpaceChar(int)) method. Does that not do what you want?
> Determines if the specified character (Unicode code point) is a Unicode space character. A character is considered to be a space character if and only if it is specified to be a space character by the Unicode standard. This method returns true if the character's general category type is any of the following: ... | Why is non-breaking space not a whitespace character in Java? | [
"",
"java",
"unicode",
""
] |
I need a way for a single variable to represent two kinds of objects derived from the same base class.
It's kinda hard to describe but I'll try the best:
Say the base class:
```
class Rectangle
{
float w;
float h;
const float area() {return w*h;}
};
```
And the two derived classes:
```
class Poker : Rectangle
{
int style; // Diamond, Club, ....
int point; // A~10, J, Q, K
};
class BusinessCard : Rectangle
{
string name;
string address;
string phone;
};
```
Now is it possible to declare an object, which could be either a poker or a business-card?
'cuz the usage below is illegal:
```
Rectangle* rec;
rec = new Poker();
delete rec;
rec = new BusinessCard();
```
Polymorphism might be a way but since it's only good for changing base-class' member attributes, I need this object to be able to represent exactly either of the derived objects.
EDIT:
Thanks for the all the answers. The public inheritance , the virtual destructor and even the boost::variant typedef are all fantastic hints. | You can do that. The problem is the inheritance modifier for classes is `private`. [Most of the time, `private` inheritance is not what you want to use](https://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance). Instead, declare it explicitly as `public`:
```
class Rectangle
{
float w;
float h;
const float area() {return w*h; }; // you missed a semicolon here, btw
virtual ~Rectangle() { } // to make `delete` work correctly
};
class Poker : public Rectangle // note the public keyword
{
int style; // Diamond, Club, ....
int point; // A~10, J, Q, K
};
class BusinessCard : public Rectangle
{
string name;
string address;
string phone;
};
```
Then your code snippet should work. | You need to change the qualifier for the inheritence to public.
```
class Poker : public Rectangle
{
int style; // Diamond, Club, ....
int point; // A~10, J, Q, K
};
class BusinessCard : public Rectangle
{
string name;
string address;
string phone;
};
```
is what you want. Now both classes, BusinessCard and Poker are of type Rectangle. | Using a base-class object to represent its derived-class objects | [
"",
"c++",
""
] |
I am trying to get text input from the keyboard in Java 6. I am new to the language and whenever i run the following code, I get this error:
```
package test1;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
boolean quit = false;
while (!quit){
Scanner keyIn;
String c = "x";
while (c != "y" && c != "n") {
keyIn = new Scanner(System.in);
c = keyIn.next();
keyIn.close();
}
if (c == "n")
quit = true;
}
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at test1.Test.main(Test.java:11)
```
Am I mis-using the next() method? I thought it would wait for user input but it looks like it isn't and throwing the exception saying that there is nothing left in the scanner. | The reason for the exception is that you are calling `keyIn.close()` after you use the scanner once, which not only closes the `Scanner` but also `System.in`. The very next iteration you create a new `Scanner` which promptly blows up because `System.in` is now closed. To fix that, what you should do is only create a scanner once before you enter the `while` loop, and skip the `close()` call entirely since you don't want to close `System.in`.
After fixing that the program still won't work because of the `==` and `!=` string comparisons you do. When comparing strings in Java you must use `equals()` to compare the string contents. When you use `==` and `!=` you are comparing the object references, so these comparisons will always return false in your code. [Always use `equals()` to compare strings.](http://weblogs.macromedia.com/cantrell/archives/2003/04/how_equals_work.html)
```
while (!quit){
Scanner keyIn = new Scanner(System.in);
String c = "x";
while (!c.equals("y") && !c.equals("n")) {
c = keyIn.next();
}
if (c.equals("n"))
quit = true;
}
``` | To evaluate strings you have to use .equals
while(!c.equals("y")) { do stuff... | Using Scanner.next() to get text input | [
"",
"java",
"java.util.scanner",
""
] |
I'm running a cronjob that calls a php script. I get "failed to open stream" when the file is invoked by cron. When I cd to the directory and run the file from that location, all is well. Basically, the include\_once() file that I want to include is two directories up from where the php script resides.
Can someone please tell me how I can get this to work from a cronjob? | There are multiple ways to do this: You could `cd` into the directory in your cron script:
```
cd /path/to/your/dir && php file.php
```
Or point to the correct include file relative to the [current script](http://php.net/manual/en/language.constants.php) in PHP:
```
include dirname(__FILE__) . '/../../' . 'includedfile.php';
``` | `cron` is notorious for starting with a minimal environment. Either:
* have your script set up it's own environment;
* have a special cron script which sets up the environment then calls your script; or
* set up the environment within crontab itself.
An example of the last (which is what I tend to use if there's not too many things that need setting up) is:
```
0 5 * * * (export PATH = /mydir:$PATH ; myexecutable )
``` | include path and cron | [
"",
"php",
""
] |
Does a application in .NET need to be built in 64 bit to take full advantage of a machine with a 64 bit OS on it, or will it take advantage of it just as a 32 bit build. Basically, we have an issue with an out of memory exception and it was suggested to run the console app on a 64 bit box which "may" solve the issue. The question is can we just spin up a 64 box and throw the current app on it or do I need to rebuild the app in a 64 bit way. | If your app is configured to build for the "Any CPU" platform, then it'll run appropriately on either.
Just make sure it doesn't use any 32/64 bit specific stuff, or you'll run into problems.
MSDN docs [here](http://msdn.microsoft.com/en-us/library/5b4eyb0k.aspx).
For some discussion on drawbacks, see [here](http://blogs.msdn.com/rmbyers/archive/2009/06/08/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx) | If it's built for any platform (the default), it will run in 64 bit on 64bit operating systems.
That being said, there are still potential issues to watch for. If you interface with native code (via p/invoke, C++/CLI, or COM), then you will need to port that code to 64 bit. If the application is 100% managed, it just works. | .net console app 32 vs 64 bit | [
"",
"c#",
".net",
"build",
"64-bit",
"32-bit",
""
] |
I have an entity which looks something like this: (I'm coding to the web page so I apologize for any mistakes)
```
@Entity
public class Entity {
@Id
private Long id;
private String field;
// Insert getters and setters here...
}
```
I try to manipulate it using reflection:
```
Long id = 1;
Entity entity = myDao.getEntity(id);
entity.setField("set directly");
Field[] fields = entity.getClass().getDeclaredFields();
for (Field f : fields) {
if (f.getName().equals("field")) {
f.setAccessible(true);
f.set(entity, "set using reflection");
f.setAccessible(false);
}
}
System.out.println(entity.getField());
```
This program prints "set using reflection". However, in the database the value set using reflection does not get updated:
```
SELECT * FROM ENTITY WHERE ID = 1
ID FIELD
1 set directly
```
This is strange. I could swear that this used to work - but now it isn't. Is it really so that you cannot manipulate entities using reflection?
I'm using EclipseLink 1.1.1 if that matters. | Changing values of an entity class by reflection is going to fraught with issues. This is because you're dealing with a class which is persistent and thus the persistence API needs to know about changes to the fields.
If you make changes via reflection, chances are the persistence API will not know about those changes.
A better solution would be to call the setters via reflection. | I'm pretty sure the Entity you are given by your persistence framework is actually wrapped in another class (possibly the same with stuff tacked on through reflection). Changing the field directly through reflection seems unlikely to work. You might want to check if there's a (generated) setter that you can use. Although if you're going that route one might ask why you don't allow callers to call the setter directly? | Updating JPA entity with reflection does not work? | [
"",
"java",
"reflection",
"jpa",
""
] |
Iam working on a website and I dont have any clue why the tabs doesnt work when I upload the website. Because when I view the website normal it does work perfectly.
By the way: The tabs are working with a jquery script.
This is the website URL: <http://bmvisuals.poshh.nl/>
Greetings.
Edit: I mean some of the tabs doesnt appear. | Your About me tab does not show up because your server is case sensitive.
Aboutme.jpg != Aboutme.JPG
You should check out [CSS Sprites](http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/). There is a flicker when you hover over a tab (the first time) because the browser has to load the hover image. With CSS Sprites an image map is used and all the images are loaded at once so the hover is seamless.
As an aside, your site does not scroll vertically. When my window is smaller than your site, the bottom gets cut off and there is no way for me to see it. | Firstly, nice site. Secondly your tabs are totally borked for me. I am using Linux Ubuntu and Firefox 3. Not sure about the fix though. Just thought I would mention it. | Everything showed good, except the tabs. (HTML,CSS,JS) | [
"",
"javascript",
"jquery",
"html",
"css",
"xhtml",
""
] |
Ninject looks great, so I'd like to use it in my project. Unfortunately I am still struggling to do the most trivial binding. The [Inject] attribute compiles just fine, but the compiler cannot find the "Bind" command:
```
using System;
using Ninject.Core;
using Ninject.Core.Binding;
namespace NinjectTest
{
public interface IFoo
{
void DoSomething();
}
public class Foo : IFoo
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
public class Bar
{
[Inject] private IFoo theFoo;
public Bar()
{
Bind<IFoo>().To<Foo>(); //Compiler Error: "The name 'Bind' does not exist in the current context"
}
}
}
```
What could be going wrong here? | The *Bind* method is a method in the Ninject StandardModule class. You need to inherit that class to be able to bind.
Here is a simple example:
```
using System;
using System.Collections.Generic;
using System.Text;
using Ninject.Core;
namespace Forecast.Domain.Implementation
{
public class NinjectBaseModule : StandardModule
{
public override void Load()
{
Bind<ICountStocks>().To<Holding>();
Bind<IOwn>().To<Portfolio>();
Bind<ICountMoney>().To<Wallet>();
}
}
}
``` | The Bind method is defined in ModuleBase - you should inherit your class from this or, even better, from StandardModule. | Compilation Error with Ninject | [
"",
"c#",
"ninject",
""
] |
Using ExtJS 2.2.1, I've got a container element which is supposed to load a piece of HTML from the server using:
```
autoLoad: { url: 'someurl' }
```
This works fine in Firefox, but for IE7 this results in a syntax error in ext-all-debug.js at line 7170:
```
this.decode = function(json){
return eval("(" + json + ')');
};
```
I fixed this by turning that function into this:
```
this.decode = function(json){
return eval('(function(){ return json; })()');
};
```
Then the autoLoad works well in both browsers, but then there's some odd bugs and besides, you really don't want to fix this in the ExtJS library as it will be unmaintainable (especially in the minified ext-all.js which is like half a megabye of Javascript on a single line).
I haven't been able to find a lot about this bug.
Variations that I've tried:
```
// With <script> tags around all the HTML
autoLoad: { url: 'someurl', scripts: true }
// With <script> tags around all the HTML
autoLoad: { url: 'someurl', scripts: false }
```
And visa versa without the `<script>` tags. There isn't any Javascript in the HTML either, but it should be possible, because eventually we will use Javascript inside the returned HTML.
The problem isn't in the HTML because even with the simplest possible HTML, the error is the same.
UPDATE - Response to donovan:
The simplest case where this is used is this one:
```
changeRolesForm = new Ext.Panel({
height: 600,
items: [{ autoScroll: true, autoLoad: WMS.Routing.Route("GetRolesList", "User") + '?userID=' + id}]
});
```
There is no datastore involved here. The response-type is also `text\html`, not json, so that can't be confusing it either. And as said, it's working just fine in Firefox, and in Firefox, it also executes the same `eval` function, but without the error. So it's not like Firefox follows a different path of execution, it's the same, but without the error on `eval`. | I located the source of the problem and it was indeed not with ExtJS. There was a section in the application that listened to the `Ext.Ajax` 'requestcomplete' event and tried decoding the response.responseText to json, even if the response was HTML (which it only is in one or two cases). IE was not amused by this. | Check your JSON. FF allow trailing commas in JSON objects while IE does not. e.g.
```
{foo:'bar',baz:'boz',}
```
would work in FF but in IE it would throw a syntax error. In order for there to not be a syntax error the JSON would need to be:
```
{foo:'bar',baz:'boz'}
``` | ExtJS: autoLoad does not work in IE | [
"",
"javascript",
"internet-explorer",
"extjs",
"autoload",
""
] |
I created a report in VS using a shared data source which is connected to a sharepoint list. In the report I created a dataset with a SOAP call to the data source so I get the result from the sharepoint list in a table.
this is the soap call
```
<Query>
<SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction>
<Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems">
<Parameters>
<Parameter Name="listName">
<DefaultValue>{BD8D39B7-FA0B-491D-AC6F-EC9B0978E0CE}</DefaultValue>
</Parameter>
<Parameter Name="viewName">
<DefaultValue>{E2168426-804F-4836-9BE4-DC5F8D08A54F}</DefaultValue>
</Parameter>
<Parameter Name="rowLimit">
<DefaultValue>9999</DefaultValue>
</Parameter>
</Parameters>
</Method>
<ElementPath IgnoreNamespaces="True">*</ElementPath>
</Query>
```
THis works fine, I have a result which I can show in a report, but I want to have the ability to select a parameter to filter the result on. I have created a parameter and when I preview the Report I see the dropdownbox which I can use to make a selection from the Title field, when I do this it still shows the first record, obviously it doens't work yet (DUH!) because I need to create a query *somewhere*, But! I have no idea where, I tried to include
```
<Where>
<Eq>
<FieldRef Name="ows_Title" />
<Value Type="Text">testValue</Value>
</Eq>
</Where>
```
in the the soap request but it didn't worked... I've searched teh intarwebz but couldn't find any simliar problems... kinda stuck now...any thoughts on this?
*EDIT*
Here's the query I used according to the blogpost Alex Angas linked.
```
<Query>
<SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction>
<Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems">
<queryOptions></queryOptions>
<query><Query>
<Where>
<Eq>
<FieldRef Name="ows_Title"/>
<Value Type="Text">someValue</Value>
</Eq>
</Where>
</Query></query>
<Parameters>
<Parameter Name="listName">
<DefaultValue>{BD8D39B7-FA0B-491D-AC6F-EC9B0978E0CE}</DefaultValue>
</Parameter>
<Parameter Name="viewName">
<DefaultValue>{E2168426-804F-4836-9BE4-DC5F8D08A54F}</DefaultValue>
</Parameter>
<Parameter Name="rowLimit">
<DefaultValue>9999</DefaultValue>
</Parameter>
</Parameters>
</Method>
<ElementPath IgnoreNamespaces="True">*</ElementPath>
</Query>
```
I tried to put the new query statement in every possible way in the existing, but it doesn't work at all, I do not get an error though so the code is valid, but I still get an unfiltered list as return... *pulling my hair out here!* | A post at:
<http://social.msdn.microsoft.com/forums/en-US/sqlreportingservices/thread/1562bc7c-8348-441d-8b59-245d70c3d967/>
Suggested using this syntax for placement of the <Query> node (this example is to retrieve the item with an ID of 1):
```
<Query>
<SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction>
<Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems">
<Parameters>
<Parameter Name="listName">
<DefaultValue>{CE7A4C2E-D03A-4AF3-BCA3-BA2A0ADCADC7}</DefaultValue>
</Parameter>
<Parameter Name="query" Type="xml">
<DefaultValue>
<Query>
<Where>
<Eq>
<FieldRef Name="ID"/>
<Value Type="Integer">1</Value>
</Eq>
</Where>
</Query>
</DefaultValue>
</Parameter>
</Parameters>
</Method>
<ElementPath IgnoreNamespaces="True">*</ElementPath>
</Query>
```
However this would give me the following error:
Failed to execute web request for the specified URL
With the following in the details:
Element <Query> of parameter query is missing or invalid
From looking at the SOAP message with Microsoft Network Monitor, it looks as though the <Query> node is getting escaped to <Query> etc, which is why it fails.
However, I was able to get this to work using the method described in Martin Kurek's response at:
<http://www.sharepointblogs.com/dwise/archive/2007/11/28/connecting-sql-reporting-services-to-a-sharepoint-list-redux.aspx>
So, I used this as my query:
```
<Query>
<SoapAction>http://schemas.microsoft.com/sharepoint/soap/GetListItems</SoapAction>
<Method Namespace="http://schemas.microsoft.com/sharepoint/soap/" Name="GetListItems">
<Parameters>
<Parameter Name="listName">
<DefaultValue>{CE7A4C2E-D03A-4AF3-BCA3-BA2A0ADCADC7}</DefaultValue>
</Parameter>
<Parameter Name="query" Type="xml">
</Parameter>
</Parameters>
</Method>
<ElementPath IgnoreNamespaces="True">*</ElementPath>
</Query>
```
And then defined a parameter on the dataset named query, with the following value:
```
<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Integer">1</Value></Eq></Where></Query>
```
I was also able to make my query dependent on a report parameter, by setting the query dataset parameter to the following expression:
```
="<Query><Where><Eq><FieldRef Name=""ID""/><Value Type=""Integer"">" &
Parameters!TaskID.Value &
"</Value></Eq></Where></Query>"
``` | See the question and answers for [GetListItems Webservice ignores my query filter](https://stackoverflow.com/questions/835358). This shows you how (and how not to) set up your SOAP call to include a query. You probably need to wrap your query with another `<Query></Query>`. | SOAP call with query on result (SSRS, Sharepoint) | [
"",
"sql",
"xml",
"sharepoint",
"visual-studio-2005",
"reporting",
""
] |
Does anyone of you know off by hand what mail headers to add in order to get a read receipt and delivery report? This now being when you use the normal PHP mail function. No fancy add-on script / class like phpMail. | **For the reading confirmations:**
You have to add the `X-Confirm-Reading-To` header.
```
X-Confirm-Reading-To: <address>
```
**For delivery confirmations:**
You have to add the `Disposition-Notification-To` header.
For usage details see [RFC 3798](https://www.rfc-editor.org/rfc/rfc3798).
---
**General tip for stuff like this:**
Use the mail client of your choice to generate an e-mail with the desired parameters, send it to yourself and look at the mail source.
There you can find the necessary headers added by the feature you are looking for. Then read the RFC or google for specific details on the header in question. | Gmail blocks methods such as:
> img src="http://yourdomain/tracking.php?id=EMAIL\_ID" width="0" height="0"
This is because the image is retrieved from a proxy. Since the URL contains variables and not a real image file, the image will not be shown. The tracker would be useless.
I've personally experienced this as I build my own newsletter system. | Delivery reports and read receipts in PHP mail | [
"",
"php",
"email",
""
] |
I have string which might be int, datetime, boolean, byte etc'.
How can i validate that the string can be convert into those types without using the TryParse of each type? | ```
public class GenericsManager
{
public static T ChangeType<T>(object data)
{
T value = default(T);
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
value = (T)Convert.ChangeType(data, Nullable.GetUnderlyingType(typeof(T)));
}
else
{
if (data != null)
{
value = (T)Convert.ChangeType(data, typeof(T));
}
}
return value;
}
}
```
Not massively useful here, but i guess you could use this, and validate that the result is not equal to the default for that type.
However, tryparse is much better and to the point of what you are trying to do. | Apart from calling Parse() inside a try catch block (a terrible idea), I think the only alternative is to write your own parsing algorithm (also a bad idea).
Why don't you want to use the TryParse methods? | How to validate string can be convert to specific type? | [
"",
"c#",
"parsing",
"types",
""
] |
I truly love NUnit's new(er) ability to test for expected exception testing, ie:
```
var ex = Assert.Throws<SomeException>(()=>methodToThrowException("blah"));
```
One minor issue I find is that to test some sort of operator overload or other assignment type functionality, the only way I can know how to do this is by giving the compiler a variable to assign to, like so:
```
// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { var ignored = nbr / m; });
```
This is compact and works great, but has the annoyance where Resharper puts out a warning that the variable ignored is never used. This is counter productive if you like to use Resharper visuals to help you judge the quality of the code at a glance, as I do. Resharper is technically correct of course, but is there a way to tell Resharper this is my intention? I have a test with a lot of these sorts of tests, so a pragma will look nasty.
Any suggestions (besides "get over it, dude")?
Cheers | Add a field to the unit test and suppress the warning, ie:
```
// ReSharper disable UnaccessedField.Local
private object _ignore;
// ReSharper restore UnaccessedField.Local
```
The use that field as the assignment variable in your test delegate:
```
// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { _ignore = nbr / m; });
```
This keeps resharper quiet, so you know if it does complain about something now it is likely a legitimate complaint that should be looked at. This eliminates the noise level so you can focus (I have over 50 tests like this in an important class that needs some refactoring).
Cheers,
Berryl | You could write your own `Throws` method which takes a `Func<object>` instead, and then just write:
```
var ex = Assert.Throws<PreconditionException>(() => nbr / m);
```
Then submit the new method to NUnit and wait for the next release :) | nunit resharper expected exception testing | [
"",
"c#",
"exception",
"nunit",
"resharper",
""
] |
I've been trying myself, and searching online, to write this regular expression but without success.
I need to validate that a given URL is from a specific domain and a well-formed link (in PHP). For example:
Good Domain: example.com
So good URLs from example.com:
* <http://example.com/so/this/is/good>
* <http://example.com/so/this/is/good/index.html>
* <http://www.examle.com/so/this/is/good/mice.html#anchortag>
* <http://anysubdomain.example.com/so/this/is/good/wow.php>
* <http://anysubdomain.example.com/so/this/is/good/wow.php?search=doozy>
So bad URLs not from example.com:
* <http://obviousexample.com>
* <http://localhost/example.com/whatever/you/get/the/idea>
* etc.
Some notes:
I don't care about "http" verus "https" but if it matters to you assume "http" always
The code that will use this regex is PHP so extra points for that.
**UPDATE 2010:**
Gruber adds a great URL regex:
```
?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
```
See his post: [An Improved Liberal, Accurate Regex Pattern for Matching URLs](http://daringfireball.net/2010/07/improved_regex_for_matching_urls) | My stab at it
```
<?php
$pattern = "#^https?://([a-z0-9-]+\.)*blah\.com(/.*)?$#";
$tests = array(
'http://blah.com/so/this/is/good'
, 'http://blah.com/so/this/is/good/index.html'
, 'http://www.blah.com/so/this/is/good/mice.html#anchortag'
, 'http://anysubdomain.blah.com/so/this/is/good/wow.php'
, 'http://anysubdomain.blah.com/so/this/is/good/wow.php?search=doozy'
, 'http://any.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
, 'http://999.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
, 'http://obviousexample.com'
, 'http://bbc.co.uk/blah.com/whatever/you/get/the/idea'
, 'http://blah.com.example'
, 'not/even/a/blah.com/url'
);
foreach ( $tests as $test )
{
if ( preg_match( $pattern, $test ) )
{
echo $test, " <strong>matched!</strong><br>";
} else {
echo $test, " <strong>did not match.</strong><br>";
}
}
// Here's another way
echo '<hr>';
foreach ( $tests as $test )
{
if ( $filtered = filter_var( $test, FILTER_VALIDATE_URL ) )
{
$host = parse_url( $filtered, PHP_URL_HOST );
if ( $host && preg_match( "/blah\.com$/", $host ) )
{
echo $filtered, " <strong>matched!</strong><br>";
} else {
echo $filtered, " <strong>did not match.</strong><br>";
}
} else {
echo $test, " <strong>did not match.</strong><br>";
}
}
``` | Do you have to use a regex? PHP has a lot of built in functions for doing this kind of thing.
```
filter_var($url, FILTER_VALIDATE_URL)
```
will tell you if a URL is valid, and
```
$domain = parse_url($url, PHP_URL_HOST);
```
will tell you the domain it refers to.
It might be clearer and more maintainable than some mad regex. | Specific domain URL validation with Regular Expression | [
"",
"php",
"regex",
""
] |
I was waiting for the stable release of Netbeans 6.7 before starting to use it for my Java Programming.
I would like to how to change the Dimensions of the Applet Viewer in NetBeans 6.7.
When ever i run a java file by pressing SHIFT + F6, it opens an Applet but the dimensions are too small, i think they are around 300 X 300.
How to change those dimensions ? | Go to the project properties, there you choose *Application -> Web Start*, select *Applet descriptor* and click the button *Applet Parameters*. There you can set required dimensions. | Or use the Resize() option to change the applet size when you run. Put the resize(width,heaght) in init() of your applet. | How to change the Dimensions of the Applet Viewer in NetBeans 6.7 | [
"",
"java",
"netbeans6.7",
""
] |
I want to preserve a property between postbacks in an ASP.Net application. Currently doing this:
```
public int MyIndex
{
get
{
return (int)Session[ToString() + "MyIndex"];
}
}
```
but would prefer something like:
```
public int MyIndex
{
get
{
return (int)Session[ToString() + #code_that_returns_property_name#];
}
}
```
Setter omitted, but it just pushes value into Session using the same string.
Is there some way to use reflection, or a different better solution? | ```
public static int Dummy {
get {
var propertyName = MethodBase.GetCurrentMethod().Name.Substring(4);
Console.WriteLine(propertyName);
return 0;
}
}
``` | Using **CallerMemberName** is a lot faster and it can be copied and pasted easily for additional properties.
```
private static object GetSessionValue([CallerMemberName]string propertyName = "")
{
return Session[propertyName];
}
private static void SetSessionValue(object value, [CallerMemberName]string propertyName = "")
{
Session[propertyName] = value;
}
public int MyIndex
{
get { return (int)GetSessionValue(); }
set { SetSessionValue(value); }
}
``` | Get property name inside setter | [
"",
"c#",
".net",
"reflection",
"properties",
""
] |
I've got a set of TreeNodes, each of which has an id, a Collection of parent nodes, and a collection of child nodes.
For a given node Id, I'm looking for an efficient way to generate all the links that pass through that node. So in short, start at the node, and iterate through all its children. If a node has more than one child, create a link for each child. The traverse the children etc..
I'd also like to be able to do this in an 'upward' direction, through the parent nodes.
Is there a simple algorithm to do this?
EDIT: Oh, and I'd like to be able to output the id's of all the nodes in a given chain... | You are looking for a [Breadth First](http://en.wikipedia.org/wiki/Breadth-first_search) or [Depth First Search](http://en.wikipedia.org/wiki/Depth-first_search). At first it is not more than the following (this is depth first search).
```
Visit(Node node)
{
foreach (Node childNode in node.Children)
{
Visit(childNode);
}
DoStuff(node);
}
```
The problem is that the graph may contain cycles, hence the algorithm will enter infinite loops. To get around this you must remember visited nodes by flaging them or storing them in a collection. If the graph has no cycles - for example if it is a tree - this short algorithm will already work.
And by the way, if a TreeNode has multiple parents, it's not a tree but a graph node. | You might want to check out `depthFirstEnumeration()` and `breadthFirstEnumeration()` on `DefaultMutableTreeNode`. However, this doesn't solve your problem of wanting to navigate the tree in a bottom-up fashion. | Efficient way to walk through an object tree? | [
"",
"java",
"algorithm",
"search",
""
] |
Say I have a query like this:
```
select ((amount1 - amount2)/ amount1) as chg from t1
where
((amount1 - amount2)/ amount1) > 1 OR
((amount1 - amount2)/ amount1) < 0.3
```
Is there a way I can perform the arithmetic calculation only once instead of doing it thrice as in the above query ?
**EDIT:** I am not sure if the database automatically optimizes queries to do such calcs only once? I am using T-SQL on Sybase. | It's better to have repeated arithmetic operation than more IO
**-- ADDED LATER**
I've checked all 3 solutions in SQL Server 2000, 2005 and 2008 (over 100,000 random rows), and in all cases they have exactly the same execution plans as well as CPU and IO usage.
Optimizer does good job.
```
select calc.amtpercent
from ( select (amount1-amount2)/cast(amount1 as float) as amtpercent from z8Test) calc
where calc.amtpercent > 1 OR calc.amtpercent < 0.3
select (amount1-amount2)/cast(amount1 as float) as amtpercent
from z8Test
where (amount1-amount2)/cast(amount1 as float) > 1
or (amount1-amount2)/cast(amount1 as float) < 0.3
select (amount1-amount2)/cast(amount1 as float) as amtpercent
from z8Test
where (amount1-amount2)/cast(amount1 as float) not between 0.3 and 1
```
**Answer on Alex comment:** Have you ever worked with databases? I've seen so many times bottlenecks in IO and never in CPU of database server. To be more precise, in few occasions when I had high CPU usage it was caused by IO bottlenecks and only in two cases because of queries that wrongly used encryption techniques (instead of encrypting parameter value and compare against column in huge table query was decrypting column and comparing against parameter) in the first and the awful number of unnecessary conversions (datetime to string and back to datetime) in second case for a query that was triggered really frequent.
Of course you have to avoid unnecessary arithmetic, but be careful if you have to increase IO as a trade off. | Conceptually you could select from your calculation, i.e:
```
select
calc.amt
from
(select (amt1 - amt2) / amt1 as amt from #tmp) calc
where
calc.amt > 1 OR calc.amt < 0.3
```
Not sure off the top of my head if SQL would optimise your code to similar anyway - running your query against my query off a basic temp table seems to indicate they execute in the same way. | How can I tweak this SQL to perform the arithmetic calculation only once | [
"",
"sql",
"database",
"t-sql",
""
] |
I have a mobile site and I'd like to redirect users to the domain.mobi or mobile.subdomain (we have both setup)
1. How do I determine a mobile browser- Is it bad practice to have the mobile site on a different domain or subdomain? | > 1. How do I determine a mobile browser
Here's some javascript that will do the job: <http://www.quirksmode.org/js/detect.html>
> 2. Is it bad practice to have the mobile site on a different domain or
> subdomain?
It's good practice, and a popular convention is to use <http://m.yoursite.com> for mobile if your main url is <http://yoursite.com>
Noah | There are a number of solutions for determining mobile browsers. Most use the UserAgent making the request but some solutions use other factors as well.
Try looking at:
[WURFL](http://wurfl.sourceforge.net/)
[MDBF](http://mdbf.codeplex.com/)
[DeviceAtlas](http://deviceatlas.com/)
[DetectRight](http://www.detectright.com/)
[Volantis](http://www.volantis.com/)
[MobileAware](http://www.mobileaware.com/)
[Movila](http://www.moviladetection.com/)
[UAProf](http://en.wikipedia.org/wiki/UAProf) | User agents for mobile site, domain changing | [
"",
"php",
"mobile-phones",
"mobile-website",
""
] |
I'm writing standards compliant XHTML Strict 1.0, so including the HTML "target" attribute on anchor elements will not do.
I've read 2 fundamentally different ways using Javascript:
1. Upon document load, find all links with **`rel='external'`** and append the **`target='_blank'`** attribute.
2. Use the HTML **`onClick`** attribute that fires a Javascript **`popup(this)`** function, which opens windows with **`window.open()`**.
These methods are now 5-6 years old, so I'm hoping things have solidified since then. What's the best way to do this? | [With JQuery and Iframes](http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-using-jquery/) (or an object instead) | There is no new way of doing this, so what you already have found is what there is.
The first method is kind of cheating. You are using Javascript to put non-standard markup in the page after it has loaded, just so that the initially loaded markup will be valid. Once the script has run, the code isn't valid any more.
The second method seems better also from another perspective. The links will work as intended instantly when the page loads, compared to the first method that will not change the links until after all content on the page has loaded. If a user is quick and clicks a link before the last image has been loaded, you still want it to go to a new window. | What's the best way to write a standards compliant popup window with XHTML and Javascript? | [
"",
"javascript",
"html",
"xhtml",
"dom-events",
"standards",
""
] |
Unlike this question:
[Linker Error while building application using Boost Asio in Visual Studio C++ 2008 Express](https://stackoverflow.com/questions/704294/linker-error-while-building-application-using-boost-asio-in-visual-studio-c-200)
I need an x64 build of the lib files... I'm not even sure how to get started. I'm reading here:
<http://www.boost.org/doc/libs/1_39_0/more/getting_started/windows.html>
Or, more generally, how do I build boost for x64? | I'm not on Windows, but I guess adding address-model=64 to the bjam invocation should do the trick. | Here is the command line I ended up using:
C:\Program Files (x86)\boost\boost\_1\_38>bjam --build-dir=c:\boost --build-type=complete --toolset=msvc-9.0 address-model=64 architecture=x86 --with-system | Using Boost::asio in Winx64: I'm stuck, need to figure out how to build libboost_system_xxxx.lib for x64 | [
"",
"c++",
"windows",
"boost",
"64-bit",
""
] |
I want to query the name of all columns of a table. I found how to do this in:
* [Oracle](https://stackoverflow.com/q/452464/419956)
* [MySQL](https://stackoverflow.com/q/193780/419956)
* [PostgreSQL](https://dba.stackexchange.com/q/22362/5089)
But I also need to know: **how can this be done in *Microsoft SQL Server* (2008 in my case)?** | You can obtain this information and much, much more by querying the [Information Schema views](http://msdn.microsoft.com/en-us/library/aa933204%28SQL.80%29.aspx).
This sample query:
```
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
```
Can be made over all these DB objects:
* [CHECK\_CONSTRAINTS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/check-constraints-transact-sql)
* [COLUMN\_DOMAIN\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/column-domain-usage-transact-sql)
* [COLUMN\_PRIVILEGES](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/column-privileges-transact-sql)
* [COLUMNS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/columns-transact-sql)
* [CONSTRAINT\_COLUMN\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/constraint-column-usage-transact-sql)
* [CONSTRAINT\_TABLE\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/constraint-table-usage-transact-sql)
* [DOMAIN\_CONSTRAINTS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/domain-constraints-transact-sql)
* [DOMAINS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/domains-transact-sql)
* [KEY\_COLUMN\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/key-column-usage-transact-sql)
* [PARAMETERS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/parameters-transact-sql)
* [REFERENTIAL\_CONSTRAINTS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/referential-constraints-transact-sql)
* [ROUTINES](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/routines-transact-sql)
* [ROUTINE\_COLUMNS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/routine-columns-transact-sql)
* [SCHEMATA](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/schemata-transact-sql)
* [TABLE\_CONSTRAINTS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/table-constraints-transact-sql)
* [TABLE\_PRIVILEGES](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/table-privileges-transact-sql)
* [TABLES](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/tables-transact-sql)
* [VIEW\_COLUMN\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/view-column-usage-transact-sql)
* [VIEW\_TABLE\_USAGE](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/view-table-usage-transact-sql)
* [VIEWS](https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/views-transact-sql) | You can use the stored procedure sp\_columns which would return information pertaining to all columns for a given table. More info can be found here <http://msdn.microsoft.com/en-us/library/ms176077.aspx>
You can also do it by a SQL query. Some thing like this should help:
```
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo.yourTableName')
```
Or a variation would be:
```
SELECT o.Name, c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.type = 'U'
ORDER BY o.Name, c.Name
```
This gets all columns from all tables, ordered by table name and then on column name. | How can I get column names from a table in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have an object for which I want to generate a unique hash (override GetHashCode()) but I want to avoid overflows or something unpredictable.
The code should be the result of combining the hash codes of a small collection of strings.
The hash codes will be part of generating a cache key, so ideally they should be unique however the number of possible values that are being hashed is small so I THINK probability is in my favour here.
Would something like this be sufficient AND is there a better way of doing this?
```
int hash = 0;
foreach(string item in collection){
hash += (item.GetHashCode() / collection.Count)
}
return hash;
```
EDIT: Thanks for answers so far.
@Jon Skeet: No, order is not important
I guess this is almost a another question but since I am using the result to generate a cache key (string) would it make sense to use a crytographic hash function like MD5 or just use the string representation of this int? | The fundamentals pointed out by Marc and Jon are not bad but they are far from optimal in terms of their evenness of distribution of the results. Sadly the 'multiply by primes' approach copied by so many people from Knuth is [not the best choice in many cases](http://www.codeproject.com/KB/recipes/hash_functions.aspx) better distribution can be achieved by cheaper to calculate functions (though this is *very* slight on modern hardware). In fact throwing primes into many aspects of hashing is [no panacea](http://www.codexon.com/posts/hash-functions-the-modulo-prime-myth).
If this data is used for significantly sized hash tables I recommend reading of [Bret Mulvey's excellent study and explanation of various modern (and not so modern) hashing techniques](http://home.comcast.net/~bretm/hash/) handily done with c#.
Note that the behaviour with strings of various hash functions is heavily biased towards wehther the strings are short (roughly speaking how many characters are hashed before the bits begin to over flow) or long.
One of the simplest and easiest to implement is also one of the best, the Jenkins One at a time hash.
```
private static unsafe void Hash(byte* d, int len, ref uint h)
{
for (int i = 0; i < len; i++)
{
h += d[i];
h += (h << 10);
h ^= (h >> 6);
}
}
public unsafe static void Hash(ref uint h, string s)
{
fixed (char* c = s)
{
byte* b = (byte*)(void*)c;
Hash(b, s.Length * 2, ref h);
}
}
public unsafe static int Avalanche(uint h)
{
h += (h<< 3);
h ^= (h>> 11);
h += (h<< 15);
return *((int*)(void*)&h);
}
```
you can then use this like so:
```
uint h = 0;
foreach(string item in collection)
{
Hash(ref h, item);
}
return Avalanche(h);
```
you can merge multiple different types like so:
```
public unsafe static void Hash(ref uint h, int data)
{
byte* d = (byte*)(void*)&data;
AddToHash(d, sizeof(int), ref h);
}
public unsafe static void Hash(ref uint h, long data)
{
byte* d= (byte*)(void*)&data;
Hash(d, sizeof(long), ref h);
}
```
If you only have access to the field as an object with no knowledge of the internals you can simply call GetHashCode() on each one and combine that value like so:
```
uint h = 0;
foreach(var item in collection)
{
Hash(ref h, item.GetHashCode());
}
return Avalanche(h);
```
Sadly you can't do sizeof(T) so you must do each struct individually.
If you wish to use reflection you can construct on a per type basis a function which does structural identity and hashing on all fields.
If you wish to avoid unsafe code then you can use bit masking techniques to pull out individual bits from ints (and chars if dealing with strings) with not too much extra hassle. | Hashes aren't *meant* to be unique - they're just meant to be well distributed in most situations. They're just meant to be consistent. Note that overflows shouldn't be a problem.
Just adding isn't generally a good idea, and dividing certainly isn't. Here's the approach I usually use:
```
int result = 17;
foreach (string item in collection)
{
result = result * 31 + item.GetHashCode();
}
return result;
```
If you're otherwise in a checked context, you might want to deliberately make it unchecked.
Note that this assumes that order is important, i.e. that { "a", "b" } should be different from { "b", "a" }. Please let us know if that's not the case. | Is it possible to combine hash codes for private members to generate a new hash code? | [
"",
"c#",
"hashcode",
"gethashcode",
""
] |
How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes. | On linux, the easiest solution is probably to use the external `ps` command:
```
>>> import os
>>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
... for x in os.popen('ps h -eo pid:1,command')]]
```
On other systems you might have to change the options to `ps`.
Still, you might want to run `man` on `pgrep` and `pkill`. | The right portable solution in Python is using [psutil](https://github.com/giampaolo/psutil). You have different APIs to interact with PIDs:
```
>>> import psutil
>>> psutil.pids()
[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
>>> psutil.pid_exists(32498)
True
>>> p = psutil.Process(32498)
>>> p.name()
'python'
>>> p.cmdline()
['python', 'script.py']
>>> p.terminate()
>>> p.wait()
```
...and if you want to "search and kill":
```
for p in psutil.process_iter():
if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
p.terminate()
p.wait()
``` | how do I get the process list in Python? | [
"",
"python",
"unix",
"kill",
"ps",
"processlist",
""
] |
I am developing a program where I find myself doing this like this a lot:
```
void Model::SetCollideMode( const std::string &m )
{
Body *body;
std::map<std::string, Body* >::iterator iter;
for (iter=this->bodies.begin(); iter!=this->bodies.end(); iter++)
{
body = iter->second;
body->SetCollideMode( m );
}
}
```
I have several methods like that in several object that basically apply a property to all its children. Coming from Ruby world I am dying to do something like:
```
for_all_bodies{ body->SetCollideMode(m) }
```
There is anyway to make this code more closures like or in other way improve it?
I am conscious of how C++ works, that it is stack based and there is no context information to create a perfect closure like functionality (this need a VM?) but at least improve over the current repeat this code 100 times kind of programming. | There are several approaches, none of them perfect.
First, the "conventional" approach would be to define a functor to do what you need:
```
struct SetCollideModeFunc {
SetCollideModeFunc(const std::string& m) : m(m) {}
void operator()(std::pair<std::string, Body*>& p) {
Body* b = p.second;
b->SetCollideMode(m);
}
const std::string& m;
};
void Model::SetCollideMode( const std::string &m )
{
std::for_each(bodies.begin(), bodies.end(), SetCollideModeFunc(m));
}
```
This doesn't save you a lot of code, but it does allow you to separate the iteration from the operation that you want to apply. And if you need to set collidemode multiple times, you can reuse the functor, of course.
A shorter version is possible with the Boost.Lambda library, which would allow you to define the functor inline. I can't remember the exact syntax, as I don't use Boost.Lambda often, but it'd be something like this:
```
std::for_each(bodies.begin(), bodies.end(), _1.second->SetCollideMode(m));
```
In C++0x, you get language support for lambdas, allowing syntax similar to this without having to pull in third-party libraries.
Finally, Boost.ForEach might be an option, allowing syntax such as this:
```
void Model::SetCollideMode(const std::string &m)
{
BOOST_FOREACH ((std::pair<std::string, Body*> p), bodies) // note the extra parentheses. BOOST_FOREACH is a macro, which means the compiler would choke on the comma in the pair if we do not wrap it in an extra ()
{
p.second->SetCollideMode(m);
}
}
``` | In C++0x, yes. [See here.](http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions) Just as you've guessed, they are done in the characteristic C++ way, i.e. if you accidentally close over a stack variable and then let the lambda object survive longer than the stack, then you have undefined behaviour. It's a whole new way to make your program crash! But that's unfair - in many ways they are more sophisticated than lambdas in many other languages, because you can declare the extent to which they are allowed to mutate state.
Until then, [there have been attempts to emulate the same thing](http://www.boost.org/doc/libs/1_39_0/doc/html/lambda.html), but they're probably more trouble than they're worth. | Ruby blocks, java closures in C++ | [
"",
"c++",
"stl",
"iterator",
"closures",
""
] |
How do I use DB2's Explain function? -- both to run it, and to use it to optimize queries. Is there a better tool available for DB2?
I've built queries before, but the only way I've had to tell how long they'd take is to run them and time them -- which is hardly ideal.
Edit:
The answer for me turned out to be "You can't. You don't have and cannot get the access." Don't you love bureaucracy? | What you're looking for is covered by two Db2 utilities:
1. The [explain facility](https://www.ibm.com/docs/en/db2/11.5?topic=optimization-explain-facility), which shows the optimizer's access plan and estimated resource cost for a specific query (based on current RUNSTATS statistics)
2. The [design advisor](https://www.ibm.com/docs/en/db2/11.5?topic=strategy-design-advisor), which recommends structural changes to improve the performance of one or more queries
Both utilities require specialized [tables](https://www.ibm.com/docs/en/db2/11.5?topic=sql-explain-tables) to be created in the database.
I tend to use the explain facility more than the design advisor, especially if I have the option of changing the underlying SQL of the statement that needs to be tuned. The [`db2expln` command](https://www.ibm.com/docs/en/db2/11.5?topic=commands-db2expln-sql-xquery-explain) is a convenient way to run the explain facility from the command line for any SQL or XQuery statement. I commonly run `db2expln` multiple times when comparing the costs of different versions of a statement I'm tuning. It's important that your table and index statistics are up to date when running explain or the design advisor. | IBM offers [**Data Studio**](https://www.ibm.com/products/ibm-data-studio) as a free tool built on eclipse, which among other benefits **includes a GUI for running visual explain, as well as providing tuning help through a query adviser.** *I highly recommend using Data Studio.*
It is relatively easy to set up the correct resources (the explain tables that need to be built, and the bind that need to be done) by right clicking a connected data source, and choosing
*analyze and tune > configure for tuning > guided configuration.*

To **generate the explain graph** - simply highlight your query, right click, and choose "Open Visual Explain":

To use the **query advisor**, choose "start tuning" instead. It will take you through a process which will generate the explain, as well as recommend any tuning opportunities it can determine.
 | How do I use DB2 Explain? | [
"",
"sql",
"db2",
"query-optimization",
"explain",
""
] |
*Not entirely sure of a good title for this, feel free to edit it to a good one*
I have an images object, which contains a list of organs which it is related to.
I want to query a list of images and find which ones have *all* of the organs in a list of organs.
Here is the method signature
```
public static IEnumerable<Image> WithOrgans(this IEnumerable<Image> qry, IEnumerable<Organ> organs)
```
Not really sure how to construct the linq for this, would appreciate some ideas, I haven't done linq in a while so am quite rusty!
UPDATE
Ok, so this is some sample data
```
dictionary.Add(7, new Image { id = 7, organs = new List<Organ> { organA, organB }});
dictionary.Add(8, new Image { id = 8, organs = new List<Organ> { organA }});
dictionary.Add(9, new Image { id = 9, organs = new List<Organ> { organC }});
``` | Another way of doing it using Intersect:
```
from i in qry
where i.Organs.Intersect(organs).Count == organs.Count
select i
```
ETA:
From your comment, you mention you are getting a WhereListIterator back. I believe that the WhereListIterator implements IEnumerable, so you are getting back exactly what you should be getting.
If you are finding that the results are empty when they shouldn't be, you might want to check to make sure your Image class implements Equals() and GetHashCode() properly so that they can be effectively compared. | Assuming the associated organs of an image are stored in the collection Image.Organs, the following query will do the trick. It depends on your LINQ provider if some modification are required because of unsupported functions.
```
public static IEnumerable<Image> WithOrgans(
this IEnumerable<Image> qry, IEnumerable<Organ> organs)
{
return qry.Where(image => organs.All(organ => image.Organs.Contains(organ)));
}
``` | LINQ query question, needs joins | [
"",
"c#",
"linq",
""
] |
I have multiple themes on my website and users can just switch between multiple themes by clicking on a javascript link. I have 5 CSS files to handle the layout of all of the themes.
1 is for structure, 3 are for colors etc for different themes, and 1 common for some other stuff.
my css filenames read like this ..
main.css, red.css, green.css, black.css, others.css
With red, green and black css files are defined as `alternate stylesheet`s.
I have installed YSLOW! and get `"This page has 5 external stylesheets. Try combining them into one."`
I was just wondering if it is possible to combine most of them into a fewer numbers of CSS files. I know that we can define
`
```
@media screen
{
//screen
}
@media print
{
//print
}
```
`
sections in a single CSS file. Can something like this be done for multiple CSS files as well?
Thanks for your help. | Your main and other can be combined, then rather than attaching the other three, can you not jsut load them with javascript when necessary?
Something like this:
```
<link rel="stylesheet" href="style1.css" id="stylesheet">
<script type="text/javascript">
function changeStyle() {
document.getElementById('stylesheet').href = 'style2.css';
}
</script>
``` | Combine the two common stylesheets, and ignore YSlow for the alternative ones. YSlow is a tool, not the enforcer of the law. | How to avoid this? Yslow -> "This page has 5 external stylesheets. Try combining them into one." | [
"",
"javascript",
"html",
"css",
"yslow",
""
] |
I'm implementig a Composite pattern in [this way](http://en.wikipedia.org/wiki/Composite_pattern):
1) the "abstract" component is:
```
class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
```
2) a leaf:
```
class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
```
The Problem is that pylint generates, of course, this warning:
```
Leaf.__init__: __init__ method from base class 'Component' is not called
```
but into my Leaf i cannot call for:
```
def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
```
without raise of the exception.
Must I ignore pylint warning or there is some bad coding? | Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.
If you don't want any instances of the Component class around, check for that in the initializer:
```
class Component(object):
def __init__(self, **kwargs):
assert type(self) != Component, "Component must not be instantiated directly"
class Leaf(Component):
def __init__(self, some, args, **kwargs):
# regular initialization
Component.__init__(self, **kwargs)
``` | Another suggestion to complement the idea of Markus:
If you really must, I suggest that you use \_\_new \_\_ and check for the given object type. When it is "Component" you could fire your exception:
```
class Component(object):
"""Basic Component Abstraction"""
def __new__(objType, *args, **kwargs):
if objType == Component:
raise NotImplementedError("must be subclassed")
return object.__new__(type, *args, **kwargs)
```
When a subclass is created, objType will be != Component and all will be fine! | Python composite pattern exception handling & pylint | [
"",
"python",
"composite",
"pylint",
""
] |
I am lookign for the correct SQL code to join 2 tables and show only the last record of the details table.
I have a DB with 2 tables,
```
Deals
DealID
Dealname
DealDetails
DealComments
dcID
DealID
CommentTime
CommentPerson
Comment
```
There are multiple comments for each Deal, but i would like to create a VIEW that displays all of the Deals and only the last Comment from each Deal (determined by the CommentTime) field | ```
select a.dealid
, a.dealname
, a.dealdetails
, b.dcid
, b.commenttime
, b.commentperson
, b.comment
from deals a, dealcomments b
where b.dealid = a.dealid
and b.commenttime = (select max(x.commenttime)
from dealcomments x
where x.dealid = b.dealid)
```
EDIT: I didn't read the initial question close enough and didn't notice that all DEALS rows were needed in the view. Below is my revised answer:
```
select a.dealid
, a.dealname
, a.dealdetails
, b.dcid
, b.commenttime
, b.commentperson
, b.comment
from deals a left outer join (select x.dcid
, x.dealid
, x.commenttime
, x.commentperson
, x.comment
from dealcomments x
where x.commenttime = (select max(x1.commenttime)
from dealcomments x1
where x1.dealid = x.dealid)) b
on (a.dealid = b.dealid)
``` | Obligatory no-subquery-nowhere-answer:
```
select d.*
, dc.*
from Deals d
left outer join DealComments dc
on d.DealID = dc.DealID
left outer join DealComments dc1
on d.DealID = dc1.DealID
and
dc1.CommentTime > dc.CommentTime
where dc1.CommentTime is null
```
Show me everything in `Deals` and `DealComments` when there exists no `CommentTime` greater than any given comment time for a particular `DealID`.
Edit: as Alex Kuznetsov astutely points out in a comment: the OP requested that *all* deals be displayed -- whether a deal has a comment or not. So I have changed the first `JOIN` from `INNER` to `LEFT OUTER`. | Last record of Join table | [
"",
"sql",
""
] |
Here is my try:
```
@header("Content-type: text/html; charset=utf-8");
@header("Location:/index.php");
@header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
@header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
```
As you have seen,there is no control over "3 seconds",how to make it take effect in 3 seconds? | This should work, in PHP:
```
header('Refresh: 3; url=index.php');
``` | The easiest way to do this is to use a [`meta` redirect](http://webmaster.indiana.edu/tool_guide_info/refresh_metatag.shtml) or a javascript redirect. Saying as how you are serving text/html, you can echo either of these to the browser.
```
<meta http-equiv="refresh" content="3;URL=/newpage.php">
```
or
```
window.setTimeout(function() { window.location = '/newpage.php' }, 3000);
```
Edit: According to the Wikipedia page on [URL redirection](http://en.wikipedia.org/wiki/URL_redirection) you can send the `Refresh` header directly to the browser from PHP. No clue on how well browsers support this though.
```
header('Refresh: 3; url=/newpage.php');
``` | how to switch to another page in 3 seconds in PHP? | [
"",
"php",
"refresh",
""
] |
I have a number of strings which contain words which are bunched together and I need to seperate them up.
For example
ThisWasCool - This Was Cool
MyHomeIsHere - My Home Is Here
Im slowly getting my head around regular expressions and I believe to do this I should use preg\_replace. My problem is putting together the expression to find the match.
I have only got this far
```
preg_replace('~^[A-Z]~', " ", $string)
```
Each string contains a lot of words, but ONLY the first word contains bunched words so using my example above a string would be
"ThisWasCool to visit you again" - "This Was Cool to visit you again"
I have told it to start at the beginning, and look for capitals, but what I dont know how to do is
- restrict it only to the first word of each string
- how to reuse the capital letter in the replace part after the space | ### Problem
1. Your regex `'~^[A-Z]~'` will match only the first capital letter. Check out [Meta Characters](http://us.php.net/manual/en/regexp.reference.meta.php) in the [Pattern Syntax](http://us.php.net/manual/en/reference.pcre.pattern.syntax.php) for more information.
2. Your replacement is a newline character `'\n'` and not a space.
### Solution
Use this code:
```
$String = 'ThisWasCool';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
```
The `(?<!\ )` is an [assertion](http://us.php.net/manual/en/regexp.reference.assertions.php) that will make sure we don't add a space before a capital letter that already has a space before it. | ```
$string = preg_replace('/[A-Z]/', ' $0', $string);
```
Maybe run the result through [ltrim](http://php.net/manual/en/function.ltrim.php) after.
```
$string = ltrim(preg_replace('/[A-Z]/', ' $0', $string));
``` | Php put a space in front of capitals in a string (Regex) | [
"",
"php",
"regex",
""
] |
I have a query limited by a date range:
```
select * from mytable
where COMPLETIONDATE >= TO_DATE('29/06/08','DD/MM/YY')
and COMPLETIONDATE <= TO_DATE('29/06/09','DD/MM/YY')
```
The table is a log for activities for a ticket system. The content may be something like:
```
ticket_id|activity|completiondate
1 1 some
1 2 some
1 3 some
1 4 some
2 1 some
2 2 some
2 3 some
2 4 some
```
That way I know when each activity was completed.
My problems is, if the `completiondate` of the first activity happens "before" the date range I loss that info:
**where completiondate >= 1 jul 09 and completiondate <= 30 jul 09**
```
ticket_id |activity|completiondate
123 3 1 jul 09
123 4 2 jul 09
```
In this case I have lost the dates for activity 1 and 2 which took place on june 30 or before.
How can I, at the same time limit the date range of the items I want to show, but also include dates from the same tickets beyond the date range?
This is for a tickets report so I have to see:
```
Tickets from jun 1 - 30 :
Page won't load, received: march 20, fixed: jun 15
Change color, received: jun 5, fixed: in progress...
```
etc. | You're going to need to write a subquery that gets all IDs that have a completion date inside of your range, and then plug that into a query that returns all ticket information for those IDs.
```
select *
from mytable
where id in (select id from mytable where
COMPLETIONDATE >= TO_DATE('29/06/08','DD/MM/YY')
COMPLETIONDATE <= TO_DATE('29/06/09','DD/MM/YY')
)
``` | So you want all records for which at least one activity occurred in the period:
```
SELECT *
FROM mytable
WHERE id IN (
SELECT id
FROM mystable
WHERE COMPLETIONDATE BETWEEN ... AND ...);
``` | Extending SQL query to include records beyond a given date | [
"",
"sql",
""
] |
I have a SQLite table called `posts`. An example is shown below. I would like to calculate the monthly income and expenses.
```
accId date text amount balance
---------- ---------- ------------------------ ---------- ----------
1 2008-03-25 Ex1 -64.9 3747.56
1 2008-03-25 Shop2 -91.85 3655.71
1 2008-03-26 Benny's -100.0 3555.71
```
For the income I have this query:
```
SELECT SUBSTR(date, 0,7) "month", total(amount) "income" FROM posts
WHERE amount > 0 GROUP BY month ORDER BY date;
```
It works fine:
```
month income
---------- ----------
2007-05 4877.0
2007-06 8750.5
2007-07 8471.0
2007-08 5503.0
```
Now I need the expenses and I could of cause just repeat the first statement with the condition `amount < 0`, but I am wondering if there is an elegant way to get both income and expenses in one query? | Try something like this
```
select substr(date, 0,7) "Month",
total(case when a > 0 then a else 0 end) "Income",
total(case when a < 0 then a else 0 end) "Expenses"
from posts
group by month
``` | Not sure if SQL Lite supports CASE statements, but if it does you could do something like this.
```
SELECT SUBSTR(date, 0,7) "month"
, total(CASE WHEN Amount > 0 THEN Amount ELSE 0 END) "income"
, -1 * total(CASE WHEN Amount < 0 THEN Amount ELSE 0 END) "expenses"
FROM posts
GROUP BY month
ORDER BY date;
``` | Can I combine my two SQLite SELECT statements into one? | [
"",
"sql",
"database",
"sqlite",
""
] |
How can I gather the visitor's time zone information?
I need both:
1. the time zone (for example, Europe/London)
2. and the offset from UTC or GMT (for example, UTC+01) | # Using `getTimezoneOffset()`
You can get the time zone *offset* in minutes like this:
```
var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01
```
> The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale
* [Mozilla Date Object reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset)
Note that not all timezones are offset by whole hours: for example, Newfoundland is UTC minus 3h 30m (leaving Daylight Saving Time out of the equation).
Please also note that this only gives you the time zone offset (eg: UTC+01), it does not give you the time zone (eg: Europe/London). | Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.
To get the system's [IANA timezone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) in JavaScript, you should use
```
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
```
## As of April 2023, this [works in 95.42% of the browsers used globally](https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_resolvedoptions_computed_timezone).
### Old compatibility information
ecma-402/1.0 says that `timeZone` may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.
> **In this version of the ECMAScript Internationalization API, the
> `timeZone` property will remain undefined if no `timeZone` property was
> provided in the options object provided to the `Intl.DateTimeFormat`
> constructor**. However, applications should not rely on this, as future
> versions may return a String value identifying the host environment’s
> current time zone instead.
in ecma-402/3.0 which is still in a draft it changed to
> In this version of the ECMAScript 2015 Internationalization API, the
> `timeZone` property will be the name of the default time zone if no
> `timeZone` property was provided in the options object provided to the
> `Intl.DateTimeFormat` constructor. The previous version left the
> `timeZone` property undefined in this case. | Getting the client's time zone (and offset) in JavaScript | [
"",
"javascript",
"timezone",
""
] |
I have a WCF service implemented with a call back contract that I am trying to send a business object through. I have the business object decorated with DataContract() and DataMember() attributes, and it contains the following number of properties:
* ints: 3
* strings: 4
* XElement: 1
* other objects: 5 (also decorated with DataContract() and DataMember()
Whenever I try and send this object over the callback, the service times-out. I have tried creating other objects with fewer properties to send through the callback, and can get it to go through if there is only one property, but if I have any more than one property, the service times out.
Is there something wrong in my configuration? I have tried the default wsDualHttpBinding, as well as a customBinding (as displayed below) and I have tried all sorts of different settings with the maxBufferSize, maxBufferPoolSize, and maxReceivedMessageSize. I don't want to increase the timeout, as I would like this object to arrive to my client fairly quickly. Please somebody help me...if I had any hair left I would have pulled it out by now!!!!!
I have configured my service as such:
Server Configuration:
```
<customBinding>
<binding name="DualBindingConfig">
<reliableSession flowControlEnabled="true" maxPendingChannels="128" />
<compositeDuplex />
<oneWay/>
<binaryMessageEncoding/>
<httpTransport maxReceivedMessageSize="655360000" maxBufferPoolSize="655360000" />
</binding>
</customBinding>
<services>
<service behaviorConfiguration="Agent_Utility_WCF.Callback.AgentMessagingBehavior"
name="Agent_Utility_WCF.Callback.AgentMessaging">
<endpoint address="" binding="customBinding" bindingConfiguration="DualBindingConfig" bindingName="AgentMessaging" contract="Agent_Utility_WCF.Callback.IAgentMessaging">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Agent_Utility_WCF.Callback.AgentMessagingBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="160" maxConcurrentSessions="100"/>
</behavior>
</serviceBehaviors>
</behaviors>
```
Client Configuration:
```
<bindings>
<customBinding>
<binding name="AgentMessaging_IAgentMessaging">
<reliableSession acknowledgementInterval="00:00:00.2000000" flowControlEnabled="true"
inactivityTimeout="00:10:00" maxPendingChannels="4" maxRetryCount="8"
maxTransferWindowSize="8" ordered="true" reliableMessagingVersion="Default" />
<compositeDuplex />
<oneWay maxAcceptedChannels="10" packetRoutable="false">
<channelPoolSettings idleTimeout="00:02:00" leaseTimeout="00:10:00"
maxOutboundChannelsPerEndpoint="10" />
</oneWay>
<binaryMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
maxSessionSize="2048">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binaryMessageEncoding>
<httpTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://localhost:666/Callback/AgentMessaging.svc"
binding="customBinding" bindingConfiguration="AgentMessaging_IAgentMessaging"
contract="AgentMessaging.IAgentMessaging" name="AgentMessaging_IAgentMessaging">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
``` | Add the following to your web.config:
```
<system.diagnostics>
<trace autoflush="true">
<listeners>
</listeners>
</trace>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="sdt"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "WcfDetailTrace.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
```
Then invoke your web service method. This will generate *WcfDetailTrace.svclog* in the root of your web site. Open this file with [SvcTraceViewer.exe](http://msdn.microsoft.com/en-us/library/ms732023.aspx). This should give you pretty much information on what's going on. | How big are the other objects? For example, how large is the `XElement`'s subtree? The graph for an object can get quite large eventually, in particular if it calls into other objects.
A simple investigative approach might be to remove the `[DataMember]` attributes except perhaps one of the strings, and re-introduce them one at a time until it breaks. | Timeout occuring when sending business object through WCF Callback | [
"",
"c#",
".net",
"wcf",
"callback",
""
] |
How can I get the return value of a process? Basically I'm \*\*[ShellExecute](http://msdn.microsoft.com/en-us/library/bb762153%28VS.85%29.aspx)()\*\*ing a .NET process from a DLL (in C++). The process does its task, but now I want to know whether it succeeded or failed. How to do that in WinAPI or MFC? | Use [`ShellExecuteEx`](http://msdn.microsoft.com/en-us/library/bb762154.aspx) instead so you can get a handle to the process which was launched. You should then be able to use [`GetExitCodeProcess`](http://msdn.microsoft.com/en-us/library/ms683189.aspx) to obtain the exit code.
(I've left this answer here despite the similar one from MSalters, as I suspect you're using `ShellExecute` deliberately to get the shell behaviour instead of explicitly creating the process.) | Use CreateProcess(). keep the process handle and call GetExitCodeProcess() when the process handle becomes signalled. | Return value of process | [
"",
".net",
"c++",
"winapi",
"process",
"return-value",
""
] |
[C++ Notes: Array Initialization](http://www.fredosaurus.com/notes-cpp/arrayptr/array-initialization.html) has a nice list over initialization of arrays. I have a
```
int array[100] = {-1};
```
expecting it to be full with -1's but its not, only first value is and the rest are 0's mixed with random values.
The code
```
int array[100] = {0};
```
works just fine and sets each element to 0.
What am I missing here.. Can't one initialize it if the value isn't zero ?
And 2: Is the default initialization (as above) faster than the usual loop through the whole array and assign a value or does it do the same thing? | Using the syntax that you used,
```
int array[100] = {-1};
```
says "set the first element to `-1` and the rest to `0`" since all omitted elements are set to `0`.
In C++, to set them all to `-1`, you can use something like [`std::fill_n`](http://en.cppreference.com/w/cpp/algorithm/fill_n) (from `<algorithm>`):
```
std::fill_n(array, 100, -1);
```
In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable. | There is an extension to the gcc compiler which allows the syntax:
```
int array[100] = { [0 ... 99] = -1 };
```
This would set all of the elements to -1.
This is known as "Designated Initializers" see [here](http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html) for further information.
Note this isn't implemented for the gcc c++ compiler. | Initialization of all elements of an array to one default value in C++? | [
"",
"c++",
"arrays",
"initialization",
"variable-assignment",
"default-value",
""
] |
In c# how can I check in the file name has the "pound sign" and "apostrophe sign"
This is waht I tried so far but doesn't work.
I need to send an error if the # or ' are in the filename
return filename.Contains("#\'"); | You can use [IndexOfAny](http://msdn.microsoft.com/en-us/library/11w09h50.aspx):
```
if (filename.IndexOfAny(new char[] {'#', '\''}) > -1)
{
// filename contains # or '
}
``` | Try something like this:
```
Regex.IsMatch(fileName, @"[#']");
``` | filename.Contains #(pound) or ' (single quote) | [
"",
"c#",
"string",
"expression",
""
] |
I want to run a simple JavaScript function on a click without any redirection.
Is there any difference or benefit between putting the JavaScript call in the `href` attribute (like this):
```
<a href="javascript:my_function();window.print();">....</a>
```
vs. putting it in the `onclick` attribute (binding it to the `onclick` event)? | Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
```
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
``` | **bad:**
```
<a id="myLink" href="javascript:MyFunction();">link text</a>
```
**good:**
```
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
```
**better:**
```
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
```
**even better 1:**
```
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
```
**even better 2:**
```
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
```
Why better? because `return false` will prevent browser from following the link
**best:**
Use jQuery or other similar framework to attach onclick handler by element's ID.
```
$('#myLink').click(function(){ MyFunction(); return false; });
``` | JavaScript - href vs onclick for callback function on Hyperlink | [
"",
"javascript",
""
] |
How can I load a CSV file into a `System.Data.DataTable`, creating the datatable based on the CSV file?
Does the regular ADO.net functionality allow this? | Here's an excellent class that will copy CSV data into a datatable using the structure of the data to create the DataTable:
[A portable and efficient generic parser for flat files](https://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F)
It's easy to configure and easy to use. I urge you to take a look. | I have been using `OleDb` provider. However, it has problems if you are reading in rows that have numeric values but you want them treated as text. However, you can get around that issue by creating a `schema.ini` file. Here is my method I used:
```
// using System.Data;
// using System.Data.OleDb;
// using System.Globalization;
// using System.IO;
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = @"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
``` | How to read a CSV file into a .NET Datatable | [
"",
"c#",
".net",
"csv",
"datatable",
""
] |
PHP version 5.3 has been released, and although it looks great, all my code already works fine. I don't see what this new version offers to justify upgrading and working through possible issues after the upgrade.
Should I upgrade anyway just for good practice, or is an upgrade not needed unless I am actually using the new features? | You might consider upgrading just for the "Improved PHP runtime speed and memory usage" and bug fixes. [Source](http://php.net/ChangeLog-5.php). I would also say that if you are using [create\_function](https://www.php.net/manual/en/function.create-function.php) anywhere, you should upgrade and replace that ugly, nasty mess, with the much cleaner [lambda](http://us.php.net/manual/en/functions.anonymous.php). [Here](http://us.php.net/migration53) is the migration guide from 5.2. | I'd say there's a few big questions you need to answer to help make this decision. The biggest of which is, what does your site/product/customers do? If you're managing an application (like say a CMS or shopping cart) then you need to understand that many hosts will not be upgrading for a while because they wait for officially supported packages/RPMs for the OS they use, and they take time to build, test and release.
If this is just a custom site running on a dedicated server the same question can be some what important. While, in this case, you can always compile by hand that may not necessarily be the best idea if you're as anal about a clean, organized, server as I am. Like Jason mentioned, there are supposed to be significant speed improvements, and as WishCow said, if you use create\_function() you can now ditch them for cleaner code.
Also keep in mind any third party libraries/extensions (PECL, PEAR, Zend Framework, Drupal, Wordpress, or custom written) that you're using that may not work on 5.3 yet for any given reason.
A dry-run upgrade is always better if it's possible. I have a server sitting next to my desk at home that I can use to upgrade and turn on a profiler to see what the performance of my site(s) looks like and make sure everything works. If you can't do this then you have to be careful because there's a chance you'll have some down time if things don't go smoothly. | Should I upgrade to PHP 5.3? | [
"",
"php",
"php-5.3",
"porting",
""
] |
I am trying to build a pie chart from a dictionary. Before I display the pie chart, I want to tidy up the data. I'm removing any pie slices that would be less than 5% of the pie and putting them in a "Other" pie slice. However I'm getting a `Collection was modified; enumeration operation may not execute` exception at runtime.
I understand why you can not add or remove items from a dictionary while iterating over them. However I don't understand why you can't simply change a value for an existing key within the foreach loop.
Any suggestions re: fixing my code, would be appreciated.
```
Dictionary<string, int> colStates = new Dictionary<string,int>();
// ...
// Some code to populate colStates dictionary
// ...
int OtherCount = 0;
foreach(string key in colStates.Keys)
{
double Percent = colStates[key] / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
colStates.Add("Other", OtherCount);
``` | Setting a value in a dictionary updates its internal "version number" - which invalidates the iterator, and any iterator associated with the keys or values collection.
I do see your point, but at the same time it would be odd if the values collection could change mid-iteration - and for simplicity there's only one version number.
The normal way of fixing this sort of thing is to either copy the collection of keys beforehand and iterate over the copy, or iterate over the original collection but maintain a collection of changes which you'll apply after you've finished iterating.
For example:
**Copying keys first**
```
List<string> keys = new List<string>(colStates.Keys);
foreach(string key in keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
```
Or...
**Creating a list of modifications**
```
List<string> keysToNuke = new List<string>();
foreach(string key in colStates.Keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
keysToNuke.Add(key);
}
}
foreach (string key in keysToNuke)
{
colStates[key] = 0;
}
``` | Call the `ToList()` in the `foreach` loop. This way we dont need a temp variable copy. It depends on Linq which is available since .Net 3.5.
```
using System.Linq;
foreach(string key in colStates.Keys.ToList())
{
double Percent = colStates[key] / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
``` | Editing dictionary values in a foreach loop | [
"",
"c#",
".net",
".net-2.0",
""
] |
I have a Menu class that has a IQueryable property called WebPages. In the following statement I am returning Menu items based on a match but I need to include the Webpages property. Here is what I have at the moment.
```
var allCategories = Menu.All().Where(x => x.CategoryID == 4 && x.Visible)
```
I need to extend it to check a property in the WebPage class, something like this..
```
var allCategories = Menu.All().Where(x => x.CategoryID == 4 && x.Visible && x.WebPages.Roles.Contains(User.Identity.Name))
```
That won't compile but I hope you get the jist of what I am trying to do.
NOTE: The Webpage property is filled by the PageID not CategoryID but not sure if that makes a difference??
Here are a brief outline of my classes.
```
public partial class Menu: IActiveRecord
{
public int ID {get; set;}
public int CategoryID {get;set;}
public bool Visible {get;set;}
public int PageID {get;set;}
public IQueryable<WebPage> WebPages
{
get
{
var repo=NorthCadburyWebsite.Models.WebPage.GetRepo();
return from items in repo.GetAll()
where items.ID == _PageID
select items;
}
}
}
public partial class WebPage: IActiveRecord
{
public int ID {get;set;}
public string Roles {get;set;}
}
``` | This should do it for you mate. You just need to say WebPages.Any, this will return true if any menus contain a webpage with your specified role.
```
var allCategories = menus.Where(menu => menu.CategoryID == 1 && menu.Visible && menu.WebPages.Any(webPage => webPage.Roles.Contains(roleToSearchFor)));
```
So the key bit that you need to add is this.
```
menu.WebPages.Any(webPage => webPage.Roles.Contains(roleToSearchFor))
```
Using the **Any()** function is very efficient as it will stop looking as soon as it finds a match.
If you used **Where()** and then **Count()** it would iterate through all the Webpages to find all matches and then iterate through the results to count them, so that would be much less efficient.
Below is a full source example for you to try.
```
namespace DoctaJonez.TestingBrace
{
public partial class Menu //: IActiveRecord
{
public int ID { get; set; }
public int CategoryID { get; set; }
public bool Visible { get; set; }
public int PageID { get; set; }
public IQueryable<WebPage> WebPages { get; set; }
}
public partial class WebPage //: IActiveRecord
{ public int ID { get; set; } public string Roles { get; set; } }
public static class Launcher
{
/// <summary>
/// The Main entry point of the program.
/// </summary>
static void Main(string[] args)
{
Menu myMenu1 = new Menu
{
ID = 1,
CategoryID = 1,
PageID = 1,
Visible = true,
WebPages = new List<WebPage>()
{
new WebPage { ID = 1, Roles = "Role1" },
new WebPage { ID = 1, Roles = "Role2" },
new WebPage { ID = 1, Roles = "Role3" },
}.AsQueryable()
};
Menu myMenu2 = new Menu
{
ID = 1,
CategoryID = 1,
PageID = 1,
Visible = true,
WebPages = new List<WebPage>()
{
new WebPage { ID = 1, Roles = "Role3" },
new WebPage { ID = 1, Roles = "Role4" },
new WebPage { ID = 1, Roles = "Role5" },
}.AsQueryable()
};
Menu myMenu3 = new Menu
{
ID = 1,
CategoryID = 1,
PageID = 1,
Visible = true,
WebPages = new List<WebPage>()
{
new WebPage { ID = 1, Roles = "Role5" },
new WebPage { ID = 1, Roles = "Role6" },
new WebPage { ID = 1, Roles = "Role7" },
}.AsQueryable()
};
List<Menu> menus = new List<Menu>() { myMenu1, myMenu2, myMenu3 };
string roleToSearchFor = "Role3";
var allCategories = menus.Where(menu => menu.CategoryID == 1 && menu.Visible && menu.WebPages.Any(webPage => webPage.Roles.Contains(roleToSearchFor))).ToList();
return;
}
}
``` | If I understand the problem correctly, you want something like this:
```
var menuItems =
from menuItem in Menu.All()
where menuItem.Visible
and (
menuItem.WebPages.Contains(
webPage => webPage.Roles.Contains(
"role"
)
)
or menuItem.PageIsNull
)
select menuItem;
```
This should select only menu items joined to pages with the appropriate role. | LINQ IQueryable | [
"",
"c#",
"asp.net-mvc",
"linq",
"subsonic",
""
] |
Something like:
```
/**
* See {@linktourl http://google.com}
*/
``` | This creates a "See Also" heading containing the link, i.e.:
```
/**
* @see <a href="http://google.com">http://google.com</a>
*/
```
will render as:
> **See Also:**
> <http://google.com>
whereas this:
```
/**
* See <a href="http://google.com">http://google.com</a>
*/
```
will create an in-line link:
> See <http://google.com> | Taken from the [javadoc spec](http://java.sun.com/javase/6/docs/technotes/tools/windows/javadoc.html#@see)
`@see <a href="URL#value">label</a>` :
Adds a link as defined by `URL#value`. The `URL#value` is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (`<`) as the first character.
For example : `@see <a href="http://www.google.com">Google</a>` | Linking to an external URL in Javadoc? | [
"",
"java",
"url",
"javadoc",
"hyperlink",
""
] |
I am using VSTS 2008 + .Net 3.5 + C# to develop Windows Forms application. My confusion is, seems Application.Exit does not force application to terminate? If not, which method should I call to make application terminate?
EDIT 1:
Normally the main method is like this, how to exit Main function gracefully without calling Environment.Exit?
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
}
}
```
thanks in advance,
George | `Application.Exit` really just asks the message loop very gently.
If you want your app to exit, the best way is to gracefully make it out of `Main`, and cleanly close any additional non-background threads.
If you want to be brutal... [`Environment.Exit`](http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx) or [`Environment.FailFast`](http://msdn.microsoft.com/en-us/library/ms131100.aspx)? **note** this is harsh - about the same as killing your own `Process`. | Try the following:
```
Process.GetCurrentProcess().Kill();
```
`Environment.Exit` doesn't work with Winforms and `Environment.FailFast` throws its own exception. | Application.Exit | [
"",
"c#",
".net",
"winforms",
"visual-studio-2008",
"exit",
""
] |
We have the following code fragment:
```
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
```
And I don't understand why we don't get an error / warning in the call to `printf`. I DO get a warning but not an error, and the program runs fine. It prints '`12`'.
`printf` is expecting an argument of type `char *`, i.e. a pointer to `char`. So if I declared `char arr[3]`, then `arr` is an address of a memory unit which contains a `char`, so if I called `printf` with it, it would decay to *pointer to char*, i.e. `char *`.
Analogously, `tab` is an address of a memory unit that contains the type *array of 3 char's* which is in turn, an address of memory unit contains `char`, so `tab` will decay to `char **`, and it should be a problem, since `printf` is expecting a `char *`.
Can someone explain this issue?
# Addendum:
The warning I get is:
`a.c:6: warning: char format, different type arg (arg 2)` | **Example Source**
```
#include <stdio.h>
int main( void ) {
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab);
return 0;
}
```
**Compile Warning**
```
$ gcc test.c
test.c: In function ‘main’:
test.c:5: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[3]’
```
**Pointers are Pointers**
The `%s` argument to `printf` indicates to the function that it will be receiving a pointer (to a string). A string, in C, is merely a series of bytes terminated by an ASCII-Z. The `tab[2][3]` variable is a pointer. Some compilers will issue a warning about the pointer mismatch. However, the code should still print out `12` because `printf`'s code traverses memory starting at the pointer it was given (printing characters as it goes) until it finds a zero byte. The 1, 2, and \0 are contiguously set in memory, starting at the address represented by the `tab` variable.
**Experiment**
As an experiment, what happens when you compile and run the following code:
```
#include <stdio.h>
int main( void ) {
char tab[2][3] = {'1', '2', '\0', '3', '4', '\0'};
printf("%s\n", tab[1]);
return 0;
}
```
Don't be afraid of experimenting. See if you can come up with the answer based on what you now know. How would you reference `tab` now (in light of the experiment) to get rid of the warning and still display `12`? | The tab parameter matches the elipsis in the printf() call. C and C++ compilers are undfer no obligation to check such parameters. | A question about printf arguments. C/C++ | [
"",
"c++",
"c",
"pointers",
"matrix",
"printf",
""
] |
Discussing with people, asking in interviews, or being asked in interviews, I do not know if I know exactly when to write a function as inline or write it as a macro. Apart from compile-time and run-time consideration, is there any suggestion from coding standard point of view.
I think this is one of those question where it comes to the programmer's preference, or one may say bias towards the usage. I might be a good idea, if members can quote anecdotes, experiences or situations where they have chosen one over the other. | Macros should be used sparingly, in circumstances where a function will simply not do the job. An example, is error reporting. I use this macro for that purpose:
```
#define ATHROW( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \
} \
```
This has to be a macro in order to get the correct file & line number using the standard `__FILE__` and `__LINE__` macros , and also to provide the error formatting so I can say things like:
```
ATHROW( "Value " << x << " is out of range" );
``` | Inline is generally preferred, because the inline constants or functions are typed, so mistakes are caught earlier.
It is hard to write bulletproof macros, and they can become quite unreadable in the process. | In C/C++ can anybody provide some thumb rules for writing small function using inline or macro? | [
"",
"c++",
"c",
"coding-style",
""
] |
When I have to get GBs of data, save it on a collection and process it, I have memory overflows. So instead of:
```
public class Program
{
public IEnumerable<SomeClass> GetObjects()
{
var list = new List<SomeClass>();
while( // get implementation
list.Add(object);
}
return list;
}
public void ProcessObjects(IEnumerable<SomeClass> objects)
{
foreach(var object in objects)
// process implementation
}
void Main()
{
var objects = GetObjects();
ProcessObjects(objects);
}
}
```
I need to:
```
public class Program
{
void ProcessObject(SomeClass object)
{
// process implementation
}
public void GetAndProcessObjects()
{
var list = new List<SomeClass>();
while( // get implementation
Process(object);
}
return list;
}
void Main()
{
var objects = GetAndProcessObjects();
}
}
```
There is a better way? | You ought to leverage C#'s [*iterator blocks*](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) and use the `yield return` statement to do something like this:
```
public class Program
{
public IEnumerable<SomeClass> GetObjects()
{
while( // get implementation
yield return object;
}
}
public void ProcessObjects(IEnumerable<SomeClass> objects)
{
foreach(var object in objects)
// process implementation
}
void Main()
{
var objects = GetObjects();
ProcessObjects(objects);
}
}
```
This would allow you to stream each object and not keep the entire sequence in memory - you would only need to keep one object in memory at a time. | Don't use a List, which requires all the data to be present in memory at once. Use `IEnumerable<T>` and produce the data on demand, or better, use `IQueryable<T>` and have the entire execution of the query deferred until the data are required.
Alternatively, don't keep the data in memory at all, but rather save the data to a database for processing. When processing is complete, then query the database for the results. | Which is the best way to improve memory usage when you collect a large data set before processing it? (.NET) | [
"",
"c#",
".net",
""
] |
I've written a site CMS from scratch, and now that the site is slowly starting to get traffic (30-40k/day) Im seeing the server load a lot higher than it should be. It hovers around 6-9 all the time, on a quad core machine with 8gb of ram. I've written scripts that performed beautifully on 400-500k/day sites, so I'd like to think Im not totally incompetent.
I've reduce numbers of queries that are done on every page by nearly 60% by combining queries, eliminating some mysql calls completely, and replacing some sections of the site with static TXT files that are updated with php when necessary. All these changes affected the page execution time (index loads in 0.3s, instead of 1.7 as before).
There is virtually no IOwait, and the mysql DB is just 30mb. The site runs lighttpd, php 5.2.9, mysql 5.0.77
What can I do to get to the bottom of what exactly is causing the high load? I really wanna localize the problem, since "top" just tells me its mysql, which hovers between 50-95% CPU usage at all times. | The best thing you can do is to profile your application code. Find out which calls are consuming so much of your resources. Here are some options (the first three Google hits for "php profiler"):
* [Xdebug](http://www.xdebug.org/docs/profiler)
* [NuSphere PhpED](http://www.nusphere.com/products/php_profiler.htm)
* [DBG](http://www.php-debugger.com/dbg/)
You might have some SQL queries that are very slow, but if they are run infrequently, they probably aren't a major cause of your performance problems. It may be that you have SQL queries that are more speedy, but they are run so often that their net impact to performance is greater. Profiling the application will help identify these.
The most general-purpose advice for improving application performance with respect to database usage is to identify data that changes infrequently, and put that data in a cache for speedier retrieval. It's up to you to identify what data would benefit from this the most, since it's very dependent on your application usage patterns.
As far as technology for caching, [APC](http://php.net/apc) and [memcached](http://php.net/memcached) are options with good support in PHP.
You can also read through the MySQL [optimization chapter](http://dev.mysql.com/doc/refman/5.1/en/optimization.html) carefully to identify any improvements that are relevant to your application.
Other good resources are [MySQL Performance Blog](http://www.mysqlperformanceblog.com/), and the book "[High Performance MySQL](https://rads.stackoverflow.com/amzn/click/com/0596101716)." If you're serious about running a MySQL-based website, you should be consulting these resources frequently. | Use [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/explain.html) to help you optimize/troubleshoot your queries. It will show you how tables are referenced and how many rows are being read. It's very useful.
Also if you've made any modifications to your [MySQL configuration](http://books.google.com/books?id=btfeDZZdiC4C&lpg=PA72&ots=rOle9C2pHp&dq=mysql%20configuration&pg=PP1), you may want to revisit that. | Whats a good way about troubleshooting a script in terms of performance (php/mysql)? | [
"",
"php",
"mysql",
"optimization",
""
] |
**Question:**
Is is possible, with regex, to match a word that contains the same character in different positions?
**Condition:**
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.
**Examples:**
using lowercase 6char words I'd like to match words where the 3rd and the 4th chars are the same.
```
parrot <- match for double r
follia <- match for double l
carrot <- match for double r
mattia <- match for double t
rettoo <- match for double t
melone <- doesn't match
```
I can't use the quantifier [\d]{2} because it match any succession of two chars, and what if I say the 2nd and the 4th position instead of 3rd and 4th?
Is it possible to do what I want with regex? If yes, how can I do that?
**EDIT:**
Ask asked in the comments, I'm using python | You can use a backreference to do this:
```
(.)\1
```
This will match consecutive occurrences of any character.
---
**Edit** Here’s some Python example:
```
import re
regexp = re.compile(r"(.)\1")
data = ["parrot","follia","carrot","mattia","rettoo","melone"]
for str in data:
match = re.search(regexp, str)
if match:
print str, "<- match for double", match.group(1)
else:
print str, "<- doesn't match"
``` | You need to use back references for such cases. I am not sure which language you are using, I tried the following example in my VI editor to search for any alphabet repeating.
**Pattern Regex:** `\([a-z]\)\1`
If you see the example, [a-z] is the pattern you are searching for, and enclose that inside the paranthesis (the parantheses should be escaped in some languages). Once you have a paranthesis, it is a group and can be referred again anywhere in the regex by using \1. If there is more than one group, you can use \1, \2 etc. \1 will be replaced by whatever was matched in the first group.
Thanks
Arvind | It is possible to match a character repetition with regex? How? | [
"",
"python",
"regex",
""
] |
So! Basically I have a database with a load of blog posts, these are all sorted by a UNIX timestamp, and what I need is a way to make this code spit out headers when appropriate, so that it will output something like this:
# 2008
## November
Title 1 - Date Goes Here
Title 2 - Date Goes Here
## December
Title 3 - Date Goes Here
# 2009
## January
Title 4 - Date Goes Here
etcetera
Here's my code so far, it works until the comparison of the year, and I still need to come up with a good way of how to make it compare months in a sensible fashion, so that January indeed comes after December, and not some ludicrous 13th month.
[code]
```
<?php
if ($db = new PDO('sqlite:./db/blog.sqlite3')) {
$stmt = $db->prepare("SELECT * FROM news ORDER BY date DESC");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$current_year = date("Y", $row[1]);
$current_month = date("m", $row[1]);
if ($current_year > $last_year) {
echo "<h1>" . $current_year . "</h1>";
$last_year = $current_year;
}
echo "<tr>";
echo "<td align='left'><a href='view_post.php?post_id=". $row[1] ."'>" . $row['0'] . " - " . date("Y-m-d, H:i:s", $row[1]) . "</a></td>";
echo "</tr>";
}
}
} else {
die($sqliteerror);
}
?>
```
[/code] | With unix timestamps you could do something like (pseudo code obviously)
```
prev_month = null
prev_year = null
foreach results as r
new_month = date('F', r[timestamp]);
new_year = date('Y', r[timestamp]);
if(prev_month != new_month)
//display month
/if
if(prev_year != new_year)
//display year
/if
// display other info
prev_month = new_month
prev_year = new_year
/foreach
``` | I would be tempted to do this in two steps, separating the database fetching from the display/html logic, for example:
```
<?php
//snip
//make big array of archive
$archive = array();
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$year = date("Y", $row[1]);
$month = date("m", $row[1]);
if (!isset($archive[$year])) {
$archive[$year] = array();
}
if (!isset($archive[$year][$month])) {
$archive[$year][$month] = array();
}
$archive[$year][$month][] = $row;
}
//snip
//loop over array and display items
?>
<?php foreach ($achive as $year => $months): ?>
<h1><?php echo $year; ?></h1>
<?php foreach ($months as $month => $posts): ?>
<h2><?php echo $month; ?></h2>
<ul>
<?php foreach ($posts as $post): ?>
<li><?php echo $post[0]; ?> etc...</li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
<?php endforeach; ?>
```
You should get the years and the months in reverse order as per your SQL query. I haven't tested this, but it should be vaguely correct. | PHP Blog, need to make a good looking archives section | [
"",
"php",
"blogs",
"archive",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.