Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I usually, almost without thinking anymore, use forward declarations so that I won't have to include headers. Something along this example:
```
//-----------------------
// foo.h
//-----------------------
class foo
{
foo();
~foo();
};
//-----------------------
// bar.h
//-----------------------
class foo; // forward declaration
class bar
{
bar();
~bar();
foo* foo_pointer;
};
```
Some developers like to use this method to avoid problems with inclusion circles. I rather use it to minimize the overhead in extensive inclusion hierarchies, an important part of physical design (for larger projects in particular).
However, in some cases I really like to declare members as normal objects instead of pointers to benefit from the automatic construction/destruction mechanism. This leads to the problem that forward declarations can't be used anymore, since the compiler needs the class definition in such case, eg:
```
//-----------------------
// foo.h
//-----------------------
class foo
{
foo();
~foo();
};
//-----------------------
// bar.h
//-----------------------
class foo; // Not enough given the way we declare "foo_object"..
#include "foo.h" // ..instead this is required
class bar
{
bar();
~bar();
foo foo_object;
};
```
So, I would be happy if anyone knows an alternative language construct which can be used here so that I can declare "foo\_object" as shown in the example, but without including its header.
Regards
/Robert
|
Just use a smart pointer - you can even use auto\_ptr in this case.
```
//-----------------------
// bar.h
//-----------------------
#include <memory>
class foo; // Not enough given the way we declare "foo_object"..
class bar
{
public:
bar();
~bar();
foo &foo_object() { return *foo_ptr; }
const foo &foo_object() const { return *foo_ptr; }
private:
auto_ptr<foo> foo_ptr;
};
```
You get all the benefits of automatic memory management, without having to know anything about foo in bar.h. See [Wrapping Pointer Data Members](http://www.gotw.ca/publications/using_auto_ptr_effectively.htm) for Herb Sutter's recommendation.
If you really want default construction to happen automatically, try this:
```
#include <iostream>
using namespace std;
class Foo;
template <typename T>
class DefaultConstuctorPtr
{
T *ptr;
void operator =(const DefaultConstuctorPtr &);
DefaultConstuctorPtr(const DefaultConstuctorPtr &);
public:
DefaultConstuctorPtr() : ptr(new T()) {}
~DefaultConstuctorPtr() { delete ptr; }
T *operator *() { return ptr; }
const T *operator *() const { return ptr; }
};
class Bar
{
DefaultConstuctorPtr<Foo> foo_ptr;
public:
Bar() {} // The compiler should really need Foo() to be defined here?
};
class Foo
{
public:
Foo () { cout << "Constructing foo"; }
};
int main()
{
Bar bar;
}
```
|
You can't. The compiler needs to know the size of the object when declaring the class.
References are an alternative, although they have to be instantiated at construction time, so it's not always feasible.
Another alternative are smart pointers, but I suppose that's technically still a pointer.
It would be good to know why you don't want to use a pointer to suggest some other construct though...
|
Alternative to forward declarations when you don't want to #include
|
[
"",
"c++",
"physical-design",
"forward-declaration",
""
] |
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().
If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
|
You can use [**atexit**](http://docs.python.org/library/atexit.html) for this, and register any clean up tasks to be run when your program exits.
**atexit.register(func[, \*args[, \*\*kargs]])**
In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs.
```
>>> import atexit
>>> import sys
>>> import time
>>>
>>>
>>>
>>> def cleanup():
... timeout_sec = 5
... for p in all_processes: # list of your processes
... p_sec = 0
... for second in range(timeout_sec):
... if p.poll() == None:
... time.sleep(1)
... p_sec += 1
... if p_sec >= timeout_sec:
... p.kill() # supported from python 2.6
... print 'cleaned up!'
...
>>>
>>> atexit.register(cleanup)
>>>
>>> sys.exit()
cleaned up!
```
**Note** -- Registered functions won't be run if this process (parent process) is killed.
**The following windows method is no longer needed for python >= 2.6**
Here's a way to kill a process in windows. Your Popen object has a pid attribute, so you can just call it by **success = win\_kill(p.pid)** (Needs [pywin32](http://sourceforge.net/projects/pywin32/) installed):
```
def win_kill(pid):
'''kill a process by specified PID in windows'''
import win32api
import win32con
hProc = None
try:
hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid)
win32api.TerminateProcess(hProc, 0)
except Exception:
return False
finally:
if hProc != None:
hProc.Close()
return True
```
|
On \*nix's, maybe using process groups can help you out - you can catch subprocesses spawned by your subprocesses as well.
```
if __name__ == "__main__":
os.setpgrp() # create new process group, become its leader
try:
# some code
finally:
os.killpg(0, signal.SIGKILL) # kill all processes in my group
```
Another consideration is to escalate the signals: from SIGTERM (default signal for `kill`) to SIGKILL (a.k.a `kill -9`). Wait a short while between the signals to give the process a chance to exit cleanly before you `kill -9` it.
|
Ensuring subprocesses are dead on exiting Python program
|
[
"",
"python",
"subprocess",
"kill",
"zombie-process",
""
] |
I wrote a simple javascript image rotator which picks a random image on each page load. The issue is that if i use a default image, that default image will show up for a second before the javascript loads and replaces it. Obviously if someone has javascript disabled i want them to see an image. How can i have a default image without a flickering of the default image.
|
It sounds like you want to change the page HTML before window.onload fires (because at that point the default image has been displayed already).
You need to attach your javascript function to a "DOMContentLoaded" or commonly called domready event. Dean Edwards provided us a fantastic cross-browser implementation <http://dean.edwards.name/weblog/2006/06/again/>.
Hope that helps :)
|
If you hide the default image as the first thing you do when the page loads, there probably won't be a chance for the users to see the image. You can then install an onload handler on the image and change its source to your random image. When the image loads, you can unhide the image.
```
window.onload = function () {
var img = document.getElementById("rotating_image");
// Hide the default image that's shown to people with no JS
img.style.visibility = "hidden";
// We'll unhide it when our new image loads
img.onload = function () {
img.style.visibility = "visible";
};
// Load a random image
img.src = "http://example.com/random" + Math.floor(Math.random() * 5) + ".jpg";
};
```
|
javascript image rotator issue, default image
|
[
"",
"javascript",
"image",
""
] |
Is there a simple attribute or data contract that I can assign to a function parameter that prevents `null` from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal `null` isn't being used anywhere for it and at run-time throw `ArgumentNullException`.
Currently I write something like ...
```
if (null == arg)
throw new ArgumentNullException("arg");
```
... for every argument that I expect to not be `null`.
On the same note, is there an opposite to `Nullable<>` whereby the following would fail:
```
NonNullable<string> s = null; // throw some kind of exception
```
|
There's nothing available at compile-time, unfortunately.
I have a bit of a [hacky solution](https://web.archive.org/web/20081231232311/http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx) which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the [Code Contracts](http://research.microsoft.com/contracts/) stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "`if (null == arg)`" instead of "`if (arg == null)`"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.
|
I know I'm incredibly late to this question, but I feel the answer will become relevant as the latest major iteration of C# comes closer to release, then released. In C# 8.0 a major change will occur, C# will assume *all* types are considered not null.
According to Mads Torgersen:
> The problem is that null references are so useful. In C#, they are the
> default value of every reference type. What else would the default
> value be? What other value would a variable have, until you can decide
> what else to assign to it? What other value could we pave a freshly
> allocated array of references over with, until you get around to
> filling it in?
>
> Also, sometimes null is a sensible value in and of itself. Sometimes
> you want to represent the fact that, say, a field doesn’t have a
> value. That it’s ok to pass “nothing” for a parameter. The emphasis is
> on sometimes, though. And herein lies another part of the problem:
> Languages like C# don’t let you express whether a null right here is a
> good idea or not.
So the resolution outlined by Mads, is:
> 1. We believe that it is more common to want a reference not to be null. Nullable reference types
> would be the rarer kind (though we don’t have good data to tell us by
> how much), so they are the ones that should require a new annotation.
> 2. The language already has a notion of – and a syntax for – nullable value types. The analogy between the two would make the language
> addition conceptually easier, and linguistically simpler.
> 3. It seems right that you shouldn’t burden yourself or your consumer with cumbersome null values unless you’ve actively decided that you
> want them. Nulls, not the absence of them, should be the thing that
> you explicitly have to opt in to.
An example of the desired feature:
```
public class Person
{
public string Name { get; set; } // Not Null
public string? Address { get; set; } // May be Null
}
```
The preview is available for Visual Studio 2017, 15.5.4+ preview.
|
Mark parameters as NOT nullable in C#/.NET?
|
[
"",
"c#",
".net",
"parameters",
"null",
""
] |
**SpousesTable**
*SpouseID*
**SpousePreviousAddressesTable**
*PreviousAddressID*, *SpouseID*, FromDate, AddressTypeID
What I have now is updating the most recent for the whole table and assigning the most recent regardless of SpouseID the AddressTypeID = 1
I want to assign the most recent SpousePreviousAddress.AddressTypeID = 1
for each unique SpouseID in the SpousePreviousAddresses table.
```
UPDATE spa
SET spa.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa INNER JOIN Spouses ON spa.SpouseID = Spouses.SpouseID,
(SELECT TOP 1 SpousePreviousAddresses.* FROM SpousePreviousAddresses
INNER JOIN Spouses AS s ON SpousePreviousAddresses.SpouseID = s.SpouseID
WHERE SpousePreviousAddresses.CountryID = 181 ORDER BY SpousePreviousAddresses.FromDate DESC) as us
WHERE spa.PreviousAddressID = us.PreviousAddressID
```
I think I need a group by but my sql isn't all that hot. Thanks.
**Update that is Working**
I was wrong about having found a solution to this earlier. Below is the solution I am going with
```
WITH result AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) AS rowNumber, *
FROM SpousePreviousAddresses
WHERE CountryID = 181
)
UPDATE result
SET AddressTypeID = 1
FROM result WHERE rowNumber = 1
```
|
Presuming you are using SQLServer 2005 (based on the error message you got from the previous attempt) probably the most straightforward way to do this would be to use the ROW\_NUMBER() Function couple with a Common Table Expression, I think this might do what you are looking for:
```
WITH result AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,
*
FROM
SpousePreviousAddresses
)
UPDATE SpousePreviousAddresses
SET
AddressTypeID = 2
FROM
SpousePreviousAddresses spa
INNER JOIN result r ON spa.SpouseId = r.SpouseId
WHERE r.rowNumber = 1
AND spa.PreviousAddressID = r.PreviousAddressID
AND spa.CountryID = 181
```
In SQLServer2005 the ROW\_NUMBER() function is one of the most powerful around. It is very usefull in lots of situations. The time spent learning about it will be re-paid many times over.
The CTE is used to simplyfy the code abit, as it removes the need for a temporary table of some kind to store the itermediate result.
The resulting query should be fast and efficient. I know the select in the CTE uses \*, which is a bit of overkill as we dont need all the columns, but it may help to show what is happening if anyone want to see what is happening inside the query.
|
Here's one way to do it:
```
UPDATE spa1
SET spa1.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa1
LEFT OUTER JOIN SpousePreviousAddresses AS spa2
ON (spa1.SpouseID = spa2.SpouseID AND spa1.FromDate < spa2.FromDate)
WHERE spa1.CountryID = 181 AND spa2.SpouseID IS NULL;
```
In other words, update the row `spa1` for which no other row `spa2` exists with the same spouse and a greater (more recent) date.
There's exactly one row for each value of `SpouseID` that has the greatest date compared to all other rows (if any) with the same `SpouseID`.
There's no need to use a `GROUP BY`, because there's kind of an implicit grouping done by the join.
**update:** I think you misunderstand the purpose of the `OUTER JOIN`. If there is no row `spa2` that matches *all* the join conditions, then all columns of `spa2.*` are returned as NULL. That's how outer joins work. So you can search for the cases where `spa1` has no matching row `spa2` by testing that `spa2.SpouseID IS NULL`.
|
Sql Server Query Selecting Top and grouping by
|
[
"",
"sql",
"sql-server",
"database-partitioning",
""
] |
## Background
We are developing some in-house utilities using ASP.NET 2.0. One of which is extracting some information from databases and building an Excel workbook containing a number of spreadsheets with data based on queries into the database.
## Problem
The proof-of-concept prototype (a simple ASP.NET page that queries a single item from the database and opens Excel to add data to a worksheet) is working well when run locally on the development machines, happily creating and displaying an Excel spreadsheet as requested. However, when run on our server, we get the following error upon trying to instantiate Excel .
Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel.\_Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E\_NOINTERFACE)).
## Solution?
We are using the PIA for Excel 2003 and we have Excel 2003 and the PIA installed on the server. Can anyone explain why this isn't working or give us some tips on how we might track the problem down?
Thanks for any assistance you can provide.
|
Can the user that the ASP.NET Application Pool runs under have access to the application? Try logging in as that user (or change the Application Pool to run as that user) and opening Excel. If that works try running a WinForms application on the server as that user with the code that is failing.
Not sure but I think the PIA assemblies might need to be registered via regsvr32.
I suspect that if you run as Network Service, you will not be able to start Excel (no interactive login, restricted account, etc). Your ASP.NET code runs inside the application pool. You can change the user the application pool runs as through the IIS manager. If you want to check what your code is currently running as look for the w3wp process in Task Manager.
For testing, change the Application Pool to run as the user you know works with Excel.
|
Consider working with **XLSX files** (new in Office 2007, but there is a plugin for Office 2003), which are just ZIP files containing XML files which you can manipulate without the need for Excel. The (XML-based) SpreadsheetML is well documented and not too complicated to program against (you might even find a LINQ to SpreadsheetML somewhere on the web).
As was pointed out above, Excel is not really a server product and you might run into all kinds of issues when using it on a server.
|
Automating Excel using ASP.NET
|
[
"",
"c#",
"asp.net",
"excel",
"interop",
"pia",
""
] |
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
|
Here's an except from MVC RC1 release notes - Jan 2009
**IsMvcAjaxRequest Renamed to IsAjaxRequest**
> The IsMvcAjaxRequest method been
> renamed to IsAjaxRequest. As part of
> this change, the IsAjaxRequest method
> was updated to recognize the
> X-Requested-With HTTP header. This is
> a well known header sent by the major
> JavaScript libraries such as
> Prototype.js, jQuery, and Dojo.
>
> The ASP.NET AJAX helpers were updated to send this header in
> requests. However, they continue to
> also send it in the body of the form
> post in order to work around the issue
> of firewalls that strip unknown
> headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the [full release notes](http://go.microsoft.com/fwlink/?LinkID=137661&clcid=0x409) but has been using previous versions - even as recent as the beta - I **STRONGLY** recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
**Important note:** You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
|
**See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.**
The way the `IsMvcAjaxRequest` extension method currently works is that it checks `Request["__MVCASYNCPOST"] == "true"`, and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the `__MVCASYNCPOST` value into your request and then you could take advantage of the `IsMvcAjaxRequest` extension method.
Here is a [link to the source of the IsMvcAjaxRequest extension method](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266442&changeSetId=17272) for your convenience.
Alternatively, you could create a clone of the `IsMvcAjaxRequest` extension method called
`IsjQueryAjaxRequest` that checks `Request["__JQUERYASYNCPOST"] == "true"` and you could dynamically insert that value into the HTTP POST.
**Update**
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
```
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
```
Checking from an action if a method is a jQuery $.ajax() request:
```
if (Request.IsjQueryAjaxRequest())
//some code here
```
JavaScript
```
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
```
|
Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?
|
[
"",
"javascript",
"jquery",
"asp.net-mvc",
"ajax",
""
] |
Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields?
```
SYSTEMTIME sysTime;
GetLocalTime( &sysTime );
char buf[80];
for (int i = 0; i < 100000; i++)
{
sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d",
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
}
```
---
Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed `sprintf()` as the offender.
|
If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year.
edit: Note that to cope with leap seconds (and to match [`strftime()`](http://en.cppreference.com/w/c/chrono/strftime)) you should be able to print seconds values of 60 and 61.
```
char LeadingZeroIntegerValues[62][] = { "00", "01", "02", ... "59", "60", "61" };
```
Alternatively, how about [`strftime()`](http://en.cppreference.com/w/c/chrono/strftime)? I've no idea how the performance compares (it could well just be calling sprintf()), but it's worth looking at (and it could be doing the above lookup itself).
|
You could try filling each char in the output in turn.
```
buf[0] = (sysTime.wYear / 1000) % 10 + '0' ;
buf[1] = (sysTime.wYear / 100) % 10 + '0';
buf[2] = (sysTime.wYear / 10) % 10 + '0';
buf[3] = sysTime.wYear % 10 + '0';
buf[4] = '-';
```
... etc...
Not pretty, but you get the picture. If nothing else, it may help explain why sprintf isn't going to be that fast.
OTOH, maybe you could cache the last result. That way you'd only need to generate one every second.
|
How can I improve/replace sprintf, which I've measured to be a performance hotspot?
|
[
"",
"c++",
"c",
"performance",
"printf",
"strftime",
""
] |
I need to determine the number of pages in a specified PDF file using C# code (.NET 2.0). The PDF file will be read from the file system, and not from an URL. Does anyone have any idea on how this could be done? Note: Adobe Acrobat Reader is installed on the PC where this check will be carried out.
|
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.
**iTextSharp Example**
You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
class Program
{
static void Main(string[] args)
{
// Right side of equation is location of YOUR pdf file
string ppath = "C:\\aworking\\Hawkins.pdf";
PdfReader pdfReader = new PdfReader(ppath);
int numberOfPages = pdfReader.NumberOfPages;
Console.WriteLine(numberOfPages);
Console.ReadLine();
}
}
}
```
|
This should do the trick:
```
public int getNumberOfPdfPages(string fileName)
{
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
Regex regex = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
```
From [Rachael's answer](https://stackoverflow.com/questions/320281/determine-number-of-pages-in-a-pdf-file-using-c-net-2-0/595458#595458) and [this one](http://www.devasp.net/net/articles/display/726.html) too.
|
Determine number of pages in a PDF file
|
[
"",
"c#",
"pdf",
".net-2.0",
""
] |
Inside my code I'm generating hashes of URLs, (which are practically of unbounded length). I'm currently using sha1(), which I know has a tiny chance of a collision, but I have up to 255 bytes to store the hash in so feel that I might as well use that available space to lower the chance of collision even further.
Is there either:
1. Another PHP hash function with a longer or customisable hash length?
2. A way of using a fixed-length hash function like sha1 with a variable length input to generate a longer hash?
Or, is sha1's 20-byte hash good enough for anything and I should stop worrying about it?
|
> Or, is sha1's 20-byte has good enough for anything and I should stop worrying about it?
Exactly.
Hashtables, Pigeonholes, and Birthdays
<http://www.codinghorror.com/blog/archives/001014.html>
|
Let see... <http://www.cryptography.com/cnews/hash.html>
> Q: How hard would it be to find
> collisions in SHA-1?
> A: The reported
> attacks require an estimated work
> factor of 2^69 (approximately 590
> billion billion) hash computations
Looks like the risk is quite low... ^\_^
|
A PHP hash function with a long output length?
|
[
"",
"php",
"hash",
""
] |
I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import.
I'm really against this idea and feel that utilising available technology such as [Remoting](http://en.wikipedia.org/wiki/.NET_Remoting), [WCF](http://en.wikipedia.org/wiki/Windows_Communication_Foundation), etc. would be far better than polling.
However, I'd like to identify the reasons why other people prefer one approach over the other and more importantly, how can I convince others that polling is wrong in this day and age?
|
Polling is not "wrong" as such.
A lot depends on how it is implemented and for what purpose. If you really care about immedatly notification of a change, it is very efficient. Your code sits in tight loop, constantly polling (asking) a resource whether it has changed / updated. This means you are notified as soon as you can be that something is different. But, your code is not doing anything else and there is overhead in terms of many many calls to the object in question.
If you are less concerned with immediate notification you can increase the interval between polls, and this can also work well, but picking the correct interval can be difficult. Too long and you might miss critical changes, too short and you are back to the problems of the first method.
Alternatives, such as interrupts or messages, etc. can provide a better compromise in these situations. You are notified of a change as soon as is practically possible, but this delay is not something you control, it depends on the component tself being timely about passing on changes in state.
What is "wrong" with polling?
* It can be resource hogging.
* It can be limiting (especially if you have many things you want to know about / poll).
* It can be overkill.
But...
* It is not inherently wrong.
* It can be very effective.
* It is very simple.
|
Examples of things that use polling in this day and age:
* Email clients poll for new messages (even with IMAP).
* RSS readers poll for changes to feeds.
* Search engines poll for changes to the pages they index.
* StackOverflow users poll for new questions, by hitting 'refresh' ;-)
* Bittorrent clients poll the tracker (and each other, I think, with DHT) for changes in the swarm.
* Spinlocks on multi-core systems can be the most efficient synchronisation between cores, in cases where the delay is too short for there to be time to schedule another thread on this core, before the other core does whatever we're waiting for.
Sometimes there simply isn't any way to get asynchronous notifications: for example to replace RSS with a push system, the server would have to know about everyone who reads the feed and have a way of contacting them. This is a mailing list - precisely one of the things RSS was designed to avoid. Hence the fact that most of my examples are network apps, where this is most likely to be an issue.
Other times, polling is cheap enough to work even where there is async notification.
For a local file, notification of changes is likely to be the better option in principle. For example, you might (might) prevent the disk spinning down if you're forever poking it, although then again the OS might cache. And if you're polling every second on a file which only changes once an hour, you might be needlessly occupying 0.001% (or whatever) of your machine's processing power. This sounds tiny, but what happens when there are 100,000 files you need to poll?
In practice, though, the overhead is likely to be negligible whichever you do, making it hard to get excited about changing code that currently works. Best thing is to watch out for specific problems that polling causes on the system you want to change - if you find any then raise those rather than trying to make a general argument against all polling. If you don't find any, then you can't fix what isn't broken...
|
What is wrong with polling?
|
[
"",
"c#",
".net",
"asp.net",
"polling",
""
] |
What is the C# equivalent of Delphi's `FillChar`?
|
If I understand FillChar correctly, it sets all elements of an array to the same value, yes?
In which case, unless the value is 0, you probably have to loop:
```
for(int i = 0 ; i < arr.Length ; i++) {
arr[i] = value;
}
```
For setting the values to the type's 0, there is `Array.Clear`
Obviously, with the loop answer you can stick this code in a utility method if you need... for example, as an extension method:
```
public static void FillChar<T>(this T[] arr, T value) {...}
```
Then you can use:
```
int[] data = {1,2,3,4,5};
//...
data.FillChar(7);
```
If you *absolutely* must have block operations, then `Buffer.BlockCopy` can be used to blit data between array locatiosn - for example, you could write the first chunk, then blit it a few times to fill the bulk of the array.
|
I'm assuming you want to fill a byte array with zeros (as that's what FillChar is mostly used for in Delphi).
.NET is guaranteed to initialize all the values in a byte array to zero on creation, so generally FillChar in .NET isn't necessary.
So saying:
```
byte[] buffer = new byte[1024];
```
will create a buffer of 1024 zero bytes.
If you need to zero the bytes after the buffer has been used, you could consider just discarding your byte array and declaring a new one (that's if you don't mind having the GC work a bit harder cleaning up after you).
|
What is a equivalent of Delphi FillChar in C#?
|
[
"",
"c#",
"delphi",
""
] |
I'd like to have some of the ScriptManager features in the new Asp.net MVC model:
1- Script combining
2- Resolving different paths for external Javascript files
3- Minify and Gzip Compression
[Here](http://www.codeproject.com/KB/aspnet/HttpCombine.aspx) is what I found, but I'm not sure is the best way for MVC approach. In general what is a good approach to deal with Javascript code in the MVC model?
|
Maybe you could just create a new 'Scripts' controller with different actions serving different combinations of compressed JS files. Since MVC is designed with a resource oriented approach, i.e. URLs are now at the center of your programming model, why not define simple URIs for your Javascripts too ?
In your views, for example you could reference your files like this :
```
<script src="http://your_domain/scripts/all"/>
```
This would call your 'all' action, resulting in all your compressed script files being sent.
Of course you would need to code the combining and compressing for now, or maybe reuse the Scriptmanager internally, I don't know if it's possible.
This is just an idea though, currently I'm referencing individual javascript files directly in my master pages.
|
Try this:
<http://www.codeplex.com/MvcScriptManager>
> MvcScriptManager is aimed to port certain key features available in AjaxControlToolkit's ToolkitScriptManager into the current ASP.NET MVC Framework. You will be able to use it as a control in your ASP.NET MVC application.
>
> ### Features
>
> 1. Script combination (or concatenation). Scripts declared with MvcScriptManager will be combined on the fly into a single script file request when the page is rendered.
> 2. Script minification (or crunching) in release mode. Minification process is done only once at the first request that references the specific script. Subsequent requests will use the crunched script content in cache (see #5 for detail). Crunching can be enabled/disabled for each script.
> 3. Render localized resources for stand-alone script files. Localized strings will be appended to the script if specified.
> 4. Support configurable HTTP compression and expiration setting when outputing scripts.
> 5. Script caching with file dependency. Script file content is cached so that rendering combined script file will be much more performant. Cache dependency is linked to the physical file therefore any script update in the file system will be reflected in the cache instantly.
> 6. Support rendering scripts in debug/release mode based on the running environment.
> 7. Resolving different paths for stand-alone script files.
> 8. Support multiple MvcScriptManagers on a single page (or master page). Support both Master and Slave rendering mode so that scripts declared with one ScriptManager can be rolled over to another one for rendering.
> 9. Support web farm scenario...
|
Scriptmanager Asp.Net Mvc
|
[
"",
"javascript",
"jquery",
"asp.net-mvc",
"performance",
"gzip",
""
] |
I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....
```
@Entity
@Table(name="widget")
public class Widget {
private Integer id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
```
The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.
However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --
```
@Entity
@Table(name="widget")
public class Widget {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
```
I've seen examples of both ways. However, when I run this second example I get the following...
```
java.lang.NullPointerException
at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25)
at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1)
at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source)
at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source)
at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source)
at java.lang.ThreadLocal.get(Unknown Source)
at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33)
at com.widget.db.dao.AbstractDao.(AbstractDao.java:12)
at com.widget.db.dao.WidgetDao.(WidgetDao.java:9)
at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
...
```
Here's the skeleton of `HibernateSessionFactory` (line 25 is marked) ....
```
protected Session initialValue() {
SessionFactory sessionFactory = null;
try {
Configuration cfg = new AnnotationConfiguration().configure();
String url = System.getProperty("jdbc.url");
if (url != null) {
cfg.setProperty("hibernate.connection.url", url);
}
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
}
Session session = sessionFactory.openSession(); // LINE 25
return session;
}
```
Anyone have an idea what's going on here?
|
From a performance and design perspective, using annotations on getters is a better idea than member variables, because the getter setters are called using reflection if placed on the field, than a method. Also if you plan to use validation and other features of hibernate, you'll have all the annotations at one place, rather than scattering them all over the place.
My recommendation go with methods not member variables.
From the documentation
> Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.
|
You got me on the right track toolkit. Thanks. Here's the deal... Of course, my contrived example didn't include the whole story. My Widget class was actually much larger than the example I gave. I have several extra fields/getters and I was ***MIXING*** my annotations. So I was annotating the @Id on the field but others were being annotated on the getter.
So the moral of the story is that you cannot mix annotation locations. Either all annotations are on the fields or they are on the getter methods. Long time Java and Hibernate, new to Annotations. Learn something every day.
Once I knew what to Google for I came across this which was helpful - <http://chstath.blogspot.com/2007/05/field-access-vs-property-access-in-jpa.html>
Of course, this now brings up the question as to which is better from design and performance perspectives.
|
Hibernate Annotation Placement Question
|
[
"",
"java",
"hibernate",
"annotations",
""
] |
I currently don't know any thing about web services, except that they are used to allow an application to share its functions.
* Where & how to start?
* Does any book on web services work with me if I use PHP as my programming language?
* Does anyone know any IRC channel for help?
* Does anyone know of a directory for tutorials for a beginner?
* Is it complicated?
* Does it take a long time to learn?
|
I've used two good books in the past that focus on web services and PHP. [Professional Web APIs with PHP](https://rads.stackoverflow.com/amzn/click/com/0764589547) is good if you want to quickly get started *using* 3rd party APIs (like Amazon, Google, eBay, etc.). It has tons of example PHP code to get you started. [Pro PHP XML and Web Services](https://rads.stackoverflow.com/amzn/click/com/1590596331) is what you want if you're interested in *implementing* web services of your own using PHP.
|
Web services are not hard to learn. If you already have PHP experience then you know most of what you need to do a web service. This [article](http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html) might start you off creating your first web service in php.
|
Can anyone show me a good source to learn web services?
|
[
"",
"php",
"web-services",
""
] |
I've written some C# code that checks whether a device is present on any SerialPort by issuing a command on the port and listening for a reply. When I just set the port speed, open the port, get the serial stream and start processing, it works 100% of the time. However, some of our devices work at different speeds and I am trying to probe for a device at various speeds to autonegotiate a connection as well as detect device presence.
When I do all this in a single thread there are no problems. However, 3s timeout at ten speeds is 30s per serial port, and there may be several. Hence the desire to probe all ports concurrently.
Sometimes this works. Sometimes Vista bluescreens. When I use threads to probe all the ports simultaneously it nearly always bluescreens. When I force everything to run in one thread it never happens.
A USB-serial Prolific PL-2303 adaptor is in use with x64 drivers.
---
@Vinko - thanks for the tip on reading minidumps.
As near as I can tell, the crux of the problem is that by starting a new asynchronous I/O operation *from a different thread* it is possible to give a whole new meaning to overlapped I/O, inducing a race condition inside the driver. Since the driver executes in kernel mode, **BLAM!**
# Epilogue
Except for kicking off, don't use BeginXxx outside of the callback handler and don't call BeginXxx until you've called EndXxx, because you'll induce a race condition in driver code that runs in kernel mode.
# Postscript
I have found that this also applies to socket streams.
|
Having written Windows drivers for one of these sort of device once, my advice would be not to waste your time with WinDbg trying to prove what you already know - i.e. that the driver you're using is buggy.
If you can find a more up-to-date driver from the PL2302, then try that, but my recommendation is that if you have to use USB->Serial adaptors, the FTDI-based ones are the best. (They're *not* the one I wrote the drivers for, either...)
|
You can also disable "Automatic Restart" under System Properties\Advanced\Start and Recovery\Settings. Once you disable that, you can see the BSOD and look for the error message, e.g. IRQL\_LESS\_OR\_EQUAL, by searching for that error name, you can usually narrow down to the source of the problem.
Btw, not many notebook comes with serial ports nowadays, so you must be using USB-Serial converter? If that's the case, the driver might have been an issue to start with, since most manufacturer wrote the serial port driver as virtual driver.
|
SerialPort and the BSOD
|
[
"",
"c#",
"concurrency",
"serial-port",
"bsod",
""
] |
Does anyone have a recommendation about web service security architecture in Java (preferably under JBoss)? Any recommended reading?
I want to expose a fairly rich web service to the world but the data are sensitive and it requires authentication from the current client (Flex), accessed via RPC. I definitely do not want any server-side session state.
What's the best way to go about implementing security through web services in Java/JBoss and where can I read about it?
|
For web services security in JBoss, I would start by reading [8.4 WS-Security](http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide#WS-Security) of the [JBossWS User Guide](http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide).
|
You could try:
[](http://www.manning.com/kanneganti/)
|
How to go about web service security in Java
|
[
"",
"java",
"web-services",
"security",
"jboss",
""
] |
In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.
If this code:
```
Console.WriteLine(someString);
```
produces:
```
Hello
World!
```
I want this code:
```
Console.WriteLine(ToLiteral(someString));
```
to produce:
```
\tHello\r\n\tWorld!\r\n
```
|
There's a method for this in [Roslyn](https://en.wikipedia.org/wiki/.NET_Compiler_Platform)'s [Microsoft.CodeAnalysis.CSharp](https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/) package on NuGet:
```
private static string ToLiteral(string valueTextForCompiler)
{
return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}
```
Obviously, this didn't exist at the time of the original question, but it might help people who end up here from Google Search.
|
A long time ago, I found this:
```
private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
}
}
```
This code:
```
var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));
```
Produces:
```
Hello
World!
"\tHello\r\n\tWorld!"
```
These days, [Graham](https://stackoverflow.com/users/1128762/graham) discovered you can use Roslyn's Microsoft.CodeAnalysis.CSharp package on NuGet:
```
private static string ToLiteral(string valueTextForCompiler)
{
return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}
```
|
Can I convert a C# string value to an escaped string literal?
|
[
"",
"c#",
"string",
"escaping",
""
] |
I need to pull some BLOB data from a SQL Server 2005 database and generate a SQL script to insert this same data in another database, in another server.
I am only allowed to do this using SQL scripts, I can't use any other utility or write a program in Java or .NET to do it.
The other big restriction I have is that I don't have access to the original database (where the original BLOB data is) when I run the script, to copy the BLOB data to the target database, so the data should already be encoded within the SQL script file.
Summing up: is there a way to encode the BLOB data into text so that I can dump it into a SQL INSERT command within a script text file and run it?
I am able to run special T-SQL statements and stored procedures if needed to.
|
TEXTCOPY was a sample application included in SQL Server 7.0 and 2000 but no longer available in SQL Server 2005.
However, googling for TEXTCOPY in SQL Server 2005, I found this alternative that might do the trick:
<http://sequelserver.blogspot.com/2007/01/texcopy-sql-server-2005.html>
It relies on writing and reading the binary data from the filesystem, which in my case is not ideal (ideally I would like to encode the binary data with the SQL script text file itself), but it's the best I've found so far.
Here's another good source on how to do binary import/export operations using BULK OPENROWSET:
<http://msdn.microsoft.com/en-us/library/ms191184.aspx>
|
This article "[Copy Text or Image into or out of SQL Server](http://www.databasejournal.com/features/mssql/article.php/1443521/Copy-Text-or-Image-into-or-out-of-SQL-Server.htm)" could help:
You could integrate the TEXTCOPY command line tool in a stored procedure:
```
CREATE PROCEDURE sp_textcopy (
@srvname varchar (30),
@login varchar (30),
@password varchar (30),
@dbname varchar (30),
@tbname varchar (30),
@colname varchar (30),
@filename varchar (30),
@whereclause varchar (40),
@direction char(1))
AS
DECLARE @exec_str varchar (255)
SELECT @exec_str =
'textcopy /S ' + @srvname +
' /U ' + @login +
' /P ' + @password +
' /D ' + @dbname +
' /T ' + @tbname +
' /C ' + @colname +
' /W "' + @whereclause +
'" /F ' + @filename +
' /' + @direction
EXEC master..xp_cmdshell @exec_str
```
You'll have to change/extend it a little in order to read the created file into the other database.
As [Vinko](https://stackoverflow.com/users/5190/vinko-vrsalovic) writes in the comment to this answer, hold in mind that this requires enabling xp\_cmdshell in the surface area configuration.
**Description of TEXTCOPY:**
*Copies a single text or image value into or out of SQL Server. The value
is a specified text or image 'column' of a single row (specified by the
"where clause") of the specified 'table'.*
*If the direction is IN (/I) then the data from the specified 'file' is
copied into SQL Server, replacing the existing text or image value. If the
direction is OUT (/O) then the text or image value is copied from
SQL Server into the specified 'file', replacing any existing file.*
|
Copying BLOB values between databases with pure SQL in SQL Server
|
[
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"blob",
""
] |
I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form.
For example, a button in the HTML might call the Close() method on the form.
Target platform: C# and Windows Forms (any version)
|
Look at the [WebBrowser.ObjectForScripting](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx) property. Managed to get Google Maps talking to a windows forms application using this.
|
I've implemeted this in a few applications in the past, here's how: (NB: the example below is not production ready and should be used as a guide only).
First create a normal .NET class (public) that contains public methods that you wish to call from Javasvcipt running in your web browser control.
Most importantly it must be decorated with the ComVisible(true)] attribute from the System.Runtime.InteropServices namespace (Javascript in IE is COM based). It can be called anything, I've called it "External" to make things clearer.
```
using System.Runtime.InteropServices;
[ComVisible(true)]
public class External
{
private static MainWindow m_mainWindow = null;
public External(MainWindow mainWindow)
{
m_mainWindow = mainWindow;
}
public void CloseApplication()
{
m_mainWindow.Close();
}
public string CurrentDate(string format)
{
return DateTime.Now.ToString(format);
}
}
```
Next in the .NET form containing your web browser control create an instance of the COMVisible class, then set the web browser controls ObjectForScripting to that instance:
```
private void MainWindow_Load(object sender, EventArgs e)
{
m_external = new External(this);
browserControl.ObjectForScripting = m_external;
}
```
Finally, in your Javascript running in the web browser control, you access the .NET methods via the window.external object. In this case window.external actually references (indirectly via a COM interop wrapper) the "External" object created above:
```
// Javascript code
function CloseButton_Click()
{
if (window.external)
{
window.external.CloseApplication();
}
}
```
Be aware that calls from Javascript to .NET pass through the COM interop layer and so querying of the default interface, marshalling of parameters etc must occur. In other words it can be relatively SLOW, so do some performance testing if you plan to make multiple calls for example from within a loop.
Also, just for future reference, calling Javascript code from .NET is simpler, just use the Document.InvokeScript method:
```
browserControl.Document.InvokeScript("jScriptFunction", new object[] { "param1", 2, "param2" });
```
|
WinForms - How do I execute C# application code from inside WebBrowser control?
|
[
"",
"c#",
"winforms",
"webbrowser-control",
""
] |
I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.
```
def analyser(testFunc):
print testFunc.__name__, 'belongs to the class, ...
```
I thought
```
testFunc.__class__
```
would solve my problems, but that just tells me that testFunc is a function.
|
```
testFunc.im_class
```
<https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy>
> `im_class` is the class of `im_self` for
> bound methods or the class that asked
> for the method for unbound methods
|
From python 3.3, `.im_class` is gone. You can use `.__qualname__` instead. Here is the corresponding PEP: <https://www.python.org/dev/peps/pep-3155/>
```
class C:
def f(): pass
class D:
def g(): pass
print(C.__qualname__) # 'C'
print(C.f.__qualname__) # 'C.f'
print(C.D.__qualname__) #'C.D'
print(C.D.g.__qualname__) #'C.D.g'
```
With nested functions:
```
def f():
def g():
pass
return g
f.__qualname__ # 'f'
f().__qualname__ # 'f.<locals>.g'
```
|
In Python, how can you get the name of a member function's class?
|
[
"",
"python",
"reflection",
"metaprogramming",
""
] |
I am wondering if it is possible to have a sort of thumbnail image gallery, in which clicking on a thumbnail would show the full image in a layer. I was wondering if it was possible to load all layers and respective images and use javascript to change the z index or something similar to avoid having to reload or leave the page. I would prefer to avoid using a server side technology but don't know if this is possible.
edit:
I am not after a "lightbox" solution or anything that overlays the page, I rather want an image to appear as part of the page, and change without reloading the page, basically like PIctureSlide linked below. But more importanlt, I am wondering if this would be easy to write without using a framework, and if it would work as I thought above?
|
Yes, you can do it without a framework:
```
<div id='big' style='width:500px;height:500px'></div>
<a href="javascript://load big image" onclick="document.getElementById('big').style.backgroundImage='url(Big.gif)'"><img border="0" src="images/Thumb.gif" /></a>
```
Here is a simple example using the [Prototype](http://www.prototypejs.org) library:
```
<div id='big' style='width:500px;height:500px'></div>
<a href="javascript://load big image" onclick="$('big').style.backgroundImage='url(Big1.gif)'"><img border="0" src="thumb1.gif" /></a>
```
This script assumes that the big images are all 500 x 500 pixels.
Here's an alternate way to do it:
```
<div id='big'></div>
<a href="javascript://load big image" onclick="loadBig('Big1.gif')"><img border="0" src="thumb1.gif" /></a>
<script type="text/javascript">
function loadBig() {
$('big').innerHTML = "<img src='Big1.gif'>"
}
</script>
```
|
There are plenty of thumbnail image gallerys around to bother writing one yourself unless you have a specific need. such as
<http://www.huddletogether.com/projects/lightbox/>
|
manipulating css layers with javascript
|
[
"",
"javascript",
"html",
"css",
""
] |
While looking at a micro-optimization question that I asked yesterday ([here](https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer)), I found something strange: an `or` statement in Java is running *slightly* faster than looking up a boolean value in an array of booleans.
In my tests, running the below algorithms on `long` values from 0 to 1 billion, alg1 is about 2% faster. (I have altered the order in which the algorithms are tested, and I get the same results). My question is: **Why is alg1 faster?** I would have expected alg2 to be slightly faster since it uses a lookup table, whereas alg1 has to execute 4 comparisons and 3 or operations for 75% of inputs.
```
private final static boolean alg1(long n)
{
int h = (int)(n & 0xF);
if(h == 0 || h == 1 || h == 4 || h == 9)
{
long tst = (long)Math.sqrt(n);
return tst*tst == n;
}
return false;
}
private final static boolean[] lookup = new boolean[16];
static
{
lookup[0] = lookup[1] = lookup[4] = lookup[9] = true;
}
private final static boolean alg2(long n)
{
if(lookup[(int)(n & 0xF)])
{
long tst = (long)Math.sqrt(n);
return tst*tst == n;
}
else
return false;
}
```
*If you're curious, this code is testing if a number is a perfect square, and utilizes the fact that perfect squares must end in 0, 1, 4, or 9 in hex.*
|
Loading some random piece of data is generally slower than a little non-branching code.
It all depends upon processor architecture, of course. Your first if statement could be implemented as four instructions. The second may potentially need null pointer checking, bounds checking as well as the load and compare. Also more code means more compile time, and more chance for the optimisation to be impeeded in some manner.
|
I would *guess* that the issues is that range checking for the array and if the array lookup is implemented as a method call. That would certainly overshadow 4 straight int compares. Have you looked at the byte code?
|
Why is this code with several "or" statements slightly faster than using a lookup table in Java?
|
[
"",
"java",
"optimization",
""
] |
I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp\_trace\_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!
|
Are you wanting this to be real-time, just like the Profiler itself? That'd be tough to do. You'd basically be re-creating the profiler.
If that is not a requirement, I would recommend simply calling the sp\_trace\_create stored procs that you found to start a server-side trace, then use your application to open up the files that this trace produces.
The EASIEST way to learn how this works is to run the SQL Profiler itself, set all the options you want, then click Run, and immediately click Stop. Then go to File, Export, Script Trace Definition, and choose the appropriate version.
This should give you a TSQL script that puts all the correct pieces together, including all the trace events, columns, etc.
More technical history of the profiler: [This old SQLMag article](http://www.microsoft.com/technet/prodtechnol/sql/70/tips/sqlprof.mspx) has some history of the Profiler, which replaced an app called "SQL Trace" when SQL 7.0 was introduced.
|
If you are still interested, found this code
```
public void FileToTable()
{
TraceServer reader = new TraceServer();
ConnectionInfoBase ci = new SqlConnectionInfo("localhost");
((SqlConnectionInfo)ci).UseIntegratedSecurity = true;
reader.InitializeAsReader(ci, @"Standard.tdf");
int eventNumber = 0;
while (reader.Read())
{
Console.Write( "{0}\n", reader.GetValue(0).ToString() );
}
reader.Close();
}
```
|
Imitating SQL Server Profiler in a C# app?
|
[
"",
"c#",
"sql-server",
"trace",
"smo",
"sql-server-profiler",
""
] |
I'm a .NET developer, and worked with VB6 before that. I've become very familiar with those environments, and working in the context of garbage collected languages. However, I now wish to bolster my skillset with native C++ and find myself a bit overwhelmed. Ironically, it's not what I'd imagine is the usual stumbling blocks for beginners as I feel that I've got the grasp of pointers and memory management fairly well. The thing that's a bit confusing for me is more along the lines of:
* Referencing/using other libraries
* Exposing *my* libraries for others to use
* String handling
* Data type conversions
* Good project structure
* Data structures to use (ie. in C#, I use `List<T>` a lot, what do I use in C++ that works simiarly?)
It almost feels like depending on the IDE you use, the guidelines are different, so I was really looking for something that's perhaps a bit more universal. Or at worst, focused on using Microsoft's compiler/IDE. Also, just to be clear, I'm not looking for anything about general programming practices (Design Patterns, Code Complete, etc.) as I feel I'm pretty well versed in those topics.
|
I know you say you've got a good grasp of pointers and memory management, but I'd still like to explain an important trick.
As a general rule of thumb, *never* have new/delete in your user code.
Every resource acquisition (whether it's a synchronization lock, a database connection or a chunk of memory or anything else that must be acquired and released) should be wrapped in an object so that the constructor performs the acquisition, and the destructor releases the resource. The technique is known as [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization), and is basically *the* way to avoid memory leaks. Get used to it.
The C++ standard library obviously uses this extensively, so you can get a feel for how it works there. Jumping a bit in your questions, the equivalent of `List<T>` is `std::vector<T>`, and it uses RAII to manage its memory. You'd use it something like this:
```
void foo() {
// declare a vector *without* using new. We want it allocated on the stack, not
// the heap. The vector can allocate data on the heap if and when it feels like
// it internally. We just don't need to see it in our user code
std::vector<int> v;
v.push_back(4);
v.push_back(42); // Add a few numbers to it
// And that is all. When we leave the scope of this function, the destructors
// of all local variables, in this case our vector, are called - regardless of
// *how* we leave the function. Even if an exception is thrown, v still goes
// out of scope, so its destructor is called, and it cleans up nicely. That's
// also why C++ doesn't have a finally clause for exception handling, but only
// try/catch. Anything that would otherwise go in the finally clause can be put
// in the destructor of a local object.
}
```
If I had to pick one single principle that a C++ programmer must learn and embrace, it's the above. Let the scoping rules and the destructors work for you. They offer all the guarantees you need to write safe code.
## String handling:
`std::string` is your friend there. In C, you'd use arrays of char's (or char pointers), but those are nasty, because they don't behave as strings. In C++, you have a std::string class, which behaves as you'd expect. The only thing to keep in mind is that "hello world" is of type char[12] and NOT std::string. (for C compatibility), so sometimes you have to explicitly convert your string literal (something enclosed in quotes, like "hello world") to a std::string to get the behavior you want:
You can still write
```
std::string s = "hello world";
```
because C-style strings (such as literals, like "hello world") are implicitly convertible to std::string, but it doesn't always work:
"hello" + " world" won't compile, because the + operator isn't defined for two pointers.
"hello worl" + 'd' however, *will* compile, but it won't do anything sensible.
Instead of appending a char to a string, it will take the integral value of the char (which gets promoted to an int), and add that to the value of the pointer.
std::string("hello worl") + "d" does as you'd expect however, because the left hand side is already a std::string, and the addition operator is overloaded for std::string to do as you'd expect, even when the right hand side is a char\* or a single character.
One final note on strings:
std::string uses char, which is a single-byte datatype. That is, it is not suitable for unicode text.
C++ provides the wide character type wchar\_t which is 2 or 4 bytes, depending on platform, and is typically used for unicode text (although in neither case does the C++ standard really specify the character set). And a string of wchar\_t's is called std::wstring.
## Libraries:
They don't exist, fundamentally.
The C++ language has no notion of libraries, and this takes some getting used to.
It allows you to #include another file (typically a header file with the extension .h or .hpp), but this is simply a verbatim copy/paste. The preprocessor simply combines the two files resulting in what is called a translation unit. Multiple source files will typically include the same headers, and that only works under certain specific circumstances, so this bit is key to understanding the C++ compilation model, which is notoriously quirky. Instead of compiling a bunch of separate modules, and exhanging some kind of metadata between them, as a C# compiler would, each translation unit is compiled in isolation, and the resulting object files are passed to a linker which then tries to merge the common bits back together (if multiple translation units included the same header, you essentially have code duplicated across translation units, so the linker merges them back into a single definition) ;)
Of course there are platform-specific ways to write libraries. On Windows, you can make .dll's or .libs, with the difference that a .lib is linked into your application, while a .dll is a separate file you have to bundle with your app, just like in .NET. On Linux, the equivalent filetypes are .so and .a, and in all cases, you have to supply the relevant header files as well, for people to be able to develop against your libraries.
## Data type conversions:
I'm not sure exactly what you're looking for there, but one point I feel is significant is that the "traditional" cast as in the following, is bad:
```
int i = (int)42.0f;
```
There are several reasons for this.
First, it attempts to perform several different types of casts in order, and you may be surprised by which one the compiler ends up applying. Second, it's hard to find in a search, and third, it's not ugly enough. Casts are generally best avoided, and in C++, they're made a bit ugly to remind you of this. ;)
```
// The most common cast, when the types are known at compile-time. That is, if
// inheritance isn't involved, this is generally the one to use
static_cast<U>(T);
// The equivalent for polymorphic types. Does the same as above, but performs a
// runtime typecheck to ensure that the cast is actually valid
dynamic_cast<U>(T);
// Is mainly used for converting pointer types. Basically, it says "don't perform
// an actual conversion of the data (like from 42.0f to 42), but simply take the
// same bit pattern and reinterpret it as if it had been something else). It is
// usually not portable, and in fact, guarantees less than I just said.
reinterpret_cast<U>(T);
// For adding or removing const-ness. You can't call a non-const member function
// of a const object, but with a const-cast you can remove the const-ness from
// the object. Generally a bad idea, but can be necessary.
const_cast<U>(T);
```
As you'll note, these casts are much more specific, which means the compiler can give you an error if the cast is invalid (unlike the traditional syntax, where it'd just try any of the above casts until it finds one that works), and it's big and verbose, allowing you to search for it, and reminds you that they should be avoided when possible. ;)
## The standard library:
Finally, getting back to data structures, put some effort into understanding the standard library. It is small, but amazingly versatile, and once you learn how to use it, you'll be in a far better position.
The standard library consists of several pretty distinct building blocks (the library has kind of accumulated over time. Parts of it were ported from C. The I/O streams library are adopted from one place, and the container classes and their associated functionality are adopted from a completely different library, and are designed noticeably different. The latter are part of what is often referred to as the STL (Standard Template Library). Strictly speaking, that is the name of the library that, slightly modified, got adopted into the C++ Standard Library.
The STL is key to understanding "modern C++". It is composed of three pillars, containers, iterators and algorithms.
In a nutshell, containers expose iterators, and algorithms work on iterator pairs.
The following example takes a vector of int's, adds 1 to each element, and copies it to a linked list, just for the sake of example:
```
int add1(int i) { return i+1; } // The function we wish to apply
void foo() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5); // Add the numbers 1-5 to the vector
std::list<int> l;
// Transform is an algorithm which applies some transformation to every element
// in an iterator range, and stores the output to a separate iterator
std::transform (
v.begin(),
v.end(), // Get an iterator range spanning the entire vector
// Create a special iterator which, when you move it forward, adds a new
// element to the container it points to. The output will be assigned to this
std::back_inserter(l)
add1); // And finally, the function we wish to apply to each element
}
```
The above style takes some getting used to, but it is extremely powerful and concise.
Because the transform function is templated, it can accept *any* types as input, as long as they behave as iterators. This means that the function can be used to combine any type of containers, or even streams or anything else that can be iterated through, as long as the iterator is designed to be compatible with the STL. We also don't have to use the begin/end pair. Instead of the end iterator, we could have passed one pointing to the third element, and the algorithm would then have stopped there. Or we could have written custom iterators which skipped every other elements, or whatever else we liked.
The above is a basic example of each of the three pillars. We use a container to store our data, but the algorithm we use to process it doesn't actually have to know about the container. It just has to know about the iterator range on which it has to work. And of course each of these three pillars can be extended by writing new classes, which will then work smoothly together with the rest of the STL.
In a sense, this is very similar to LINQ, so since you're coming from .NET, you can probably see some analogies. The STL counterpart is a bit more flexible though, at the cost of slightly weirder syntax. :)
(As mentioned in comments, it is also more efficient. In general, there is *zero* overhead to STL algorithms, they can be just as efficient as hand-coded loops. This is often surprising, but is possible because all relevant types are known at compile-time (which is a requirement for templates to work), and C++ compilers tend to inline aggressively.)
|
I'll not repeat what others have said about libraries and such, but if you're serious about C++, do yourself a favor and pick up Bjarne Stroustrup's "The C++ Programming Language."
It took me years of working in C++ to finally pick up a copy, and once I did, I spent an afternoon slapping my forehead saying "of course! I should have realized! etc."
(Ironically, I had EXACTLY the same experience with K&R's "The C Programming Language." Someday, I'll learn to just go get "The Book" on day 1.)
|
C++ for a C# developer
|
[
"",
"c++",
""
] |
I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection? For example:
```
public string[] Items
{
get;
set;
}
```
My method so far:
```
public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
T to = new T();
Type myType = from.GetType();
PropertyInfo[] myProperties = myType.GetProperties();
for (int i = 0; i < myProperties.Length; i++)
{
if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
{
myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
}
}
return to;
}
```
|
```
if (propertyInfo.GetIndexParameters().Length > 0)
{
// Property is an indexer
}
```
|
What you want is the `GetIndexParameters()` method. If the array that it returns has more than 0 items, that means it's an indexed property.
See [the MSDN documentation](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getindexparameters.aspx) for more details.
|
C# Reflection Indexed Properties
|
[
"",
"c#",
"reflection",
"clone",
""
] |
I'm using a repeater control and I'm trying to pass a parameter as such:
```
<%# SomeFunction( DataBinder.Eval(Container.DataItem, "Id") ) %>
```
It's basically calling:
```
public string SomeFunction(long id) {
return "Hello";
}
```
I'm not able to achieve this as I get an error:
error CS1502: The best overloaded method match ... SomeFunction(long id) ... has some invalid arguments.
Any ideas?
|
You need to cast the result to a long, so:
```
<%# SomeFunction( (long)DataBinder.Eval(Container.DataItem, "Id") ) %>
```
The alternative is to do something like this:
```
<%# SomeFunction(Container.DataItem) %>
```
and...
```
public string SomeFunction(object dataItem) {
var typedDataItem = (TYPED_DATA_ITEM_TYPE)dataItem;
// DO STUFF HERE WITH THE TYPED DATA ITEM
return "Hello";
}
```
This at least allows you to work with multiple values from the data item (DataRows etc).
|
I think you should cast the DataBinder.Eval(Container.DataItem, "Id") as long.
|
How do you pass a Container.DataItem as a parameter?
|
[
"",
"c#",
"asp.net",
""
] |
If I have a vector of pairs:
```
std::vector<std::pair<int, int> > vec;
```
Is there and easy way to sort the list in **increasing** order based on the second element of the pair?
I know I can write a little function object that will do the work, but is there a way to use existing parts of the *STL* and `std::less` to do the work directly?
EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:
```
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
```
|
**EDIT**: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type `auto`. **This is my current favorite solution**
```
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
```
---
**ORIGINAL ANSWER**:
Just use a custom comparator (it's an optional 3rd argument to `std::sort`)
```
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
```
If you're using a C++11 compiler, you can write the same using lambdas:
```
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
```
**EDIT**: in response to your edits to your question, here's some thoughts ...
if you **really** wanna be creative and be able to reuse this concept a lot, just make a template:
```
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
```
then you can do this too:
```
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
```
or even
```
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
```
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
|
You can use boost like this:
```
std::sort(a.begin(), a.end(),
boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2));
```
I don't know a standard way to do this equally short and concise, but you can grab `boost::bind` it's all consisting of headers.
|
How do I sort a vector of pairs based on the second element of the pair?
|
[
"",
"c++",
"stl",
"stdvector",
""
] |
In a C# application I am working on I have a very long identifier as follows:-
```
foo.bar.bwah.blah.whatever.very.very.huge
```
Whenever I to reference this object it's an absolute nightmare, and unfortunately I do need to reference it a lot:-
```
var something = foo.bar.bwah.blah.whatever.very.very.huge.a;
var somethingElse = foo.bar.bwah.blah.whatever.very.very.huge.b;
foo.bar.bwah.blah.whatever.very.very.huge.c = 12;
```
etc. etc.
I want to update this code using a far smaller alias of some kind, the problem is however that I want to change the underlying reference, and have the alias update also *without explicitly updating the alias*.
Currently if I do the following:-
```
foo.bar.bwah.blah.whatever.very.very.huge.a = "hello";
string shorter = foo.bar.bwah.blah.whatever.very.very.huge.a;
foo.bar.bwah.blah.whatever.very.very.huge.a = "world";
Console.WriteLine(shorter);
```
It will output "hello". What I want to achieve is something like the following:-
```
foo.bar.bwah.blah.whatever.very.very.huge.a = "hello";
string** shorterPointer = &foo.bar.bwah.blah.whatever.very.very.huge.a;
foo.bar.bwah.blah.whatever.very.very.huge.a = "world";
Console.WriteLine(**shorter);
```
Which would output "world" as required.
I believe you can achieve something like this using unsafe code in C#, however I *cannot* do that, I have to use safe code only.
Does anybody have any ideas how I might achieve this?
**Please Note:** This question is not about strings being immutable, I know they are - in fact I assumed they are for the purposes of the question. It might perhaps be simpler if I used some other type... so when I assign "hello" to a then "world" to a, I am *instantiating different objects* on each occasion, hence my stored reference to a becomes invalid after re-assignment.
|
One way out is to use one or a pair of lambdas.
For example:
```
Func<string> getter = () => blah_de_blah;
Action<string> setter = x => blah_de_blah = x;
```
Now, you can use getter and setter to read and write the long identifier.
However, since your dots are member accessors, the easiest way of going about it is to take a reference to the immediate parent, like so:
```
var myHuge = foo.bar.bwah.blah.whatever.very.very.huge;
// now access myHuge.a everywhere
```
This is good practice in any case, as a long dotted expression like this is a violation of the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter), which inhibits the flexibility of the codebase - it requires too much information in too many places.
|
I would use namespace alias.
```
using myAlias = foo.bar.bwah.blah.whatever.very.very
```
then inside your method you just had to type: `myAlias.huge.a = "hello";`
|
SAFE Pointer to a pointer (well reference to a reference) in C#
|
[
"",
"c#",
".net",
""
] |
I'm looking to setup video uploads for users on a site and want to have them viewed through a Flash player. The site is already partially built (by someone else) and I'm wondering what kind of technologies there are to deal with the video files, specifically in PHP.
I'm thinking the files need to be converted to an FLV. After that I think it's just loading the FLV, like an SWF in Flash.
They also want to do mp3's with Flash streaming, so it'd be cool if it could also support mp3's.
|
[ffmpeg](http://ffmpeg.mplayerhq.hu/) is the tool for you. It's a major opensource video encoding library that a lot of other tools are based on. It's a bit tricky to use directly, but I think there are a few wrappers around.
|
In adition to Daniels answer, I recommend you to check [ffmpeg-php](http://ffmpeg-php.sourceforge.net/), is a wrapper library for PHP that adds an object-oriented API for accessing and retrieving information from video and audio files using [ffmpeg](http://ffmpeg.mplayerhq.hu/).
You can do a lot of things, from converting between formats, get video frame images for thumbnails and more in an easy way...
|
Add dynamic video content (YouTube like) (PHP)
|
[
"",
"php",
"flash",
"mp3",
"flv",
""
] |
I am trying to do positioning in JavaScript. I am using a cumulative position function based on the [classic quirksmode function](http://www.quirksmode.org/js/findpos.html "Find position") that sums `offsetTop` and `offsetLeft` for each `offsetParent` until the top node.
However, I am running into an issue where the element I'm interested in has no `offsetParent` in Firefox. In IE `offsetParent` exists, but `offsetTop` and `offsetLeft` all sum up to 0, so it has the same problem in effect as in Firefox.
What would cause an element that is clearly visible and usable on the screen to not have an `offsetParent`? Or, more practically, how can I find the position of this element in order to place a drop-down beneath it?
**Edit**: Here's how to reproduce one particular instance of this (not solved by the currently-accepted answer):
1. Open the [home page of Stack Overflow](http://stackoverflow.com).
2. Run the following code in the Console of the web browser (e.g. Chromev21):
```
var e = document.querySelector('div');
console.log(e);
// <div id="notify-container"></div>
do{
var s = getComputedStyle(e);
console.log(e.tagName,s.display,s.visibility,s.position,e.offsetParent);
} while(e=e.parentElement)
// DIV block visible fixed null
// BODY block visible static null
// HTML block visible static null
```
**Why is the `offsetParent` of that element `null`?**
|
If the document hasn't finished loading then offsetParent can be null
|
I have made [a test of 2,304 divs](http://jsfiddle.net/XEHZV/3/) with unique combinations of values for `position`, `display`, and `visibility`, nested inside unique combinations of each of those values, and determined that:
an otherwise-valid element
that is a descendant of `<body>`
will not have an `offsetParent` value if:
* The element has `position:fixed` (*Webkit and IE9*)
* The element has `display:none` (*Webkit and FF*)
* Any ancestor has `display:none` (*Webkit and FF*)
*It is also reasonable to expect that an element that has no parent, or that is not added to the page itself (is not a descendant of the `<body>` of the page), will also have `offsetParent==null`.*
|
What would make offsetParent null?
|
[
"",
"javascript",
"html",
"positioning",
""
] |
I can't seem to find an answer to this problem, and I'm wondering if one exists. Simplified example:
Consider a string "nnnn", where I want to find all matches of "nn" - but also those that overlap with each other. So the regex would provide the following 3 matches:
1. **nn**nn
2. n**nn**n
3. nn**nn**
I realize this is not exactly what regexes are meant for, but walking the string and parsing this manually seems like an awful lot of code, considering that in reality the matches would have to be done using a pattern, not a literal string.
|
Update 2016:
To get `nn`, `nn`, `nn`, [SDJMcHattie](https://stackoverflow.com/users/772095/sdjmchattie) proposes in [the comments](https://stackoverflow.com/questions/320448/overlapping-matches-in-regex/320478?noredirect=1#comment57488084_320478) [`(?=(nn))` (see regex101)](https://regex101.com/r/ET6Rvs/1/).
```
(?=(nn))
```
---
Original answer (2008)
A possible solution could be to use a [positive look behind](http://www.regular-expressions.info/lookaround.html):
```
(?<=n)n
```
It would give you the end position of:
1. *n***n**nn
2. n*n***n**n
3. nn*n***n**
---
As mentioned by [Timothy Khouri](https://stackoverflow.com/users/11917/timothy-khouri), a **positive lookahead** is more intuitive ([see example](https://regex101.com/r/cLFqDC/1))
I would prefer to his proposition `(?=nn)n` the simpler form:
```
(n)(?=(n))
```
That would reference the **first position** of the strings you want **and would capture the second n in group(2)**.
That is so because:
* Any valid regular expression can be used inside the lookahead.
* If it contains capturing parentheses, the **backreferences will be saved**.
So group(1) and group(2) will capture whatever 'n' represents (even if it is a complicated regex).
---
|
Using a lookahead with a capturing group works, at the expense of making your regex slower and more complicated. An alternative solution is to tell the Regex.Match() method where the next match attempt should begin. Try this:
```
Regex regexObj = new Regex("nn");
Match matchObj = regexObj.Match(subjectString);
while (matchObj.Success) {
matchObj = regexObj.Match(subjectString, matchObj.Index + 1);
}
```
|
Overlapping matches in Regex
|
[
"",
"c#",
"regex",
"overlap",
""
] |
Something is eluding me ... it seems obvious, but I can't quite figure it out.
I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ...
So if a user selects:
1 room, there is one text box
2 rooms, there are two text boxes
3 rooms, three text boxes
back to 2 rooms, two text boxes
and so on ...
|
Using straight DOM and Javascript you would want to modify the InnterHtml property of a DOM object which will contain the text boxes...most likely a div. So it would look something like:
```
var container = document.getElementById("myContainerDiv");
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
container.innerHtml = html;
```
Using a Javascript library like jQuery could make things slightly easier:
```
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
$("#myContainerDiv").append(html);
```
|
for your select list of rooms, add an onchange event handler that will show/hide the text boses.
```
<script>
//swap $ with applicable lib call (if avail)
function $(id){
return document.getElementById(id);
}
function adjustTexts(obj){
var roomTotal = 4;
var count = obj.selectedIndex;
//show/hide unrequired text boxes...
for(var i=0;i<roomTotal;i++){
if(i < count){
$('room'+ (i+1)).style.display = 'block';
} else {
$('room'+ (i+1)).style.display = 'none';
}
}
}
</script>
<select name="rooms" onchange="adjustTexts(this);">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<div id="room1">
<label>Room 1</label>:<input type="text" name="room1text"/>
</div>
<div id="room2" style="display:none;">
<label>Room 2</label>:<input type="text" name="room2text"/>
</div>
<div id="room3" style="display:none;">
<label>Room 3</label>:<input type="text" name="room3text"/>
</div>
<div id="room4" style="display:none;">
<label>Room 4</label>:<input type="text" name="room4text"/>
</div>
```
|
Add HTML control(s) via javascript
|
[
"",
"javascript",
"html",
"controls",
""
] |
I have downloaded Privoxy few weeks ago and for the fun I was curious to know how a simple version of it can be done.
I understand that I need to configure the browser (client) to send request to the proxy. The proxy send the request to the web (let say it's a http proxy). The proxy will receive the answer... but how can the proxy send back the request to the browser (client)?
I have search on the web for C# and http proxy but haven't found something that let me understand how it works behind the scene correctly. (I believe I do not want a reverse proxy but I am not sure).
Does any of you have some explication or some information that will let me continue this small project?
## Update
This is what I understand (see graphic below).
**Step 1** I configure the client (browser) for all request to be send to 127.0.0.1 at the port the Proxy listen. This way, request will be not sent to the Internet directly but will be processed by the proxy.
**Step2** The proxy see a new connection, read the HTTP header and see the request he must executes. He executes the request.
**Step3** The proxy receive an answer from the request. Now he must send the answer from the web to the client but how???

### Useful link
[Mentalis Proxy](http://www.mentalis.org/soft/projects/proxy/) : I have found this project that is a proxy (but more that I would like). I might check the source but I really wanted something basic to understand more the concept.
[ASP Proxy](http://www.codeproject.com/KB/aspnet/asproxy.aspx) : I might be able to get some information over here too.
[Request reflector](http://bartdesmet.net/blogs/bart/archive/2007/02/22/httplistener-for-dummies-a-simple-http-request-reflector.aspx) : This is a simple example.
Here is a [Git Hub Repository with a Simple Http Proxy](https://github.com/MrDesjardins/SimpleHttpProxy).
|
You can build one with the [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) class to listen for incoming requests and the [`HttpWebRequest`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) class to relay the requests.
|
I wouldn't use HttpListener or something like that, in that way you'll come across so many issues.
Most importantly it'll be a huge pain to support:
* Proxy Keep-Alives
* SSL won't work (in a correct way, you'll get popups)
* .NET libraries strictly follows RFCs which causes some requests to fail (even though IE, FF and any other browser in the world will work.)
What you need to do is:
* Listen a TCP port
* Parse the browser request
* Extract Host connect to that host in TCP level
* Forward everything back and forth unless you want to add custom headers etc.
I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.
Mentalis doing this, but their code is "delegate spaghetti", worse than GoTo :)
|
How to create a simple proxy in C#?
|
[
"",
"c#",
".net",
".net-2.0",
"proxy",
""
] |
We have a large management software that is producing big reports of all kinds, based on numerous loops, with database retrievals, objects creations (many), and so on.
On PHP4 it could run happily with a memory limit of 64 MB - now we have moved it on a new server and with the same database - same code, the same reports won't come up without a gig of memory limit...
I know that PHP5 has changed under the hood quite a lot of things, but is there a way to make it behave ?
The question at the end is, what strategies do you apply when you need to have your scripts on a diet ?
|
A big problem we have run into was circular references between objects stopping them from freeing memory when they become out of scope.
Depending on your architecture you may be able to use \_\_destruct() and manually unset any references. For our problem i ended up restructuring the classes and removing the circular references.
|
When I need to optimize resources on any script, I try always to analyze, profile and debug my code, I use [xDebug](http://www.xdebug.org/), and the [xDebug Profiler](http://www.xdebug.org/docs/profiler), there are other options like [APD](http://php.net/apd), and [Benchmark Profiler](http://pear.php.net/package/Benchmark).
Additionally I recommend you this articles:
* [Make PHP apps fast, faster, fastest..](http://www.ibm.com/developerworks/library/os-php-fastapps2/index.html)
* [Profiling PHP Applications](http://www.schlossnagle.org/~george/talks/Profiling-phpworks-2004.pdf) *(PDF)*
* [PHP & Performance](http://ilia.ws/files/frankfurt_perf.pdf) *(PDF)*
|
Strategies for handling memory consumption in PHP5?
|
[
"",
"php",
"memory",
""
] |
Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.
|
How do you feel about Win32 interop? I found [C/Win32 code](http://skyscraper.fortunecity.com/gigo/311/winprog/shellico.txt "this C/Win32 code") that might do the trick for you. (Actually, it looks like an interesting problem so I might try to tackle it myself, just not now).
The magic appears to be that he gets a handle to the system tray's window:
```
NotifyWnd = FindWindowEx(SysTray, 0, "TrayNotifyWnd", 0);
```
Then he sets a hook on its message pump:
```
hHook=SetWindowsHookEx(WH_CALLWNDPROC,HOOKPROC(MsgProc),
hInstance,dwExplorerThreadId);
```
Then during the message pump hook callback, he gets a reference to some pointer data about the window:
```
TWDataT* twd=(TWDataT*)GetWindowLong(NotifyWnd,0);
```
The mystery is then his loop:
```
pTWIconDataT p=COMCTL32_332(twd->iconsInfo,i);
```
COMCTL32\_332 is defined with GetProcAddress and points to ordinal 332 of Comctl32.dll - according to my checking with Dependency Viewer, that's [DPA\_GetPtr](http://msdn.microsoft.com/en-us/library/bb775617.aspx "DPA_GetPtr"), which gets data from a dynamic pointer array. I'm not familiar with what's going on behind the scenes there, but it doesn't seem entirely out of the question.
I'm going to play with this a bit myself, but hopefully it's a good place to get you started. :)
|
Mathias Rauen's madCollection (for Delphi not c#) can list [Tray Icons](http://help.madshi.net/TrayIcons.htm).
And there is a commandline tool: [Windows System Tray Scan Utility](http://exodusdev.com/products/windows-system-tray-scan-utility)
I have also written (not released) my own program in Delphi (not Delphi.NET), not using madCollection, which shows tray icons, process names, tooltips and other info but it's not perfect. There are a few icons it can't display (even though it lists other info), and it can't display any icons under windows 9x. I haven't tested it at all under Vista.
|
Systray Access
|
[
"",
"c#",
".net",
""
] |
Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.
Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the `is` operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?
|
Take a look at this:
```
>>> a = 256
>>> b = 256
>>> id(a) == id(b)
True
>>> a = 257
>>> b = 257
>>> id(a) == id(b)
False
```
Here's what I found in the documentation for ["Plain Integer Objects"](https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong):
> The current implementation keeps an array of integer objects for all integers between `-5` and `256`. When you create an int in that range you actually just get back a reference to the existing object.
So, integers 256 are [identical](https://docs.python.org/3/library/functions.html#id), but 257 are not. This is a CPython implementation detail, and not guaranteed for other Python implementations.
|
> # Python's “is” operator behaves unexpectedly with integers?
In summary - let me emphasize: ***Do not use `is` to compare integers.***
This isn't behavior you should have any expectations about.
Instead, use `==` and `!=` to compare for equality and inequality, respectively. For example:
```
>>> a = 1000
>>> a == 1000 # Test integers like this,
True
>>> a != 5000 # or this!
True
>>> a is 1000 # Don't do this! - Don't use `is` to test integers!!
False
```
## Explanation
To know this, you need to know the following.
First, what does `is` do? It is a comparison operator. From the [documentation](https://docs.python.org/2/reference/expressions.html#not-in):
> The operators `is` and `is not` test for object identity: `x is y` is true
> if and only if x and y are the same object. `x is not y` yields the
> inverse truth value.
And so the following are equivalent.
```
>>> a is b
>>> id(a) == id(b)
```
From the [documentation](https://docs.python.org/library/functions.html#id):
> **`id`**
> Return the “identity” of an object. This is an integer (or long
> integer) which is guaranteed to be unique and constant for this object
> during its lifetime. Two objects with non-overlapping lifetimes may
> have the same `id()` value.
Note that the fact that the id of an object in CPython (the reference implementation of Python) is the location in memory is an implementation detail. Other implementations of Python (such as Jython or IronPython) could easily have a different implementation for `id`.
So what is the use-case for `is`? [PEP8 describes](https://www.python.org/dev/peps/pep-0008/#programming-recommendations):
> Comparisons to singletons like `None` should always be done with `is` or
> `is not`, never the equality operators.
## The Question
You ask, and state, the following question (with code):
> **Why does the following behave unexpectedly in Python?**
>
> ```
> >>> a = 256
> >>> b = 256
> >>> a is b
> True # This is an expected result
> ```
It is *not* an expected result. Why is it expected? It only means that the integers valued at `256` referenced by both `a` and `b` are the same instance of integer. Integers are immutable in Python, thus they cannot change. This should have no impact on any code. It should not be expected. It is merely an implementation detail.
But perhaps we should be glad that there is not a new separate instance in memory every time we state a value equals 256.
> ```
> >>> a = 257
> >>> b = 257
> >>> a is b
> False # What happened here? Why is this False?
> ```
Looks like we now have two separate instances of integers with the value of `257` in memory. Since integers are immutable, this wastes memory. Let's hope we're not wasting a lot of it. We're probably not. But this behavior is not guaranteed.
> ```
> >>> 257 is 257
> True # Yet the literal numbers compare properly
> ```
Well, this looks like your particular implementation of Python is trying to be smart and not creating redundantly valued integers in memory unless it has to. You seem to indicate you are using the referent implementation of Python, which is CPython. Good for CPython.
It might be even better if CPython could do this globally, if it could do so cheaply (as there would a cost in the lookup), perhaps another implementation might.
But as for impact on code, you should not care if an integer is a particular instance of an integer. You should only care what the value of that instance is, and you would use the normal comparison operators for that, i.e. `==`.
## What `is` does
`is` checks that the `id` of two objects are the same. In CPython, the `id` is the location in memory, but it could be some other uniquely identifying number in another implementation. To restate this with code:
```
>>> a is b
```
is the same as
```
>>> id(a) == id(b)
```
## Why would we want to use `is` then?
This can be a very fast check relative to say, checking if two very long strings are equal in value. But since it applies to the uniqueness of the object, we thus have limited use-cases for it. In fact, we mostly want to use it to check for `None`, which is a singleton (a sole instance existing in one place in memory). We might create other singletons if there is potential to conflate them, which we might check with `is`, but these are relatively rare. Here's an example (will work in Python 2 and 3) e.g.
```
SENTINEL_SINGLETON = object() # this will only be created one time.
def foo(keyword_argument=None):
if keyword_argument is None:
print('no argument given to foo')
bar()
bar(keyword_argument)
bar('baz')
def bar(keyword_argument=SENTINEL_SINGLETON):
# SENTINEL_SINGLETON tells us if we were not passed anything
# as None is a legitimate potential argument we could get.
if keyword_argument is SENTINEL_SINGLETON:
print('no argument given to bar')
else:
print('argument to bar: {0}'.format(keyword_argument))
foo()
```
Which prints:
```
no argument given to foo
no argument given to bar
argument to bar: None
argument to bar: baz
```
And so we see, with `is` and a sentinel, we are able to differentiate between when `bar` is called with no arguments and when it is called with `None`. These are the primary use-cases for `is` - do *not* use it to test for equality of integers, strings, tuples, or other things like these.
|
"is" operator behaves unexpectedly with integers
|
[
"",
"python",
"int",
"operators",
"identity",
"python-internals",
""
] |
i want the result of an equation rounded to the nearest integer.
e.g.
```
137 * (3/4) = 103
```
Consider the following incorrect code.
```
int width1 = 4;
int height1 = 3;
int width2 = 137;
int height2 = width2 * (height1 / width1);
```
What is the proper way to perform "integer" math in C#?
Do i really have to do:
```
int height2 = (int)Math.Round(
(float)width2 * ((float)height1 / (float)width1)
);
```
|
As said above, you should do the multiplication before the division.
Anyway you could write your expression with casting only the divisor:
```
int height2 = (int)Math.Round(width2 * (height1 / (float)width1));
```
|
```
int height2 = (width2 * height1) / width1;
```
|
C#: How do I do simple math, with rounding, on integers?
|
[
"",
"c#",
"math",
"rounding",
""
] |
I occasionally see the list slice syntax used in Python code like this:
```
newList = oldList[:]
```
Surely this is just the same as:
```
newList = oldList
```
Or am I missing something?
|
Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.
`newList = oldList` would create two different variables that point to the same object, therefore, changing `oldList` would also change `newList`.
However, when you do `newList = oldList[:]`, it "slices" the list, and creates a new list. The default values for `[:]` are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.
|
`[:]` [Shallow copies](http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy) the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original.
A [Deep Copy](http://en.wikipedia.org/wiki/Deep_copy#Deep_copy) would make copies of all the list members as well.
The code snippet below shows a shallow copy in action.
```
# ================================================================
# === ShallowCopy.py =============================================
# ================================================================
#
class Foo:
def __init__(self, data):
self._data = data
aa = Foo ('aaa')
bb = Foo ('bbb')
# The initial list has two elements containing 'aaa' and 'bbb'
OldList = [aa,bb]
print OldList[0]._data
# The shallow copy makes a new list pointing to the old elements
NewList = OldList[:]
print NewList[0]._data
# Updating one of the elements through the new list sees the
# change reflected when you access that element through the
# old list.
NewList[0]._data = 'xxx'
print OldList[0]._data
# Updating the new list to point to something new is not reflected
# in the old list.
NewList[0] = Foo ('ccc')
print NewList[0]._data
print OldList[0]._data
```
Running it in a python shell gives the following transcript. We can see the
list being made with copies of the old objects. One of the objects can have
its state updated by reference through the old list, and the updates can be
seen when the object is accessed through the old list. Finally, changing a
reference in the new list can be seen to not reflect in the old list, as the
new list is now referring to a different object.
```
>>> # ================================================================
... # === ShallowCopy.py =============================================
... # ================================================================
... #
... class Foo:
... def __init__(self, data):
... self._data = data
...
>>> aa = Foo ('aaa')
>>> bb = Foo ('bbb')
>>>
>>> # The initial list has two elements containing 'aaa' and 'bbb'
... OldList = [aa,bb]
>>> print OldList[0]._data
aaa
>>>
>>> # The shallow copy makes a new list pointing to the old elements
... NewList = OldList[:]
>>> print NewList[0]._data
aaa
>>>
>>> # Updating one of the elements through the new list sees the
... # change reflected when you access that element through the
... # old list.
... NewList[0]._data = 'xxx'
>>> print OldList[0]._data
xxx
>>>
>>> # Updating the new list to point to something new is not reflected
... # in the old list.
... NewList[0] = Foo ('ccc')
>>> print NewList[0]._data
ccc
>>> print OldList[0]._data
xxx
```
|
Python list slice syntax used for no obvious reason
|
[
"",
"python",
"list",
"shallow-copy",
""
] |
I have an entity that maps to an external oracle table which is one of the primary data sources of my application. This entity is modelled using hibernate.
The oracle table now has a complex function defined the calculates some special values. I need to call this function somehow - almost as another accessor on the entity.
What would you suggest is the best way to incorporate this function call so that I can maintain relatively normal hibernate access to the entities?
|
I have a solution using the @Formula annotation
|
In order to keep the decoupling from your database, provided by Hibernate, I would rely on Oracle to invoke this function, using triggers or views.
The main advantage of this approach is that it is totally seamless to your Hibernate implementation.
|
Hibernate and Oracle native functions
|
[
"",
"java",
"oracle",
"hibernate",
""
] |
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.
For example:
```
typedef std::bitset<16> WordSet;
```
Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in `g++`.
|
It's not possible in general to pick arbitrary template parameters.
However, the usual way you do it is this:
```
template<int N>
struct foo {
static const int value = N;
};
```
and for types
```
template<typename T>
struct foo {
typedef T type;
};
```
You can access it then as `foo<39>::value` or `foo<int>::type`.
If you have a particular type, you can use partial template specialization:
```
template<typename>
struct steal_it;
template<std::size_t N>
struct steal_it< std::bitset<N> > {
static const std::size_t value = N;
};
```
The same principle is possible for type parameters too, indeed. Now you can pass any bitset to it, like `steal_it< std::bitset<16> >::value` (note to use size\_t, not int!). Because we have no variadic many template paramters yet, we have to limit ourself to a particular parameter count, and repeat the steal\_it template specializations for count from 1 up to N. Another difficulty is to scan types that have mixed parameters (types and non-types parameters). This is probably nontrivial to solve.
If you have not the type, but only an object of it, you can use a trick, to still get a value at compile time:
```
template<typename T>
char (& getN(T const &) )[steal_it<T>::value];
int main() {
std::bitset<16> b;
sizeof getN(b); // assuming you don't know the type, you can use the object
}
```
The trick is to make the function template auto-deduce the type, and then return a reference to a character array. The function doesn't need to be defined, the only thing needed is its type.
|
You can easily do this in C++11 using argument deduction and unevaluated contexts (note that demo uses C++14's variable template feature for convenience).
```
#include <type_traits>
#include <iostream>
template<int>
struct foo {};
template<int arg_N>
struct val {
static constexpr auto N = arg_N;
};
template<template <int> typename T, int N>
constexpr auto extract(const T<N>&) -> val<N>;
template<typename T>
constexpr auto extract_N = decltype(extract(std::declval<T>()))::N;
int main() {
std::cout << extract_N<foo<5>>;
}
```
[`Live demo`](http://coliru.stacked-crooked.com/a/498365c253663e80)
|
Extract C++ template parameters
|
[
"",
"c++",
"templates",
"rtti",
""
] |
Nested If or single if with And operator, which is better approach?
**Single If with And**
```
if (txtPackage.Text != string.Empty && txtPackage.Text == "abc")
{
//
}
```
**Nested If**
```
if (txtPackage.Text != string.Empty)
{
if (txtPackage.Text == "abc")
{
//
}
}
```
|
Are you going to do something different in the 'nested if' example if, in fact, txtPackage.Text isn't empty but contains something other than "abc"?
If you aren't, I'd ask why are you checking for string.empty at all?
You could just write:
```
if (txtPackage.Text == "abc")
{
//
}
```
and be done with it.
Totally depends upon what you want to do in the end.
|
I wasn't going to chime in, but seeing that some answers here seem to be about "I like my code to *look* like this"... I feel that I should say something :)
"Better" means the code will execute faster, or it's more readable / extendable. You **would** want to nest your if's in the case that you would possibly have multiple checks that all have a common requirement.
Example:
```
if (myThingy != null)
{
if (myThingy.Text = "Hello") ...
if (myThingy.SomethingElse = 123) ...
}
```
EDIT: It also needs to be said that nesting your IF's requires more CPU cycles (and is therefore "slower") than a single IF. On top of that, the order of your conditions can greatly increase performance.
Exapmle again:
```
if (somethingQuick() && somethingThatTakesASecondToCalculate()) ...
```
is a LOT faster (of course) than
```
if (somethingThatTakesASecondToCalculate() && somethingQuick()) ...
```
Because if the first part of the IF fails, the second part won't even be executed, thus saving time.
|
Which is better apply two conditions in nested If or using single with And?
|
[
"",
"c#",
"vb.net",
""
] |
I'm a self-taught developer and my experience is all in small applications that I've developed.
I'm currently working on an application that I've made public, and I've realized that I need to start doing good unit testing to catch regressions and generally make sure everything works.
I've read up on a [previous question](https://stackoverflow.com/questions/205566/comprehensive-introduction-to-unit-testing). I would like to know if there are any resources online specifically dealing with C# unit testing in Visual Studio 2008, preferably with examples.
EDIT: I'm using Visual Studio 2008 Professional for Windows applications, no web development.
|
You don't specify which [flavor of VS2008](http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx) you are using. If it is Pro or above, then MSTest is bundled, but a lot of people have issues with it - it isn't always very intuitive, and it takes far too much setup to do simple things like coverage / file deployment.
A walkthrough is [here](http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx).
As a recommendation, I suggest using VS2008 with [NUnit](http://www.nunit.org/) (free) and [TestDriven.NET](http://testdriven.net/) (not free). It takes away all the pain, allowing you to just write simple things like:
```
[TestFixture]
public class Foo {
[Test]
public void Bar() {
Assert.AreEqual(2, 1+1);
}
}
```
Then just right-click (on the class, on the method, on the project, on the solution) and use the Test options that TestDriven.NET provides, including (if you have MSTest) "Test With -> Team Coverage", which runs your NUnit tests with the MSTest coverage tools, including giving the colorization back into the IDE to show which lines executed. No messing with "testrunconfig" and the other files that MSTest wants you to use.
|
<http://www.asp.net/learn/mvc-videos/>
Storefront and the Pair Programming videos involve a lot of TDD (Test Driven Development)
|
Beginners introduction to unit testing in Visual Studio 2008
|
[
"",
"c#",
"visual-studio-2008",
"unit-testing",
""
] |
I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?
|
Lets see... you'll need:
1. A JDK. Preferably the [Standard Edition](http://java.sun.com/javase/downloads/index.jsp), unless you plan on using GlassFish as a J2EE server. If you do use the standard edition, you need to include the jars from your servlet container/J2EE stack to access J2EE libraries.
2. A Servlet container. [Apache Tomcat](http://tomcat.apache.org/) is a popular one, and Eclipse already has integration support for it. Keep in mind that Tomcat is not a complete J2EE stack... you need something like [JBoss Application Server](http://www.jboss.org/jbossas/) or [Apache Geronimo](http://geronimo.apache.org/) for that.
3. (Semi-Optional) A web server. Apache Web Server *surprisingly* works well with Apache Tomcat or Apache Geronimo... it's almost like they were made by the same people! Eclipse has built-in support for Tomcat and doesn't appear to require a web server because of it. I could be wrong, though.
4. (Optional) An IDE. If you use [Eclipse](http://www.eclipse.org/), get the version for Java EE Developers.
5. (Optional) A Database. MySQL and HSQLDB are popular ones for Java, at least for small to medium applications. Keep in mind that you also need to download the JDBC drivers for your database.
6. (Optional) A revision control system. Even on a single-developer project, a revision control system can save your hide if you accidentally remove code or a file that you shouldn't. There are several choices here; [Subversion](http://subversion.tigris.org/) is my personal choice, along with an Eclipse plugin for it, such as [Subclipse](http://subclipse.tigris.org/).
|
I'd recommend having a database server installed as well- you can go pretty far with the various pure Java implementations, but anything significant will probably benefit from having a copy of MySQL around.
I'd also get some sort of version control going- tortoiseSVN works really well for windows. Even if you're just goofing around for yourself, getting in the habit of using it will save time and heartache down the road.
|
What do I need to write Java-based web applications and test them on my personal computer?
|
[
"",
"java",
""
] |
I need to test a url that it **does not** end with `.asp`
So `test`, `test.html` and `test.aspx` should match, but `test.asp` should not match.
Normally you'd test if the url **does** end with .asp and negate the fact that it matched using the NOT operator in code:
```
if(!regex.IsMatch(url)) { // Do something }
```
In that case the regular expression would be `\.asp$` but in this case I need the regular expression to result in a match.
---
Background: I need to use the regular expression as a route contraint in the ASP.NET MVC `RouteCollection.MapRoute` extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp
|
The trick is to use [negative lookbehind](http://www.regular-expressions.info/lookaround.html).
If you need just a yes/no answer:
```
(?<!\.asp)$
```
If you need to match the whole URL:
```
^.*(?<!\.asp)$
```
These regexes will work with any URL where the file name occurs at the end of the URL (i.e. URLs without a query or fragment). I'm assuming your URLs fit this limitation given the regex .asp$ in your question. If you want it to work with all URLs, try this:
```
^[^#?]+(?<!\.asp)([#?]|$)
```
Or this if you want the regex to match the whole URL:
```
^[^#?]+(?<!\.asp)([#?].+|$)
```
|
Not a regexp, but c# String.EndsWith method which could easily do the job.
ie
```
string test1 = "me.asp" ;
string test2 = "me.aspx" ;
test1.EndsWith(".asp") // true;
test2.EndsWith(".asp") // false ;
```
|
Regular expression to match a string (1+ characters) that does NOT end in .ext (extension)
|
[
"",
"c#",
".net",
"asp.net-mvc",
"regex",
""
] |
I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand.
ld output:
> ld: duplicate symbol text\_field(std::basic\_istream >&)in /path/final/build/final.build/Release/final.build/Objects-normal/ppc/generics.o and /path/final/build/final.build/Release/final.build/Objects-normal/ppc/main.o
> collect2: ld returned 1 exit status
Below is my file io\_functions.cpp This is the only declaration of text\_field in the entire project.
```
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
#ifndef ENDF
#define ENDF '|'
#define ENDR '\n'
/**
reads one field from a given input stream
Usage: var = text_field(in)
*/
string text_field(istream &in){
string s;
getline(in, s, ENDF);
return s;
}
long long_field(istream &in){
return atol(text_field(in).c_str());
}
int int_field(istream &in){
return atoi(text_field(in).c_str());
}
double double_field(istream &in){
return atof(text_field(in).c_str());
}
#endif
```
What is going wrong? For a number of reasons I don't want to post my project's entire source.
|
My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in `main.o` and `generics.o`.
So it looks like you're including the `io_functions.cpp` file into the `main.cpp` and `generics.cpp` which is a bad idea at the best of times.
You should have a header file (e.g., `io_functions.h`) that specifies everything contained in `io_functions.cpp` and include that *header* file into the other two.
|
It sounds like io\_functions.cpp is being included twice (once by generics.cpp, once by main.cpp).
|
ld: duplicate symbol
|
[
"",
"c++",
"xcode",
"linker",
""
] |
I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to the x and the y axis, that is all of their edges will have slopes of 0 or infinity.
I've tried to implement what is mentioned in [this](https://stackoverflow.com/questions/115426) question but I am not having very much luck.
My current implementation does the following:
```
// Gets all the vertices for Rectangle 1 and stores them in an array -> arrRect1
// point 1 x: arrRect1[0], point 1 y: arrRect1[1] and so on...
// Gets all the vertices for Rectangle 2 and stores them in an array -> arrRect2
// rotated edge of point a, rect 1
int rot_x, rot_y;
rot_x = -arrRect1[3];
rot_y = arrRect1[2];
// point on rotated edge
int pnt_x, pnt_y;
pnt_x = arrRect1[2];
pnt_y = arrRect1[3];
// test point, a from rect 2
int tst_x, tst_y;
tst_x = arrRect2[0];
tst_y = arrRect2[1];
int value;
value = (rot_x * (tst_x - pnt_x)) + (rot_y * (tst_y - pnt_y));
cout << "Value: " << value;
```
However I'm not quite sure if (a) I've implemented the algorithm I linked to correctly, or if I did exactly how to interpret this?
Any suggestions?
|
```
if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&
RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top )
```
or, using Cartesian coordinates
(With X1 being left coord, X2 being right coord, **increasing from left to right** and Y1 being Top coord, and Y2 being Bottom coord, **increasing from bottom to top** -- if this is not how your coordinate system [e.g. most computers have the Y direction reversed], **swap the comparisons below**) ...
```
if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
RectA.Y1 > RectB.Y2 && RectA.Y2 < RectB.Y1)
```
Say you have Rect A, and Rect B.
Proof is by contradiction. Any one of four conditions guarantees that **no overlap can exist**:
* Cond1. If A's left edge is to the right of the B's right edge,
- then A is Totally to right Of B
* Cond2. If A's right edge is to the left of the B's left edge,
- then A is Totally to left Of B
* Cond3. If A's top edge is below B's bottom edge,
- then A is Totally below B
* Cond4. If A's bottom edge is above B's top edge,
- then A is Totally above B
So condition for Non-Overlap is
```
NON-Overlap => Cond1 Or Cond2 Or Cond3 Or Cond4
```
Therefore, a sufficient condition for Overlap is the opposite.
```
Overlap => NOT (Cond1 Or Cond2 Or Cond3 Or Cond4)
```
De Morgan's law says
`Not (A or B or C or D)` is the same as `Not A And Not B And Not C And Not D`
so using De Morgan, we have
```
Not Cond1 And Not Cond2 And Not Cond3 And Not Cond4
```
This is equivalent to:
* A's Left Edge to left of B's right edge, [`RectA.Left < RectB.Right`], and
* A's right edge to right of B's left edge, [`RectA.Right > RectB.Left`], and
* A's top above B's bottom, [`RectA.Top > RectB.Bottom`], and
* A's bottom below B's Top [`RectA.Bottom < RectB.Top`]
**Note 1**: It is fairly obvious this same principle can be extended to any number of dimensions.
**Note 2**: It should also be fairly obvious to count overlaps of just one pixel, change the `<` and/or the `>` on that boundary to a `<=` or a `>=`.
**Note 3**: This answer, when utilizing Cartesian coordinates (X, Y) is based on standard algebraic Cartesian coordinates (x increases left to right, and Y increases bottom to top). Obviously, where a computer system might mechanize screen coordinates differently, (e.g., increasing Y from top to bottom, or X From right to left), the syntax will need to be adjusted accordingly/
|
```
struct rect
{
int x;
int y;
int width;
int height;
};
bool valueInRange(int value, int min, int max)
{ return (value >= min) && (value <= max); }
bool rectOverlap(rect A, rect B)
{
bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||
valueInRange(B.x, A.x, A.x + A.width);
bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||
valueInRange(B.y, A.y, A.y + A.height);
return xOverlap && yOverlap;
}
```
|
Determine if two rectangles overlap each other?
|
[
"",
"c++",
"algorithm",
"geometry",
"overlap",
"rectangles",
""
] |
When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.
I know how to do this with Win32 functions (the `WNet*` family from `mpr.dll`), but would like to do it with .Net (2.0) functionality.
What options are available?
**Maybe some more information helps:**
* The use case is a windows service, not an Asp.Net application.
* The service is running under an account which has no rights on the share.
* The user account needed for the share is not known on the client side.
* Client and server are not members of the same domain.
|
You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):
```
using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
File.Copy(@"\\server\read\file", @"\\server2\write\file");
}
```
|
I liked [Mark Brackett](https://stackoverflow.com/users/2199/mark-brackett)'s answer so much that I did my own quick implementation. Here it is if anyone else needs it in a hurry:
```
public class NetworkConnection : IDisposable
{
string _networkName;
public NetworkConnection(string networkName,
NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result);
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
[MarshalAs(UnmanagedType.LPWStr)]
public string LocalName;
[MarshalAs(UnmanagedType.LPWStr)]
public string RemoteName;
[MarshalAs(UnmanagedType.LPWStr)]
public string Comment;
[MarshalAs(UnmanagedType.LPWStr)]
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
```
|
How to provide user name and password when connecting to a network share
|
[
"",
"c#",
".net",
"winapi",
"networking",
"passwords",
""
] |
I've tried the following, but I was unsuccessful:
```
ALTER TABLE person ALTER COLUMN dob POSITION 37;
```
|
"[Alter column position](http://wiki.postgresql.org/wiki/Alter_column_position)" in the PostgreSQL Wiki says:
> PostgreSQL currently defines column
> order based on the `attnum` column of
> the `pg_attribute` table. The only way
> to change column order is either by
> recreating the table, or by adding
> columns and rotating data until you
> reach the desired layout.
That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.
One other idea occurs to me: you can define a `VIEW` that specifies the order of columns how you like it, without changing the physical position of the column in the base table.
|
In PostgreSQL, while adding a field it would be added at the end of the table.
If we need to insert into particular position then
```
alter table tablename rename to oldtable;
create table tablename (column defs go here); ### with all the constraints
insert into tablename (col1, col2, col3) select col1, col2, col3 from oldtable;
```
**WARNING:** with this solution, other tables having foreign keys to `tablename` will keep referencing the `oldtable`, so you have any, you will have to fix them.
|
How do I alter the position of a column in a PostgreSQL database table?
|
[
"",
"sql",
"database",
"postgresql",
"alter-table",
""
] |
Does anyone know of a definitive list of LINQ to SQL query limitations that are not trapped at compile time, along with (where possible) workarounds for the limitations?
The list we have so far is:
* Calling methods such as `.Date` on `DateTime`
+ no workaround found
* `string.IsNullOrEmpty`
+ simple, just use `== ""` instead
* `.Last()`
+ we used `.OrderByDescending(x => x.WhateverProperty).First()`
|
Basically, that list is huge... it is everything outside of the relatively [small set of things that **are** handled](http://msdn.microsoft.com/en-us/library/bb386970.aspx). Unfortunately, the [Law Of Leaky Abstractions](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) kicks in, and each provider has different answers...
LINQ-to-Objects will do anything (pretty much), since it is delegates; LINQ-to-SQL and Entity Framework have **different** sets of support.
In general, I've had a fair amount of success using the `DateTime` properties etc - but in reality, you're going to have to ensure that your query expressions are covered by unit tests, so that if you ever change providers (or the provider gets updated) you know it all still works.
I guess one view is to think in terms of TSQL; there is no `BOTTOM n`, but there is a `TOP 1` (re the `OrderByDescending`); In terms of `string.IsNullOrEmpty`, you could be quite literal: `foo.Bar == null || foo.Bar == ""`; and with `DateTime.Date` you can probably do quite a bit with `DATEPART` / the various components.
Another option with LINQ-to-SQL is to encapsulate the logic in a UDF - so you could write a UDF that takes a `datetime` and returns a `datetime`, and expose that via the dbml onto the data-context. You can then use that in your queries:
```
where ctx.Date(foo.SomeDate) == DateTime.Today
```
This approach, however, doesn't necessarily make good use of indexes.
---
Update:
* The supported method translations etc are [here](http://msdn.microsoft.com/en-us/library/bb386970.aspx).
* The supported query operations etc are [here](http://msdn.microsoft.com/en-us/library/bb399342.aspx).
For the full gory details, you can look at `System.Data.Linq.SqlClient.PostBindDotNetConverter+Visitor` in reflector - in particular the `Translate...` methods; some `string` functions are handled separately. So not a *huge* selection - but this is an implementation detail.
|
LINQ is the language. LINQ-to-SQL compiles your LINQ command down into a SQL query. Thus, it is limited by the normal limitations of the TSQL syntax, or rather the items that can easily be converted into it.
As others have said, the lists of what you cannot do would be enormous. It is a much smaller list of what you can do. A general rule of thumb is to try to determine how the function you want to use would be converted into TSQL. If you have much trouble figuring it out, then don't use that function (or at least test it first).
But there is an easy work around to use LINQ commands that are not in LINQ-to-SQL. Separate the pure LINQ portions of your code from the LINQ-to-SQL portions. In other words, do the LINQ-to-SQL to pull the data in (with any functions you need that are available in LINQ-to\_SQL), with the command to put it into an object (ToEnumerable, ToList, or others similar). This executes the query and pulls the data local. Now it is available for the full LINQ syntax.
|
"Cannot call methods on DateTime", and other limitations
|
[
"",
".net",
"sql",
"linq",
"linq-to-sql",
""
] |
This SQL query was generated by Microsoft Access 2003, and works fine when run, but fails when trying to run from a Macro. Is there any obvious error within the query, or any reason it would not work?
```
SELECT tblAuction.article_no, tblAuction.article_name, tblAuction.subtitle, tblAuction.current_bid, tblAuction.start_price, tblAuction.bid_count, tblAuction.quant_total, tblAuction.quant_sold, tblAuction.start, tblAuction.ends, tblAuction.origin_end, tblUser.user_name, tblAuction.best_bidder_id, tblAuction.finished, tblAuction.watch, tblAuction.buyitnow_price, tblAuction.pic_url, tblAuction.private_auction, tblAuction.auction_type, tblAuction.insert_date, tblAuction.update_date, tblAuction.cat_1_id, tblAuction.cat_2_id, tblAuction.article_desc, tblAuction.countrycode, tblAuction.location, tblAuction.condition, tblAuction.revised, tblAuction.paypal_accept, tblAuction.pre_terminated, tblAuction.shipping_to, tblAuction.fee_insertion, tblAuction.fee_final, tblAuction.fee_listing, tblAuction.pic_xxl, tblAuction.pic_diashow, tblAuction.pic_count, tblAuction.item_site_id
FROM tblUser INNER JOIN tblAuction ON tblUser.id = tblAuction.seller_id;
```
|
Did you mean from a Access Macro or from VBScript or from VBA? If you have a macro that is invoking an action then my recommendation would be to convert it to a VBA statement. I assume when you say it works fine when run you mean run as an Access query. You don't specify whether the database is local or is a remote one (i.e. SQL Server). Assuming it is local then running that SQL statement from VBA must work.
|
[This article](http://support.microsoft.com/kb/931407) is for Access 2007, but perhaps you're experiencing this as well.
What's the security level you're using in Access? (Open an MDB, then go to Tools\Macro\Security...). Try lowering the security level and see if that helps.
|
sql query causing error 2950
|
[
"",
"sql",
"ms-access",
"macros",
""
] |
I am attempting to integrate an existing payment platform into my webshop. After making a succesful transaction, the payment platform sends a request to an URL in my application with the transaction ID included in the query parameters.
However, I need to do some post-processing like sending an order confirmation, etc. In order to do this, I'd need access to the user's session, since a lot of order-related information is stored there. To do this, I include the session\_id in the intial request XML and do the following after the transaction is complete:
```
$sessionId = 'foo'; // the sessionId is succesfully retrieved from the XML response
session_id($sessionId);
session_start();
```
The above code works fine, but `$_SESSION` is still empty. Am I overlooking something or this simply not possible?
**EDIT:**
Thanks for all the answers. The problem has not been solved yet. As said, the strange thing is that I can succesfully start a new session using the session\_id that belongs to the user that placed the order. Any other ideas?
|
Many thanks for all the replies.
[Smazurov's answer](https://stackoverflow.com/questions/325836/how-to-re-initialize-a-session-in-php#326915) got me thinking and made me overlook my PHP configuration once more.
PHP's default behaviour is not to encrypt the session-related data, which *should* make it possible to read out the session data after restarting an old session from another client. However, I use [Suhosin](http://www.hardened-php.net/suhosin/index.html) to patch and prevent some security issues. Suhosin's default behaviour is to [encrypt session data based on the User Agent](http://www.hardened-php.net/suhosin/configuration.html#suhosin.session.encrypt), making it a lot harder to read out other people's sessions.
This was also the cause of my problems; disabling this behaviour has solved the issue.
|
Not really what you ask for, but don't you need to persist the order into database before you send the customer to the payment-service? It's better to rely on persisted data in your post-processing of the order when you receive the confirmation of the payment.
Relying on sessions is not reliable since you will have no idea on how long this confirmation will take (usually it's instant, but in rare cases this will have a delay).
Also, in the event of your webserver restarting during this time span, will make you lose relevant data.
A third issue is if you have a load-balancing solution, with individual session-managment (very common) then you will have no guarantee that the payment-server and your client will reach the same webserver (since stickiness is usually source-ip based).
|
How to re-initialize a session in PHP?
|
[
"",
"php",
"session",
""
] |
Consider the following piece of Java code.
```
int N = 10;
Object obj[] = new Object[N];
for (int i = 0; i < N; i++) {
int capacity = 1000 * i;
obj[i] = new ArrayList(capacity);
}
```
Because in Java, all objects live on the Heap, the array does not
contain the objects themselves, but references to the objects. Also,
the array itself is also an object, thus it lives on the heap.
What is the equivalent in C++, but keeping the array and objects on
the stack, to avoid as much as possible needing new and delete ?
Edit: changed the code to use a custom constructor.
|
For an array of ArrayList objects:
```
ArrayList obj[10];
```
The objects will be default initialised, which is fine for user-defined types, but may not be what you want for builtin-types.
Consider also:
```
std::vector<ArrayList> obj(10, ArrayList());
```
This initialises the objects by copying whatever you pass as the second parameter. So they're all the same, but not necessarily default. And as litb points out, the "10" in the vector can be replaced by a non-constant expression, whereas the "10" in the array declaration can't.
This doesn't actually put the ArrayList objects on the stack, it puts all 10 in a single allocation from the heap. So there may very rarely be performance concerns, if you really can't afford a single allocation. However, the std::vector is on the stack and it deletes any heap objects it uses when it is destroyed. So for the purposes of making sure your resources are freed, the vector behaves "as though" it were all on the stack.
Note that mixing a container of Object, with ArrayList values, as you do in your example Java code, is fraught with peril in C++. Basically you can't do it, even if ArrayList extends Object, because the array would only contain the storage for 10 Objects, and ArrayList likely requires more bytes to store than Object. The result is that any ArrayList you try to copy into the array would get "sliced": only the initial part of its representation is put in the array.
If you want a container of a type saying that it contains Objects, but which actually contains ArrayLists, then you need a container of pointers. To get good resource-handling, this probably means you need a container of smart pointers.
|
Simply declaring
```
Object array_of_objects[10];
```
in C++ creates 10 default-constructed objects of type Object on the stack.
If you want to use a non-default constructor, that's not so easy in C++. There might be a way with placement new but I couldn't tell you off the top of my head.
**EDIT: Link to other question on StackOverflow**
How to use placement new for the array is explained in the answer to [this question](https://stackoverflow.com/questions/15254/can-placement-new-for-arrays-be-used-in-a-portable-way) here on StackOverflow.
|
C++: how to create an array of objects on the stack?
|
[
"",
"c++",
"arrays",
"stack",
"oop",
""
] |
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app?
In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):
```
class Movie(models.Model):
title = models.CharField(max_length=255)
```
and in profiles/models.py I want to have:
```
class MovieProperty(models.Model):
movie = models.ForeignKey(Movie)
```
But I can't get it to work. I've tried:
```
movie = models.ForeignKey(cf.Movie)
```
and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:
```
NameError: name 'User' is not defined
```
Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?
|
According to the docs, your second attempt should work:
> To refer to models defined in another application, you must instead explicitly specify the application label. For example, if the Manufacturer model above is defined in another application called production, you'd need to use:
```
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
```
Have you tried putting it into quotes?
|
It is also possible to pass the class itself:
```
from django.db import models
from production import models as production_models
class Car(models.Model):
manufacturer = models.ForeignKey(production_models.Manufacturer)
```
|
Foreign key from one app into another in Django
|
[
"",
"python",
"django",
"django-models",
""
] |
My code runs inside a JAR file, say **foo.jar**, and I need to know, in the code, in which folder the running **foo.jar** is.
So, if **foo.jar** is in `C:\FOO\`, I want to get that path no matter what my current working directory is.
|
```
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
```
Replace "MyClass" with the name of your class.
Obviously, this will do odd things if your class was loaded from a non-file location.
|
Best solution for me:
```
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
```
This should solve the problem with spaces and special characters.
|
How to get the path of a running JAR file?
|
[
"",
"java",
"path",
"jar",
"executable-jar",
""
] |
Does anyone know of a good, extensible source code analyzer that examines JavaScript files?
|
In the interest of keeping this question up-to-date, there is a fork of JSLint called [JSHint](http://jshint.com/). An explanation of why JSHint was created can be found [here](http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/), but to summarize:
> JSHint is a fork of JSLint, the tool
> written and maintained by Douglas
> Crockford. JSLint served me well for
> quite some time but in the past few
> months it has gotten uncomfortably
> opinionated and hostile towards your
> code. It is quickly transforming from
> a tool that helps developers to
> prevent bugs to a tool that makes sure
> you write your code like Douglas
> Crockford.
|
[JSLint](http://www.jslint.com/) has historically been the main tool for this, but several more now exist:
* [JSHint](http://jshint.com/) - a fork of JSLint that is said to be a little less opinionated
* [Closure Linter](https://developers.google.com/closure/utilities/) - a linter that checks against the [Google Javascript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
* [ESLint](https://github.com/eslint/eslint) - a more flexible tool, but newer, and not yet as stable.
|
JavaScript Source Code Analyzer
|
[
"",
"javascript",
"code-analysis",
""
] |
I have a linq to sql database. Very simplified we have 3 tables, Projects and Users. There is a joining table called User\_Projects which joins them together.
I already have a working method of getting `IEnumberable<Project>` for a given user.
```
from up in User_Projects
select up.Project;
```
Now I want to get the projects the user *isn't* involved with. I figured the except method of IEnumerable would be pretty good here:
```
return db.Projects.Except(GetProjects());
```
That compiles, however I get a runtime error: "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."
Is there any way to get around this?
---
## Update:
A few views but no answers :p
I have tried this:
```
IEnumerable<Project> allProjects = db.Projects;
IEnumerable<Project> userProjects = GetProjects();
return allProjects.Except(GetProjects());
```
I know it's essentially the same as the original statement - but now i dont get a runtime error. Unfortunately, it doesn't really do the except part and just returns all the projects, for some reason
|
Linq to Sql doesn't understand how to work with an arbitrary in-memory sequence of objects. You need to express this in relational terms, which works on IDs:
```
var userProjectIds =
from project in GetProjects()
select project.ProjectId;
var nonUserProjects =
from project in db.Projects
where !userProjectIds.Contains(project.ProjectId)
select project;
```
|
You could try something simple like
```
User u = SomeUser;
from up in User_Projects
where up.User != u
select up.Project;
```
|
IEnumerable.Except wont work, so what do I do?
|
[
"",
"c#",
"linq",
""
] |
I need a 2d political map of the world on which I will draw icons, text, and lines that move around. Users will interact with the map, placing and moving the icons, and they will zoom in and out of the map.
The Google Maps interface isn't very far from what I need, but this is NOT web related; it's a Windows MFC application and I want to talk to a C++ API for a map that lives in the application, not a web interface. Ideally I don't want a separate server, either, and any server MUST run locally (not on the Internet). What canned map package or graphics library should I use to do this? I have no graphics programming experience.
This is strictly 2D, so I don't think something like Google Earth or WorldWind would be appropriate. Good vector graphics support would be cool, and easy drawing of bitmaps is important.
All the canned options seem web oriented. SDL is about all I know of for flexible canvas programming, but it seems like making my own map would be a lot of work for what is probably a common problem. Is there anything higher level? Maybe there's a way to interact with an adobe Flash object? I'm fairly clueless.
|
Perhaps:
<http://www.codeplex.com/SharpMap>
ESRI MapObjects
<http://www.esri.com/software/mapobjects/index.html>
ESRI MapObjects LT
<http://www.esri.com/software/mapobjectslt/index.html>
See
<http://www.esri.com/software/mapobjectslt/about/mo_vs_lt.html>
for a comparison of the two MapObjects feature sets.
ESRI may have a replacement to the MapObjects libraries
|
You might want to try the [Mapnik C++/Python GIS Toolkit](http://www.mapnik.org/).
You can take a look at the [Marble Widget](http://edu.kde.org/marble/#developers), which is part of KDE's Marble project. There are Windows binaries for this, too, but they might be dependent on Qt.
|
Need a client-side interactive 2D world map: best map package? Or best C++ graphics/canvas library to make one?
|
[
"",
"c++",
"graphics",
"google-maps",
"canvas",
"sdl",
""
] |
I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code.
What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item.
Then you go off and may display some DisplayMember and a ValueMember and so on.
If I want to retrieve that value later I need to typecast my object back to what it was. Like with strings getting the value takes
```
string value = (string)combobox1.SelectedItem;
```
Since there are generics in the Framework for quite some time now, I still wonder why in the Hell not one control from the standard toolbox is generic.
I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object. But everytime I need to access that object I then need another typecast.
Why cant I just create a ComboBox or ListView with items of type ListViewItem
Am I missing something here or is this just another example of not perfectly well thought through controls?
|
While the criticism of "didn't use generics" can't be fairly applied to controls developed before their existence... one must wonder about WPF controls (new in .NET 3.0, after generics in .NET 2.0).
I checked out the [AddChild](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.addchild.aspx) method in [ComboBox](http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox_members.aspx). It takes an object parameter (ugh).
This control is intended to be used primarily via XAML. Was this done this way because there is no way to specify a type parameter in XAML? (aside, is there no way to specify a type parameter in XAML?)
Sorry to have no definitive "Why" answer, just sharing the common misery of needing to cast when working with the UI.
|
I dont think you're missing anything.
It's just that these classes were created back in the pre-Generics days, and WinForms is simply not cutting edge enough for MS to spend a lot of time changing or extending the API.
|
Strongly Typed Controls in .NET
|
[
"",
"c#",
".net",
"winforms",
"generics",
""
] |
I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using:
```
SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
```
|
```
WHERE
DateDiff(d, Received, GETDATE()) = 0
```
Edit: As lined out in the comments to this answer, that's not an ideal solution. Check the other answers in this thread, too.
|
If you just want to find all the records where the Received Date is today, and there are records with future Received dates, then what you're doing is (very very slightly) wrong... Because the Between operator allows values that are equal to the ending boundary, so you could get records with Received date = to midnight tomorrow...
If there is no need to use an index on Received, then all you need to do is check that the date diff with the current datetime is 0...
```
Where DateDiff(day, received, getdate()) = 0
```
This predicate is of course not SARGable so it cannot use an index...
If this is an issue for this query then, assuming you cannot have Received dates in the future, I would use this instead...
```
Where Received >= DateAdd(day, DateDiff(Day, 0, getDate()), 0)
```
If Received dates can be in the future, then you are probably as close to the most efficient as you can be... (Except change the Between to a >= AND < )
|
Best way to check for current date in where clause of sql query
|
[
"",
"sql",
"t-sql",
"stored-procedures",
"performance",
""
] |
I use an SQL statement to remove records that exist on another database but this takes a very long time.
Is there any other alternative to the code below that can be faster? Database is Access.
email\_DB.mdb is from where I want to remove the email addresses that exist on the other database (table Newsletter\_Subscribers)
customers.mdb is the other database (table Customers)
```
SQLRemoveDupes = "DELETE FROM Newsletter_Subscribers WHERE EXISTS (select * from [" & strDBPath & "Customers].Customers " _
& "where Subscriber_Email = Email or Subscriber_Email = EmailO)"
NewsletterConn = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & strDBPath & "email_DB.mdb"
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = NewsletterConn
MM_editCmd.CommandText = SQLRemoveDupes
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
Set MM_editCmd = Nothing
```
EDIT: Tried the SQL below from one of the answers but I keep getting an error when running it:
SQL: DELETE FROM Newsletter\_Subscribers WHERE CustID IN (select CustID from [" & strDBPath & "Customers].Customers where Subscriber\_Email = Email or Subscriber\_Email = EmailO)
I get a "Too few parameters. Expected 1." error message on the Execute line.
|
I would use **WHERE Subscriber\_Email IN (Email, Email0)** as the WHERE clause
```
SQLRemoveDupes = "DELETE FROM Newsletter_Subscribers WHERE EXISTS " & _
(select * from [" & strDBPath & "Customers].Customers where Subscriber_Email IN (Email, EmailO)"
```
I have found from experience that using an OR predicate in a WHERE clause can be detrimental in terms of performance because SQL will have to evaluate each clause separately, and it might decide to ignore indexes and use a table scan. Sometime it can be better to split it into two separate statements. (I have to admit I am thinking in terms of SQL Server here, but the same may apply to Access)
```
"DELETE FROM Newsletter_Subscribers WHERE EXISTS " & _
(select * from [" & strDBPath & "Customers].Customers where Subscriber_Email = Email)"
"DELETE FROM Newsletter_Subscribers WHERE EXISTS " & _
(select * from [" & strDBPath & "Customers].Customers where Subscriber_Email = EmailO)"
```
|
Assuming there's an ID-column present in the Customers table, the following change in SQL should give better performance:
"DELETE FROM Newsletter\_Subscribers WHERE ID IN (select ID from [" & strDBPath & "Customers].Customers where Subscriber\_Email = Email or Subscriber\_Email = EmailO)"
PS. The ideal solution (judging from the column names) would be to redesign the tables and code logic of inserting emails in the first place. DS
|
Improve asp script performance that takes 3+ minutes to run
|
[
"",
"sql",
"asp-classic",
""
] |
> Write a class ListNode which has the following properties:
>
> * int value;
> * ListNode \*next;
>
> Provide the following functions:
>
> * ListNode(int v, ListNode \*l)
> * int getValue();
> * ListNode\* getNext();
> * void insert(int i);
> * bool listcontains(int j);
>
> Write a program which asks the user to enter some integers and stores them as
> ListNodes, and then asks for a number which it should seek in the list.
Here is my code:
```
#include <iostream>
using namespace std;
class ListNode
{
private:
struct Node
{
int value;
Node *next;
} *lnFirst;
public:
ListNode();
int Length();
void DisplayList();
void Insert( int num );
bool Contains( int num );
int GetValue( int num );
};
ListNode::ListNode()
{
lnFirst = NULL;
}
int ListNode::Length()
{
Node *lnTemp;
int intCount = 0;
for( lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )
{
intCount++;
}
return intCount;
}
void ListNode::DisplayList()
{
Node *lnTemp;
for( lnTemp = lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )
cout<<endl<<lnTemp->value;
}
void ListNode::Insert(int num)
{
Node *lnCurrent, *lnNew;
if( lnFirst == NULL )
{
lnFirst = new Node;
lnFirst->value = num;
lnFirst->next = NULL;
}
else
{
lnCurrent = lnFirst;
while( lnCurrent->next != NULL )
lnCurrent = lnCurrent->next;
lnNew = new Node;
lnNew->value = num;
lnNew->next = NULL;
lnCurrent->next = lnNew;
}
}
bool ListNode::Contains(int num)
{
bool boolDoesContain = false;
Node *lnTemp,*lnCurrent;
lnCurrent = lnFirst;
lnTemp = lnCurrent;
while( lnCurrent!=NULL )
{
if( lnCurrent->value == num )
{
boolDoesContain = true;
return boolDoesContain;
}
lnTemp = lnCurrent;
lnCurrent = lnCurrent->next;
}
return boolDoesContain;
}
int ListNode::GetValue(int num)
{
Node *lnTemp;
int intCount = 1;
for( lnTemp=lnFirst; lnTemp != NULL; lnTemp = lnTemp->next )
{
if (intCount == num)
{
return lnTemp->value;
}
intCount++;
}
}
int main()
{
cout << "Input integers below. Input the integer -1 to stop inputting.\n\n";
ListNode lnList;
int intNode = 1, intInput = 0;
while (intInput != -1) {
cout << "Please input integer number " << intNode << ": "; cin >> intInput;
intNode++;
if (intInput != -1) { lnList.Insert(intInput); }
}
lnList.DisplayList();
cout << "\n\n";
int intListLength = lnList.Length();
cout << "Which value do you wish to recall? (Between 1 and " << intListLength << "): "; cin >> intNode;
if ( intNode >= 1 && intNode <= intListLength ) {
cout << "Value at position " << intNode << " is " << lnList.GetValue(intNode) << ".";
} else {
cout << "No such position in the list. Positions run from 1 to " << intListLength << ". You asked for " << intNode << ".";
}
cout << "\n\nCheck if the following value is in the list: "; cin >> intNode;
bool IsThere = lnList.Contains(intNode);
if (IsThere) {
cout << intNode << " is in the list.";
} else {
cout << intNode << " is not in the list.";
}
cout << "\n\n";
system("pause");
return 0;
}
```
Where can we improve this?
|
What unwind and ckarmann say. Here is a hint, i implement listcontains for you to give you the idea how the assignment could be meant:
```
class ListNode {
private:
int value;
ListNode * next;
public:
bool listcontains(int v) {
// does this node contain the value?
if(value == v) return true;
// was this the last node?
if(next == 0) return false;
// return whether nodes after us contain the value
return next->listcontains(v);
}
};
```
So, you only have the head of the list, which links to the next node in turn. The tail will have `next == 0`;
|
I think you misunderstood the requested design. The ListNode class is supposed to be a node, not a list containing nodes.
I would advise you not to put several commands on a single ligne, like this:
```
cout << "Please input integer number " << intNode << ": "; cin >> intInput;
```
This is simply confusing.
|
C++ Pointers / Lists Implementation
|
[
"",
"c++",
"list",
"pointers",
""
] |
I query all security groups in a specific domain using
```
PrincipalSearchResult<Principal> results = ps.FindAll();
```
where ps is a PrincipalSearcher.
I then need to iterate the result (casting it to a GroupPrincipal first ) and locate the ones that contains a specific string in the notes field.
But the Notes field from AD is appearently not a public field in the GroupPrincipal class, doh.
What am I doing wrong ?
Update:
I have given up on this one. It seems like there is no way to access that pesky Notes field.
|
I have been returning to this challange over and over again, but now I have finally given up. It sure looks like that property is inaccessible.
|
You can access the 'notes' field of a directory entry as such:
```
// Get the underlying directory entry from the principal
System.DirectoryServices.DirectoryEntry UnderlyingDirectoryObject =
PrincipalInstance.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry;
// Read the content of the 'notes' property (It's actually called info in the AD schema)
string NotesPropertyContent = UnderlyingDirectoryObject.Properties["info"].Value;
// Set the content of the 'notes' field (It's actually called info in the AD schema)
UnderlyingDirectoryObject.Properties["info"].Value = "Some Text"
// Commit changes to the directory entry
UserDirectoryEntry.CommitChanges();
```
Took a little bit of hunting - I had assumed the notes property was indeed called 'notes', ADSIEdit to the rescue!
|
How to access the notes field on a GroupPrincipal object
|
[
"",
"c#",
"active-directory",
""
] |
I've been working a little with DevExpress CodeRush and Refactor! Pro this week, and I picked up a commentor plug-in that will automatically generate comments as you type code.
I don't want to go into how good a job it does of picking out basic meaning (pretty good, actually) but it's default implementation does raise a question.
By default, typing a } character to close a block will result in the plugin adding a comment like the following...
```
using(MyType myType = new MyType())
{
myType.doWork();
} // using
```
(i.e. adding a comment to the closing brace labelling where it was opened.)
While I can see that there are instances where this behaviour may be of great use, I feel that the resultant code looks very untidy with all the additional commenting.
I was wondering what other people;'s take on this kind of comment was. Not just from an academic standpoint, but if I get a good number of negative comments about them I can decide whether to inflict them upon my co-workers or strip them out.
|
I think comments like that are useless, unless of course the code is awful. With proper formatting of code it's not difficult to see where a block starts and where a block ends because usually those blocks are indented.
Edit:
If a procedure is so big that is not readily apparent what block of code is being closed by a brace, then there should already be more descriptive comments describing the procedure anyways and these comments would just be clutter.
|
I find the idea of a plugin that genrates comments from code rather useless. If it can be inferred by the machine then it can also be inferred by anybody reading it. The comments are extremely likely to be totally redundant.
I feel that those closing brace comment is messy, it gives information that is better provided directly by the IDE if the individual wants it.
|
C# comments on closing {}
|
[
"",
"c#",
"devexpress",
"comments",
""
] |
Say I have 2 tables: Customers and Orders. A Customer can have many Orders.
Now, I need to show any Customers with his latest Order. This means if a Customer has more than one Orders, show only the Order with the latest Entry Time.
This is how far I managed on my own:
```
SELECT a.*, b.Id
FROM Customer a INNER JOIN Order b ON b.CustomerID = a.Id
ORDER BY b.EntryTime DESC
```
This of course returns all Customers with one or more Orders, showing the latest Order first for each Customer, which is not what I wanted. My mind was stuck in a rut at this point, so I hope someone can point me in the right direction.
For some reason, I *think* I need to use the MAX syntax somewhere, but it just escapes me right now.
**UPDATE:** After going through a few answers here (there's a lot!), I realized I made a mistake: I meant **any** Customer with his latest record. That means if he does not have an Order, then I do not need to list him.
**UPDATE2:** Fixed my own SQL statement, which probably caused no end of confusion to others.
|
I don't think you do want to use MAX() as you don't want to group the OrderID. What you need is an ordered sub query with a SELECT TOP 1.
```
select *
from Customers
inner join Orders
on Customers.CustomerID = Orders.CustomerID
and OrderID = (
SELECT TOP 1 subOrders.OrderID
FROM Orders subOrders
WHERE subOrders.CustomerID = Orders.CustomerID
ORDER BY subOrders.OrderDate DESC
)
```
|
Something like this should do it:
```
SELECT X.*, Y.LatestOrderId
FROM Customer X
LEFT JOIN (
SELECT A.Customer, MAX(A.OrderID) LatestOrderId
FROM Order A
JOIN (
SELECT Customer, MAX(EntryTime) MaxEntryTime FROM Order GROUP BY Customer
) B ON A.Customer = B.Customer AND A.EntryTime = B.MaxEntryTime
GROUP BY Customer
) Y ON X.Customer = Y.Customer
```
This assumes that two orders for the same customer may have the same EntryTime, which is why `MAX(OrderID)` is used in subquery `Y` to ensure that it only occurs once per customer. The `LEFT JOIN` is used because you stated you wanted to show all customers - if they haven't got any orders, then the LatestOrderId will be `NULL`.
Hope this helps!
--
UPDATE :-) This shows only customers with orders:
```
SELECT A.Customer, MAX(A.OrderID) LatestOrderId
FROM Order A
JOIN (
SELECT Customer, MAX(EntryTime) MaxEntryTime FROM Order GROUP BY Customer
) B ON A.Customer = B.Customer AND A.EntryTime = B.MaxEntryTime
GROUP BY Customer
```
|
SQL Statement Help - Select latest Order for each Customer
|
[
"",
"sql",
"sql-server-2005",
""
] |
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.
L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.
|
You can have your users run the system from a startup script, and that script can fix the pythonpath ahead of time to put your versions first. For example if you put CherryPy, SQLAlchemy, etc. in an "external" subdirectory, you could try:
```
# startproj.sh
script_path=`dirname $0`
export PYTHONPATH=${script_path}/external;${PYTHONPATH}
exec ${script_path}/projstartup.py
```
|
You could try `freeze.py`, see <http://wiki.python.org/moin/Freeze> for more details.
|
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
|
[
"",
"python",
"linux",
"deployment",
""
] |
I'm quite confused about the basic concepts of a Hash table. If I were to code a hash how would I even begin? What is the difference between a Hash table and just a normal array?
Basically if someone answered this question I think all my questions would be answered:
If I had 100 randomly generated numbers (as keys), how would I implement a hash table and why would that be advantageous over an array?
Psuedo-code or Java would be appreciated as a learning tool...
|
The answers so far have helped to define hash tables and explain some theory, but I think an example may help you get a better feeling for them.
*What is the difference between a hash table and just a normal array?*
A hash table and an array are both structures that allow you to store and retrieve data. Both allow you to specify an *index* and retrieve a value associated with it. The difference, as Daniel Spiewak noted, is that the indices of an array are *sequential*, while those of a hash table are based on the *value of the data* associated with them.
*Why would I use a hash table?*
A hash table can provide a very efficient way to search for items in large amounts of data, particularly data that is not otherwise easily searchable. ("Large" here means [*ginormous*](http://en.wiktionary.org/wiki/ginormous), in the sense that it would take a long time to perform a sequential search).
*If I were to code a hash how would I even begin?*
No problem. The simplest way is to invent an arbitrary mathematical operation that you can perform on the data, that returns a number `N` (usually an integer). Then use that number as the index into an array of "buckets" and store your data in bucket #`N`. The trick is in selecting an operation that tends to place values in different buckets in a way that makes it easy for your to find them later.
**Example:** A large mall keeps a database of its patrons' cars and parking locations, to help shoppers remember where they parked. The database stores `make`, `color`, `license plate`, and `parking location`. On leaving the store a shopper finds his car by entering the its make and color. The database returns a (relatively short) list of license plates and parking spaces. A quick scan locates the shopper's car.
You could implement this with an SQL query:
```
SELECT license, location FROM cars WHERE make="$(make)" AND color="$(color)"
```
If the data were stored in an array, which is essentially just a list, you can imagine implementing the query by scanning an array for all matching entries.
On the other hand, imagine a hash rule:
> Add the ASCII character codes of all the letters in the make and color, divide by 100, and use the remainder as the hash value.
This rule will convert each item to a number between 0 and 99, essentially *sorting* the data into 100 buckets. Each time a customer needs to locate a car, you can hash the make and color to find the *one* bucket out of 100 that contains the information. You've immediately reduced the search by a factor of 100!
Now scale the example to huge amounts of data, say a database with millions of entries that is searched based on tens of criteria. A "good" hash function will distribute the data into buckets in a way that minimizes any additional searching, saving a significant amount of time.
|
First, you have to understand a what a hash function is.
A hash function is a function that takes a key (for example, an string of arbritrary length) and returns a number *as unique as possible*. The same key must always return the same hash. A really simple string hashing function in java might look like
```
public int stringHash(String s) {
int h = s.length();
for(char c : s.toCharArray()) {
h ^= c;
}
return h;
}
```
You can study a good hash function at <http://www.azillionmonkeys.com/qed/hash.html>
Now, the hash map uses this hash value to place the value into an array. Simplistic java method:
```
public void put(String key, Object val) {
int hash = stringHash(s) % array.length;
if(array[hash] == null) {
array[hash] = new LinkedList<Entry<String, Object> >();
}
for(Entry e : array[hash]) {
if(e.key.equals(key)){
e.value = val;
return;
}
}
array[hash].add(new Entry<String, Object>(key, val));
}
```
(This map enforces unique keys. Not all maps do.)
It is possible for two different keys to hash to the same value, or two different hashes to map to the same array index. There exists many techniques for dealing with this. The simplest is to use a linked list (or binary tree) for each array index. If the hash function is good enough, you will never need a linear search.
Now to look up a key:
```
public Object get(String key) {
int hash = stringHash(key) % array.length;
if(array[hash] != null) {
for(Entry e : array[hash]) {
if(e.key.equals(key))
return e.value;
}
}
return null;
}
```
|
The fundamentals of Hash tables?
|
[
"",
"java",
"hashtable",
""
] |
I'm looking for a PHP (with MYSQL) nested sets class with all needed functions.
For example:
createLeftNode, createRightNode,createRootNode, createSubNode,deleteNode and **moveTree**. Not only 1 left, 1 right, 1 up and 1 down but also a part of a tree in a nother tree.
Thanks!
|
Well nested sets are great if you are working with hierarchical data. It's much more complex to implement it only with php arrays especially if you want to save these information in a database.
you could try this on. Never used it but after a short code screening it looks almost complete.
<http://www.edutech.ch/contribution/nstrees/index.php>
|
look at the [nested behavior](http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/behaviors.html#nesting-behaviors) of Doctrine
|
Searching for the best PHP nested sets class (PEAR class excluded)
|
[
"",
"php",
"class",
"nested",
"set",
"nested-sets",
""
] |
I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack.
Is there anyway to access objects allocated on the heap? What mechanisms does java enforce to guarantee that the right method can access the right data off the heap?
It seems like if you were crafty and maybe even manipulate the java bytecode during runtime, that you might be able to manipulate data off the heap when you aren't supposed to?
|
There is no instruction in the JVM instruction set that gives arbitrary access to the heap. Hence, bytecode manipulation will not help you here.
The JVM also has a verifier. It checks the code of every method (as a class is being loaded) to verify that the method does not try to pop more values off the execution stack than what it had pushed onto it. This ensures that a method cannot "see" the objects pointed by its calling method.
Finally, local variables are stored in a per-method array (known as the "local variables array"). Again, the verifier makes sure that every read/write instruction from-/to- that array specifies an index that is less than the size of the array. Note that these JVM instructions can only specify a constant index. They cannot take a computed value and use it as an index.
So to recap, the answer is No.
|
All objects in Java are located on the heap. I'm not quite sure what you mean by "access objects from the heap". The only things stored on the stack are the list of functions which called into the current context and their local variables and parameters. All local variables and parameters are either primitive types or references.
If you allocate an object using `new` (which is the only way to allocate non-primitive types; yes this includes array types), then the object is allocated on the heap, and a reference to that object is stored on either the stack or the heap, depending on if the reference is stored in a local variable/parameter or as a member of another object.
When passed as parameters to functions, all objects are passed by reference - if the function modifies the parameter, the original object is also modified. Identically, one could also say that the object references are passed by value - if you change a parameter to refer to a new object, it will continue to refer to that object for the duration of the function, but the original object which was passed in will still refer to whatever it referred to before. Primitive types are also passed by value.
|
General Question: Java has the heap and local stack. Can you access any object from the heap?
|
[
"",
"java",
"jvm",
"stack",
"heap-memory",
""
] |
I have some HTML and jQuery that slides a `div` up and down to show or hide` it when a link is clicked:
```
<ul class="product-info">
<li>
<a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
```
```
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
}
```
My question is: How do I use `preventDefault()` to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?
I can't figure out the right syntax, I just keep getting an error saying
> preventDefault() is not a function.
|
Try something like:
```
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
```
Here is the page about that in the [jQuery documentation](http://learn.jquery.com/events/event-basics/#preventdefault)
|
Set the **`href`** attribute as `href="javascript:;"`
```
<ul class="product-info">
<li>
<a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
```
|
preventDefault() on an <a> tag
|
[
"",
"javascript",
"jquery",
""
] |
Is there any way to direct C# to ignore `NullReferenceException` (or any specific exception for that matter) for a set of statements.
This is useful when trying to read properties from a deserialized object that may contain many null objects in it.
Having a helper method to check for null could be one way but I'm looking for something close to 'On Error Resume Next' (from VB) at a block of statement level.
EDIT:Try-Catch will skip the succeeding statements on exception
```
try
{
stmt 1;// NullReferenceException here, will jump to catch - skipping stmt2 and stmt 3
stmt 2;
stmt 3;
}
catch (NullReferenceException) { }
```
For Example: I'm deserializing an XML message to an object and then try to access a property like
```
Message.instance[0].prop1.prop2.ID
```
now prop2 could be a null object (because it doesn't exists in XML Message - an optional element in XSD). right now I need to check for null for each element in the hierarchy before accessing the leaf element. i.e I've to check if instance[0], prop1, prop2 are not null, before accessing 'ID'.
Is there a better way that avoids null-checking for each element in the hierarchy?
|
now I'm using delegate and NullReferenceException handling
```
public delegate string SD();//declare before class definition
string X = GetValue(() => Message.instance[0].prop1.prop2.ID); //usage
//GetValue defintion
private string GetValue(SD d){
try
{
return d();
}
catch (NullReferenceException) {
return "";
}
}
```
Thanks to
[Try-catch every line of code without individual try-catch blocks](https://stackoverflow.com/questions/117173/c-try-catch-every-line-of-code-without-individual-try-catch-blocks)
for the idea
|
In short: no. Null-check the reference before trying to use it. One useful trick here might be C# 3.0 extension methods... they allow you to *appear to* invoke something on a null reference without error:
```
string foo = null;
foo.Spooky();
...
public static void Spooky(this string bar) {
Console.WriteLine("boo!");
}
```
Other than that - perhaps some use of the conditional operator?
```
string name = obj == null ? "" : obj.Name;
```
|
Ignore NullReferenceException when reading object properties
|
[
"",
"c#",
".net",
"exception",
"language-features",
"serialization",
""
] |
I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices.
If not, how do I detect a mobile device? My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device.
Any advice for me?
EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.
|
I'm not sure how the IPhone/iPod Touch declare themselves when requesting the stylesheet, but for most, using
```
<style type="text/css">
@media handheld
{
/* handheld styles */
}
</style>
```
should do the trick. It works in the same way @media print does (or doesn't).
For a complete list of media types, see [here.](http://www.w3.org/TR/CSS2/media.html)
|
Mobile browsers are a real hodge-podge in terms of what they support, whether they follow the "media" attribute on your styles, etc.
I would say aim for [progressive enhancement](http://www.alistapart.com/articles/progressiveenhancementwithcss) (that's one of a series of articles) and make sure that if the browser only understands plain HTML, your content is still viewable and in the right order - for example, you want your main content to appear before the sidebar in the code, since the main content is more important.
A [decent looking resource](http://mobiforge.com/) was mentioned in the article above.
|
Web Site Designing for Mobile
|
[
"",
"c#",
"css",
"mobile",
""
] |
I have this code
```
<?php
session_start();
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","root","geheim");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if($cmd=="GetAuctionData")
{
echo "<table border='1' width='100%'>
<tr>
<th>Username</th>
<th>Start Date</th>
<th>Description</th>
</tr>";
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo "<tr>
<td>".$row['USERNAME']."</td>
<td>".$row['ARTICLE_NO']."</td>
<td>".$row['ARTICLE_NAME']."</td>
<td>".$row['SUBTITLE']."</td>
<td>".$row['CURRENT_BID']."</td>
<td>".$row['START_PRICE']."</td>
<td>".$row['BID_COUNT']."</td>
<td>".$row['QUANT_TOTAL']."</td>
<td>".$row['QUANT_SOLD']."</td>
<td>".$row['ACCESSSTARTS']."</td>
<td>".$row['ACCESSENDS']."</td>
<td>".$row['ACCESSORIGIN_END']."</td>
<td>".$row['USERNAME']."</td>
<td>".$row['BEST_BIDDER_ID']."</td>
<td>".$row['FINISHED']."</td>
<td>".$row['WATCH']."</td>
<td>".$row['BUYITNOW_PRICE']."</td>
<td>".$row['PIC_URL']."</td>
<td>".$row['PRIVATE_AUCTION']."</td>
<td>".$row['AUCTION_TYPE']."</td>
<td>".$row['ACCESSINSERT_DATE']."</td>
<td>".$row['ACCESSUPDATE_DATE']."</td>
<td>".$row['CAT_1_ID']."</td>
<td>".$row['CAT_2_ID']."</td>
<td>".$row['ARTICLE_DESC']."</td>
<td>".$row['COUNTRYCODE']."</td>
<td>".$row['LOCATION']."</td>
<td>".$row['CONDITIONS']."</td>
<td>".$row['REVISED']."</td>
<td>".$row['PAYPAL_ACCEPT']."</td>
<td>".$row['PRE_TERMINATED']."</td>
<td>".$row['SHIPPING_TO']."</td>
<td>".$row['FEE_INSERTION']."</td>
<td>".$row['FEE_FINAL']."</td>
<td>".$row['FEE_LISTING']."</td>
<td>".$row['PIC_XXL']."</td>
<td>".$row['PIC_DIASHOW']."</td>
<td>".$row['PIC_COUNT']."</td>
<td>".$row['ITEM_SITE_ID']."</td>
<td>".$row['STARTS']."</td>
<td>".$row['ENDS']."</td>
<td>".$row['ORIGIN_END']."</td>
</tr>
<tr><td></td></tr>";
}
echo "</table>";
echo "<img src=".$row['PIC_URL'].">";
}
mysql_close($con);
?>
```
Here is the generated html:
```
<table border='1' width='100%'>
<tr>
<th>Username</th>
<th>Start Date</th>
<th>Description</th>
</tr><tr>
<td>fashionticker1</td>
<td>220288560247</td>
<td>Ed Hardy Herren Shirt Rock & Roll Weiss XXL Neu & OVP</td>
<td></td>
<td>0.00</td>
<td>49.00</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>1.10.2008 16:22:09</td>
<td>6.10.2008 16:22:09</td>
<td>6.10.2008 16:22:09</td>
<td>fashionticker1</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>59.00</td>
<td>http://storage.supremeauction.com/flash/ebay2/10/49/76/10497654/13895964e.jpg</td>
<td>0</td>
<td>1</td>
<td>6.10.2008 16:21:47</td>
<td>6.10.2008 16:28:31</td>
<td>32315</td>
<td>0</td>
<td><!-- +++++++++++++++++++++++++ Bitte ändern Sie im eigenen Interesse nichts an diesem Code! ++++++++++++++++++++++++ -->
<!-- +++++++++++++++++++++++++ Das kann massive Fehldarstellungen ihrer Auktion zur Folge haben! +++++++++++++++++++ -->
<!-- +++++++++++++++++++++++++ ++++++++++++++++++++++++++ Ihr Supreme Team +++++++++++++++++++++++++++++++++++++++++ -->
</td>
<td>
<br>
<br>
<style ty</td>
<td>float: right;
</td>
<td>margin: 0px;
</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>padding:5px;
</td>
<td>0.00</td>
<td>0.00</td>
<td>0.00</td>
<td>0</td>
<td>0</td>
<td>font-size: 12px;
</td>
<td>color: #333333;
}
#h</td>
<td>0000-00-00 00:00:00</td>
<td>0000-00-00 00:00:00</td>
<td>0000-00-00 00:00:00</td>
</tr>
<tr><td></td></tr></table><img src=>
```
Whatever I do, I can not get an image to display, and when PIC\_URL is empty, it only displays a placeholder image above the table, and I want it below.
|
It should be:
```
echo "<img src=\"".$row['PIC_URL']."\">";
```
|
`<style ty</td>` looks like the problem to me.
|
cant display image from database outside of table in php
|
[
"",
"php",
"html",
""
] |
I'm having trouble trying to optimize the following query for sql server 2005. Does anyone know how could I improve it. Each one of the tables used there have about 40 million rows each. I've tried my best trying to optimize it but I manage to do the exact opposite.
Thanks
```
SELECT
cos
, SIN
FROM
ConSisHis2005
union all
SELECT
cos
, SIN
FROM
ConSisHis2006
union all
SELECT
cos
, SIN
FROM
ConSisHis2007
UNION ALL
SELECT
cos
, SIN
FROM
ConSisHis2008
```
Maybe I should have said something else about the schema, all the tables used here are historical tables, they are not referenced to any other table. And theres already an index for cos and SIN. I was just wondering if there was any other way to optimize the query... as you can imagine 160millon records are hard to get :s
|
It seems that the query is just combining the separated history tables into a single result set containing all the data. In that case the query is already optimal.
|
Another approach would be to tackle the problem of why do you need to have all the 160 million rows? If you are doing some kind of reporting can you create separate reporting tables that already have some of the data aggregated. Or do you actually need a data warehouse to support your reporting needs.
|
Optimizing unions
|
[
"",
"sql",
"sql-server-2005",
"optimization",
""
] |
I have the following problem:
I open the dialog, open the SIP keyboard to fill the form and then minimize the SIP. Then when I close the current dialog and return to the main dialog the SIP keyboard appears again. Does anyone know how could I show/hide SIP keyboard programatically or better what could be done to solve the described problem. Once the user minimizes the keyboard it should not appear on the screen on dialog switching.
Thanks!
|
We use [SHSipPreference](http://msdn.microsoft.com/en-us/library/aa458034.aspx) to control the display of the SIP in our applications. I know it works with MFC and it sets the state of the SIP for the window so you can set it once and you know the SIP state will be restored to your set state every time the window is shown.
I've never heard of SipShowIM but I did see on the MSDN page linked:
> The standard method of showing and
> hiding the SIP (SIPShowIM) exhibits
> some problems in MFC dialogs.
|
You'll want to call **SipShowIM**() in coredll. See this MSDN article:
<http://msdn.microsoft.com/en-us/library/ms838341.aspx>
|
how to show/hide SIP on Pocket PC
|
[
"",
"c++",
"windows-mobile",
"pocketpc",
""
] |
I am using the following code to set a tray icon in Windows and Linux. It works wonderful in Windows and works okay in Linux. In Linux (Ubuntu) I have my panel set to be (somewhat) transparent and when I add a GIF (with a transparent background) the background of the icon shows up all grey and ugly (see image, green diamond "!")....Any ideas on how to make the GIF image I am adding "keep" its transparent background?
[alt text http://unarm.org/stackoverflow/panel\_task.jpg](http://unarm.org/stackoverflow/panel_task.jpg)
and the image I am using, if you'd like to test:
[alt text http://unarm.org/stackoverflow/green\_info.gif](http://unarm.org/stackoverflow/green_info.gif)
```
import java.awt.*;
import java.awt.event.*;
public class TrayFun {
static class ShowMessageListener implements ActionListener {
TrayIcon trayIcon;
String title;
String message;
TrayIcon.MessageType messageType;
ShowMessageListener(
TrayIcon trayIcon,
String title,
String message,
TrayIcon.MessageType messageType) {
this.trayIcon = trayIcon;
this.title = title;
this.message = message;
this.messageType = messageType;
}
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage(title, message, messageType);
}
}
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
if (SystemTray.isSupported()) {
final SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("green_info.png");
PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup);
trayIcon.setImageAutoSize(true);
MenuItem item = new MenuItem("Close");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
}
});
popup.add(item);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("Can't add to tray");
}
} else {
System.err.println("Tray unavailable");
}
}
};
EventQueue.invokeLater(runner);
}
}
```
|
Chances are this problem cannot be resolved. It depends on wether Java is doing a good job in creating the tray subwindow in Linux or not. If Jave does it wrong, transparency is already lost when the image is drawn.
1. What is the real background value of the icon you are using? Is it the gray tone shown above? Set it to purple to see if the transparency of the image is used (Java defaults to gray background) or not.
2. Make sure you tried both transparency options of PNG: transparent color index as well as alpha channel. Alpha channel is very common in Linux, not so in the Windows world.
3. The resolution of your icon is too small. Do it in 64x64 or better 128x128. AFAIK there is no standard resolution for tray icons, and even if so, it is certainly not 16x16.
4. Another format you could try is SVG. Only try that after making sure that the transparency of the image is the problem (see 1).
See here for background information on this issue:
<http://www.rasterman.com/index.php?page=News> (scroll down to 2 February 2006)
|
The problem lies in the sun.awt.X11.XTrayIconPeer.IconCanvas.paint() method!
Before painting, the icon background is amateurishly cleared by simply drawing a rectangle of IconCanvas’ background color, to allow image animations.
```
public void paint(Graphics g) {
if (g != null && curW > 0 && curH > 0) {
BufferedImage bufImage = new BufferedImage(curW, curH, BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = bufImage.createGraphics();
if (gr != null) {
try {
gr.setColor(getBackground());
gr.fillRect(0, 0, curW, curH);
gr.drawImage(image, 0, 0, curW, curH, observer);
gr.dispose();
g.drawImage(bufImage, 0, 0, curW, curH, null);
} finally {
gr.dispose();
}
}
}
}
```
see: <http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6453521>
|
java TrayIcon using image with transparent background
|
[
"",
"java",
"linux",
"panel",
"gnome",
"tray",
""
] |
What's the best way to do it in .NET?
I always forget what I need to `Dispose()` (or wrap with `using`).
EDIT: after a long time using `WebRequest`, I found out about customizing `WebClient`. Much better.
|
Following Thomas Levesque's comment [here](https://stackoverflow.com/questions/1469805/c-canonical-http-post-code/1474861#1474861), there's a simpler and more generic solution.
We create a `WebClient` subclass with timeout support, and we get all of [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx)'s goodness.
```
public class WebClientWithTimeout : WebClient
{
private readonly int timeoutMilliseconds;
public WebClientWithTimeout(int timeoutMilliseconds)
{
this.timeoutMilliseconds = timeoutMilliseconds;
}
protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result.Timeout = timeoutMilliseconds;
return result;
}
}
```
Sample usage:
```
public string GetRequest(Uri uri, int timeoutMilliseconds)
{
using (var client = new WebClientWithTimeout(timeoutMilliseconds))
{
return client.DownloadString();
}
}
```
|
Syncronous Way:
```
var request = HttpWebRequest.Create("http://www.contoso.com");
request.Timeout = 50000;
using (var response = request.GetResponse())
{
//your code here
}
```
You can also have the asynchronous way:
```
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
public class RequestState
{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] BufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
streamResponse = null;
}
}
class HttpWebRequest_BeginGetResponse
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
// Abort the request if the timer fires.
private static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
request.Abort();
}
}
}
static void Main()
{
try
{
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.ReadWriteTimeout = DefaultTimeout;
// Create an instance of the RequestState and assign the previous myHttpWebRequest
// object to its request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest;
// Start the asynchronous request.
IAsyncResult result =
(IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);
// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();
// Release the HttpWebResponse resource.
myRequestState.response.Close();
}
catch (WebException e)
{
Console.WriteLine("\nMain Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
Console.WriteLine("Press any key to continue..........");
}
catch (Exception e)
{
Console.WriteLine("\nMain Exception raised!");
Console.WriteLine("Source :{0} ", e.Source);
Console.WriteLine("Message :{0} ", e.Message);
Console.WriteLine("Press any key to continue..........");
Console.Read();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest myHttpWebRequest = myRequestState.request;
myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);
// Read the response into a Stream object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse = responseStream;
// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
catch (WebException e)
{
Console.WriteLine("\nRespCallback Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
allDone.Set();
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead(asyncResult);
// Read the HTML page and then print it to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
else
{
Console.WriteLine("\nThe contents of the Html page are : ");
if (myRequestState.requestData.Length > 1)
{
string stringContent;
stringContent = myRequestState.requestData.ToString();
Console.WriteLine(stringContent);
}
Console.WriteLine("Press any key to continue..........");
Console.ReadLine();
responseStream.Close();
}
}
catch (WebException e)
{
Console.WriteLine("\nReadCallBack Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
allDone.Set();
}
}
```
|
C#: Downloading a URL with timeout
|
[
"",
"c#",
"httpwebrequest",
"timeout",
"webrequest",
".net-3.0",
""
] |
So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.
I would like to use generics to create a general class for this scenario. Something like:
```
Adder<Double> adder = new Adder<Double>();
adder.add(10.0d, 10.0d); // = 20.0d
```
But, I cannot instantiate the generic type I pass in to my Adder class! So -- what to do?
|
Uh oh---generics are not C++ templates. Because of type erasure, the `Double` in your example won't even show through to the runtime system.
In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., `double add(double, double)`, `float add(float, fload)`, `BigDecimal add(BigDecimal, BigDecimal)`, etc.
|
I *think* you can do what you want, but I'm not sure, given the information you provided. It sounds as if you want some variation of the following:
```
public class Foob<T extends Number> {
public T doSomething(T t1, T t2) {
return null;
}
}
```
|
Java: Using generics to implement a class that operates on different kinds of numbers
|
[
"",
"java",
"generics",
""
] |
It's hard to put this into the title, so let me explain.
I have an application that uses Direct3D to display some mesh and directshow(vmr9 + allocator) to play some video, and then send the video frame as texture to the Direct3D portion to be applied onto the mesh. The application needs to run 24/7. At least it's allowed to be restarted every 24hours but not more frequent than that.
Now the problem is that directshow seems to be giving problem after a few hours of playback, either due to the codec, video driver or video file itself. At which point the application simply refuse playing anymore video. But the Direct3D portion is still running fine, mesh still displayed. Once the application is restarted, everything back to normal.
So, I'm thinking of splitting the 2 parts into 2 different process. So that when ever the video process failed to play video, at least I could restart it immediately, without loosing the Direct3D portion.
So here comes the actual question, whether it's possible to pass the texture from the video player to the direct3d process by passing the pointer, aka retrieve the texture of another process from pointer? My initial guess is not possible due to protected memory addressing.
I have TCP communication setup on both process, and let's not worry about communicating the pointer at this point.
This might be a crazy idea, but it will work wonder of it's ever possible
|
Yes you can do this with Direct3D 9Ex. This only works with Vista and you must use a Direct3DDevice9Ex. You can read about sharing [resources here.](http://msdn.microsoft.com/en-us/library/bb219800(VS.85).aspx)
|
> Now the problem is that directshow seems to be giving problem after a few hours of playback, either due to the codec, video driver or video file itself. At which point the application simply refuse playing anymore video.
Why not just fix this bug instead?
|
Pass texture using pointer across process
|
[
"",
"c#",
".net",
"directx",
"directshow",
"direct3d",
""
] |
Use case: 3rd party application wants to programatically monitor a text file being generated by another program. Text file contains data you want to analyze as it's being updated.
I'm finding a lot of answers to this question wrapped around FileSystemWatcher but let's say you are writing an application for a Windows machine and can't guarantee .NET is installed.
Are there any libraries out there available for this, or am I just going to have to roll my own solution then?
Thanks.
|
You can monitor a directory with [FindFirstChangeNotification](http://msdn.microsoft.com/en-us/library/aa364417.aspx) works on any windows.
It's efficent if you know where the file is - otherwise you can use the virtual driver/Filemon described below to check for changes anywhere on the system.
Example code [here](http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx)
|
A simpler solution could be to check the last modified time stamp of the file.
If you use the \_stat64() function to do this, it becomes a cross-platform solution.
Example code:
```
struct __stat64 fileinfo;
if(-1 != _stat64(filename, &fileinfo)
return fileinfo.st_mtime;
```
|
How do I Monitor Text File Changes with C++? Difficulty: No .NET
|
[
"",
"c++",
"file",
"monitoring",
""
] |
In an interview for a SQL DBA position a while back, I mentioned I prefer the SQL 2005 Management Studio app vs. the old 2000 versions of Enterprise Manager / Query Analyzer. The DBA who was interviewing me said that they had experienced some sort of database corruption in their 2000 databases when making changes from the 2005 MS, so they always use Enterprise Manager now.
He was a bit vague, but I got the impression he was talking about some sort of corruption experienced when making server-wide or database-level setting changes, and not just routine SQL updates or something.
Anyone heard of anything like this? I didn't end up taking that position, so I can't follow up to get more info.
|
It sounds like he was just was using that as an excuse for lack of experience with SQL 2005 Management Studio. DBAs hate change.
|
I have never encountered this, in almost three years of using SQL Management Studio 2005 to manage SQL 2000 databases. There are a few tasks I still bounce back into EntMan for, but I've never had a database encounter even the minutest bit of corruption. (And background: As a consultant, I'm managing about 45 different databases for both client and internal projects; most are heavily hit, and only about a dozen are SQL2005 databases.)
|
Is there danger of corruption in SQL Server 2000 databases when using SQL Server 2005 Management Studio?
|
[
"",
"sql",
"sql-server",
"ssms",
""
] |
I need a standard, Microsoft delivered, encryption library that works for both .NET 2.0 and C++. What would you suggest?
We find that AES is only offered in .NET 3.5 (and available in C++)
We find that Rijndael is used in .NET 2.0 but not available in the standard C++ libraries.
If I am wrong (very good chance), can you point me in the right direction?
Worst case scenario, I suppose I can call the Rijndael algorithm from .NET using PInvoke but I would rather have a native solution.
|
We successfully do a similar thing that I hope might help you:
### C++ CryptoAPI
* [CryptoAPI](http://msdn.microsoft.com/en-us/library/aa380239(VS.85).aspx) is pure Win32 (c/c++), native to all Microsoft OS's.
* Use [Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx) (`MS_ENHANCED_PROV`)
* Use [Triple DES](http://msdn.microsoft.com/en-us/library/aa382020(VS.85).aspx) (`CALG_3DES`) algorithm
### .NET TripleDes Provider
* Use [TripleDESCryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider(VS.80).aspx) on the .NET side.
### Side Notes
* We **avoid CAPICOM** like the plague as the deployment nightmares that come with it are not worth the hassle.
* Byte order on the .NET side can come into play at times. For example, to consume a key that is generated on the C++ (CryptoAPI) side, you need to reverse the byte array prior to using it within the TripleDESCryptoServiceProvider.
If you would like more details please leave a comment and I can give more. Happy crypto!
|
AES and Rijndael are essentially the same algorithm with a restriction on block size and cipher mode. So as long as you can live with the [restrictions](http://blogs.msdn.com/shawnfa/archive/2006/10/09/The-Differences-Between-Rijndael-and-AES.aspx) (which are not onerous) you can use them interchangeably.
|
Encryption algorithm/library for .NET 2.0 + C++
|
[
"",
"c++",
"encryption",
".net-2.0",
"aes",
"rijndael",
""
] |
Delegates look like such a powerful language feature, but I've yet to find an opportunity to use them in anger (apart from in DALs I must say).
How often do you use them, and under what circumstances do you find them most useful?
|
Funcs and Actions are newish "types" of delegates and I use them a lot with Linq and really other odd situations. For Linq they are nice because personally I'd rather have a descriptive name than a lambda expression:
```
someList.Select(item => item.Name);
```
Where with a Func I can:
```
Func<Item, String> itemName = item => item.Name;
...
someList.Select(itemName);
```
It might be a line more, but there are times where I find myself repeating a certain lambda expressions a couple times in a class, so personally I think Funcs work well for that.
Another situation is a, for lack of a better term, Method Factory. Basically it is a dictionary that holds a list of Actions as the value and say an Enum as the key:
```
Dictionary<UserType, Action<User>> showControls;
showControls = new Dictionary<UserType, Action<User>>();
showControls.Add(SomeEnum.Admin, setControlsForAdmin);
showControls.Add(SomeEnum.Normal, setControlsForNormalUser);
showControls.Add(SomeEnum.Unregistered, setControlsForUnregisteredUser);
```
And then I have the methods themselves written out somewhere else on the page. And use would be:
```
showControls[user.UserType]();
```
Or maybe you want to pass the method itself to another:
```
Action<User> neededMethod;
neededMethod = showControls[user.UserType];
SomeMethod(neededMethod);
```
I'm sure there are much better uses for delegates, but these are useful.
|
I use C# Delegate the most of time with Event.
```
public delegate void MyDelegate(object sender, EventArgs e, string otherParameterIWant);
//...Inside the class
public event MyDelegate myEvent;
//...Inside a method
if (myEvent != null)
myEvent(this, new EventArgs(), "Test for SO");
```
|
C# Delegates - How Often Do You Use Them, And When?
|
[
"",
"c#",
"delegates",
""
] |
Thanks for reading this.
I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and `$(this)`, I could not get it to work. Any ideas would be helpful. Thanks
The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select
`.one` is so the select is updated only once, then the `.bind` allows any options selected to be placed in the adjacent text box.
```
$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
```
|
`$(this)` is only relevant within the scope of the function. outside of the function though, it loses that reference:
```
$('.classSelect').one("click", function() {
$(this); // refers to $('.classSelect')
$.ajax({
// content
$(this); // does not refer to $('.classSelect')
});
});
```
a better way to handle this may be:
```
$('.classSelect').one("click", function() {
var e = $(this);
$.ajax({
...
success : function(request) {
e.html(request);
}
}); // end ajax
$(this).bind('click', function() {
// bind stuff
}); // end bind
}); // end one
```
by the way, are you familiar with the [`load()`](http://docs.jquery.com/Ajax/load) method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like `$.ajax()`. here's how i would rewrite this using `load()`:
```
$('.classSelect').one('click', function() {
var options = {
type : 'post',
dataType : 'text',
data : {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
}
} // end options
// load() will automatically load your .classSelect with the results
$(this).load(myUrl, options);
$(this).click(function() {
// etc...
}); // end click
}); // end one
```
|
I believe that this is because the function attached to the success event doesn't know what 'this' is as it is run independently of the object you're calling it within. (I'm not explaining it very well, but I think it's to do with closures.)
I think if you added the following line before the $.ajax call:
```
var _this = this;
```
and then in the success function used that variable:
```
success:
function(request) {
_this.html(request); // populate select box
}
```
it may well work
|
jQuery: Referencing the calling object(this) when the bind/click event is for a class
|
[
"",
"javascript",
"jquery",
""
] |
Is there an elegantish way in Swing to find out if there are any tooltips currently being displayed in my frame?
I'm using custom tooltips, so it would be very easy to set a flag in my `createToolTip()` method, but I can't see a way to find out when the tooltip is gone.
`ToolTipManager` has a nice flag for this, tipShowing, but of course it's `private` and they don't seem to offer a way to get to it. `hideWindow()` doesn't call out to the tooltip component (that I can tell), so I don't see a way there.
Anyone have any good ideas?
Update: I went with reflection. You can see the code here:
```
private boolean isToolTipVisible() {
// Going to do some nasty reflection to get at this private field. Don't try this at home!
ToolTipManager ttManager = ToolTipManager.sharedInstance();
try {
Field f = ttManager.getClass().getDeclaredField("tipShowing");
f.setAccessible(true);
boolean tipShowing = f.getBoolean(ttManager);
return tipShowing;
} catch (Exception e) {
// We'll keep silent about this for now, but obviously we don't want to hit this
// e.printStackTrace();
return false;
}
}
```
|
It appears that the isEnabled() property of the hideTipAction is directly tied to the tipShowing boolean. You could try this:
```
public boolean isTooltipShowing(JComponent component) {
AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip");
return hideTipAction.isEnabled();
}
```
You probably want to do some sanity checking for nulls, etc. But this should get you pretty close.
EDIT, to your responses:
Short of some ugly reflection code, I don't think you have much choice. You cannot subclass `ToolTipManager` because of the package private constructor, and the `showTipWindow()` and `hideTipWindow()` are also package private, so the Adapter pattern is out as well.
|
It looks like that is going to require looping over all of the components to see if they have a tooltip. I'm looking for a global value. It may be that a loop is doable, but it seems inefficient.
|
Can Swing tell me if there is an active tooltip?
|
[
"",
"java",
"swing",
"tooltip",
""
] |
I've added a weakly named assembly to my [Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005) project (which is strongly named). I'm now getting the error:
> "Referenced assembly 'xxxxxxxx' does not have a strong name"
Do I need to sign this third-party assembly?
|
To avoid this error you could either:
* Load the assembly dynamically, or
* Sign the third-party assembly.
You will find instructions on signing third-party assemblies in *[.NET-fu: Signing an Unsigned Assembly (Without Delay Signing)](https://dzone.com/articles/net-fu-zero-delay-signing-of-a)*.
### Signing Third-Party Assemblies
The basic principle to sign a thirp-party is to
1. Disassemble the assembly using `ildasm.exe` and save the intermediate language (IL):
```
ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll
```
2. Rebuild and sign the assembly:
```
ilasm /dll /key=myKey.snk thirdPartyLib.il
```
### Fixing Additional References
The above steps work fine unless your third-party assembly (*A.dll*) references another library (*B.dll*) which also has to be signed. You can disassemble, rebuild and sign both *A.dll* and *B.dll* using the commands above, but at runtime, loading of *B.dll* will fail because *A.dll* was originally built with a reference to the *unsigned* version of *B.dll*.
The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling
```
sn -Tp B.dll
```
which will give you the following output:
```
Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.33440
Copyright (c) Microsoft Corporation. All rights reserved.
Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
78effe92
Public key token is a8a7ed7203d87bc9
```
The last line contains the public key token. You then have to search the IL of *A.dll* for the reference to *B.dll* and add the token as follows:
```
.assembly extern /*23000003*/ MyAssemblyName
{
.publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )
.ver 10:0:0:0
}
```
|
Expand the project file that is *using* the project that does not "have a strong name key" and look for the `.snk` file (.StrongNameKey).
Browse through to this file in [Windows Explorer](http://en.wikipedia.org/wiki/Windows_Explorer) (just so that you know where it is).
Back in Visual Studio in the project that does not "have a strong name key", do
* Right click on the project file
* Select Properties
* Select "Signing tab" (on the left)
* Click the check box "Sign the assembly"
* Then `<Browse>` to the `.snk` file you found earlier
That should do the trick. This solved a problem for me for one project using a form inside another project in the same solution.
I hope it helps.
|
How to fix "Referenced assembly does not have a strong name" error
|
[
"",
"c#",
"visual-studio",
"visual-studio-2005",
"assemblies",
"strongname",
""
] |
What's a better way to start a thread, `_beginthread`, `_beginthreadx` or `CreateThread`?
I'm trying to determine what are the advantages/disadvantages of `_beginthread`, `_beginthreadex` and `CreateThread`. All of these functions return a thread handle to a newly created thread, I already know that CreateThread provides a little extra information when an error occurs (it can be checked by calling `GetLastError`)... but what are some things I should consider when I'm using these functions?
I'm working with a windows application, so cross-platform compatibility is already out of the question.
I have gone through the msdn documentation and I just can't understand, for example, why anybody would decide to use \_beginthread instead of CreateThread or vice versa.
Cheers!
Update:
OK, thanks for all the info, I've also read in a couple of places that I can't call `WaitForSingleObject()` if I used `_beginthread()`, but if I call `_endthread()` in the thread shouldn't that work? What's the deal there?
|
`CreateThread()` is a raw Win32 API call for creating another thread of control at the kernel level.
`_beginthread()` & `_beginthreadex()` are C runtime library calls that call `CreateThread()` behind the scenes. Once `CreateThread()` has returned, `_beginthread/ex()` takes care of additional bookkeeping to make the C runtime library usable & consistent in the new thread.
In C++ you should almost certainly use `_beginthreadex()` unless you won't be linking to the C runtime library at all (aka MSVCRT\*.dll/.lib).
|
There are several differences between `_beginthread()` and `_beginthreadex()`. `_beginthreadex()` was made to act more like `CreateThread()` (in both parameters and how it behaves).
As [Drew Hall](https://stackoverflow.com/questions/331536/windows-threading-beginthread-vs-beginthreadex-vs-createthread-c#331567) mentions, if you're using the C/C++ runtime, you must use `_beginthread()`/`_beginthreadex()` instead of `CreateThread()` so that the runtime has a chance to perform it's own thread initialization (setting up thread local storage, etc.).
In practice, this means that `CreateThread()` should pretty much never be used directly by your code.
The MSDN documents for `_beginthread()`/`_beginthreadex()` have quite a bit of detail on the differences - one of the more important is that since the thread handle for a thread created by `_beginthread()` gets closed automatically by the CRT when the thread exits, "if the thread generated by \_beginthread exits quickly, the handle returned to the caller of \_beginthread might be invalid or, worse, point to another thread".
Here is what the comments for `_beginthreadex()` in the CRT source have to say:
```
Differences between _beginthread/_endthread and the "ex" versions:
1) _beginthreadex takes the 3 extra parameters to CreateThread
which are lacking in _beginthread():
A) security descriptor for the new thread
B) initial thread state (running/asleep)
C) pointer to return ID of newly created thread
2) The routine passed to _beginthread() must be __cdecl and has
no return code, but the routine passed to _beginthreadex()
must be __stdcall and returns a thread exit code. _endthread
likewise takes no parameter and calls ExitThread() with a
parameter of zero, but _endthreadex() takes a parameter as
thread exit code.
3) _endthread implicitly closes the handle to the thread, but
_endthreadex does not!
4) _beginthread returns -1 for failure, _beginthreadex returns
0 for failure (just like CreateThread).
```
**Update** Jan 2013:
The CRT for VS 2012 has an additional bit of initialization performed in `_beginthreadex()`: if the process is a "packaged app" (if something useful is returned from `GetCurrentPackageId()`) the runtime will initialize the MTA on the newly created thread.
|
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
|
[
"",
"c++",
"c",
"multithreading",
"winapi",
""
] |
What is the correct syntax for this:
```
IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();
```
What am I messing up?
What does TSource mean?
|
The problem is that you're calling `List<T>.Reverse()` which returns `void`.
You could either do:
```
List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();
```
or:
```
IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();
```
The latter is more expensive, as reversing an arbitrary `IEnumerable<T>` involves buffering all of the data and then yielding it all - whereas `List<T>` can do all the reversing "in-place". (The difference here is that it's calling the `Enumerable.Reverse<T>()` extension method, instead of the `List<T>.Reverse()` instance method.)
More efficient yet, you could use:
```
string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();
```
This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.
|
I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas:
```
string str = "Tom, Scott, Bob";
IList<string> names = str.Split(new string[] {","," "},
StringSplitOptions.RemoveEmptyEntries);
```
The StringSplitOptions removes the records that would only be a space char...
|
C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order
|
[
"",
"c#",
"generics",
"syntax",
"ilist",
""
] |
My code is like the following:
```
URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();
```
Is it ok if I set the headers before I get the `InputStream`? Will my header be sent, or will the server see the default `URLConnection`'s user-agent ( if any ) ?
|
The headers **must** be set prior to getting the `InputStream` to have any affect - an `IllegalStateException` will be thrown if the connection is already open.
As far as the `User-Agent` header specifically, it should be sent if it has been set.
See the [URLConnection](http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html) JavaDoc.
|
To answer the question, the code is correct. The moment getInputStream(), an HTTP get is sent to the target server.
A side-note on user-agent, if you don't set it, URLConnection will send the default one anyway, which is:
```
User-Agent: Java/1.6.0_24 (varies depending on your java version)
```
|
What is the proper way of setting headers in a URLConnection?
|
[
"",
"java",
"header",
"urlconnection",
""
] |
I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.
**EDIT:**
To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.
|
Try this
```
SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM
(SELECT product_id, sum(quantity) as inventory_total
FROM inventory
GROUP BY product_id) inv_t LEFT OUTER JOIN
(SELECT product_id, count(*) AS sales_total
FROM sales
GROUP BY product_id) sale_t
ON (inv_t.product_id = sale_t.product_id)
```
This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table. You want to make sure that such products also show up in the results.
NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument. There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.
|
```
SELECT product AS prd,
SUM(quantity) -
IFNULL((SELECT COUNT(*)
FROM sells
WHERE product = prd
GROUP BY product), 0)
AS stock
FROM bought
GROUP BY product;
```
This one also works when quantity sold is 0.
|
Finding difference in row count of two tables in MySQL
|
[
"",
"mysql",
"sql",
"count",
"sum",
""
] |
When I discovered [`boost::lexical_cast`](http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm) I thought to myself "why didn't I know about this sooner!" - I hated having to write code like
```
stringstream ss;
ss << anIntVal;
mystring = ss.str();
```
Now I write
```
mystring = boost::lexical_cast<string>(anIntVal);
```
Yesterday, on stackoverflow, I came across boost split (another gem that will save me writing code).
```
string stringtobesplit = "AA/BB-CC")
vector<string> tokens;
boost::split(tokens, stringtobesplit, boost::is_any_of("/-"));
// tokens now holds 3 items: AA BB CC
```
I am going to start looking through boost documentation looking for other functions that I will be able to use regularly, but I feel that it will be very easy to miss things.
What boost functions do you use most / would hate not to have?
|
Probably the most used part of boost for me is [boost::shared\_ptr](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm).
|
[BOOST\_FOREACH](http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html) makes life worthwhile again.
(Why has nobody mentioned this? The question was asked 8 months ago!)
|
Most used parts of Boost
|
[
"",
"c++",
"boost",
""
] |
I want to create maintainable code, but this inheritance situation is causing me problems.
The issue is with my 2nd database helper class named **InitUserExtension**.
Since UserExtension inherits from User, I have to make sure that I **mirror** any changes in my InitUser helper to InitUserExtension.
I really don't like this as **its prone to bugs, what's the solution?**
My class definitions:
```
public class User
{
public string Name {get; set; }
public string Age { get; set; }
}
public class UserExtension : User
{
public string Lastname {get; set; }
public string Password {get; set; }
}
```
My database helpers:
```
public static SqlDataReader InitUser(SqlDataReader dr)
{
User user = new User();
user.Name = Convert.ToString(dr["name"]);
user.Age ...
}
public static SqlDataReader InitUserExtension(SqlDataReader dr)
{
UserExtension user = new UserExtension();
// note: mirror attributes from User
user.Name = Convert.ToString(dr["name"]);
user.Age ...
user.Lastname = Convert.ToString(dr["lastname"]);
user.Password = ....;
}
```
|
How about moving the processing of Name etc into a method (accepting either a User or a T : User), and call that from both?
```
private static void InitUser(User user, SqlDataReader dr)
{ // could also use an interface here, or generics with T : User
user.Name = Convert.ToString(dr["name"]);
user.Age ...
}
public static User InitUser(SqlDataReader dr)
{
User user = new User();
InitUser(user, dr);
return user;
}
public static UserExtension InitUserExtension(SqlDataReader dr)
{
UserExtension user = new UserExtension();
InitUser(user, dr);
user.Lastname = Convert.ToString(dr["lastname"]);
user.Password = ....;
return user;
}
```
As an alternative, you could reduce the line count, but increase the complexity, using generics:
```
private static T InitUserCore<T>(SqlDataReader dr) where T : User, new()
{
T user = new T();
// ...
return user;
}
public static User InitUser(SqlDataReader dr)
{
return InitUserCore<User>(dr);
}
public static UserExtension InitUserExtension(SqlDataReader dr)
{
UserExtension user = InitUserCore<UserExtension>(dr);
// ...
return user;
}
```
|
Why don't you call `InitUser` from the `InitUserExtension` method. Let the base initialization handle the base class properties and let the extended initializer handled the extension class properties.
|
Inherited class quagmire, how to make this maintainable code
|
[
"",
"c#",
"coding-style",
""
] |
I'm working on a webservice + AJAX interface, and I'm worried about authentication. This moment I'm passing username and password to the webservice as arguments, but I fear that this approach is highly insecure. I was told that ssl could solve my problem, but I want more alternatives.
My webservice is written in php and my interface is in php + AJAX. The webservice receives arguments from POST or GET and retreives xml (in a future maybe I'll use JSON)
|
AJAX request are no different to normal request.
Since you have an AJAX interface I guess you can have a page where users log-in. When they log-in store a cookie at the browser. This cookie can then be sent back with every AJAX request.
Your PHP script can "authenticate" the AJAX request using the cookie exactly as it would with normal requests.
|
There are various standards like ws-trust, ws-security, ws-federation etc. which you could rely upon to secure your webservices.
You can also sign your soap headers containing security information.
The following blog details out various authentication mechanism for webservices using php.
<http://phpwebservices.blogspot.com/>
|
Webservice Authentication
|
[
"",
"php",
"html",
"ajax",
"web-services",
"authentication",
""
] |
I need to create an `XmlDocument` with a root element containing multiple namespaces. Am using C# 2.0 or 3.0
Here is my code:
```
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB", "http://www.example.com");
root.AppendChild(job);
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
job.AppendChild(docInputs);
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
```
The current output:
```
<JOBS xmlns="http://www.example.com">
<JOB>
<JOB:DOCINPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
```
However, my desired output is:
```
<JOBS xmlns:JOBS="http://www.example.com" xmlns:JOB="http://www.example.com">
<JOB>
<JOB:DOCINPUTS>
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS>
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
```
My question: how do I create an `XmlDocument` that contains a root element with multiple namespaces?
|
The following will generate the desired output that you requested above:
```
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS");
root.SetAttribute("xmlns:JOBS", "http://www.example.com");
root.SetAttribute("xmlns:JOB", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB");
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
job.AppendChild(docInputs);
XmlElement docOutputs = doc.CreateElement("JOB", "DOCOUTPUTS", "http://www.example.com");
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
job.AppendChild(docOutputs);
doc.DocumentElement.AppendChild(job);
```
However, it seems odd that in your example/desired output that the same XML namespace was used against two different prefixes. Hope this helps.
|
You can explicitly create namespace prefix attributes on an element. Then when you add descendant elements that are created with both the same namespace and the same prefix, the XmlDocument will work out that it doesn't need to add a namespace declaration to the element.
Run this example to see how this works:
```
using System;
using System.Xml;
static void Main(string[] args)
{
XmlDocument d = new XmlDocument();
XmlElement e = d.CreateElement("elm");
d.AppendChild(e);
d.DocumentElement.SetAttribute("xmlns:a", "my_namespace");
e = d.CreateElement("a", "bar", "my_namespace");
d.DocumentElement.AppendChild(e);
e = d.CreateElement("a", "baz", "other_namespace");
d.DocumentElement.AppendChild(e);
e = d.CreateElement("b", "bar", "my_namespace");
d.DocumentElement.AppendChild(e);
d.Save(Console.Out);
Console.ReadLine();
}
```
|
How do I add multiple namespaces to the root element with XmlDocument?
|
[
"",
"c#",
".net",
"xml",
"namespaces",
"xmldocument",
""
] |
How do I retrieve an item at random from the following list?
```
foo = ['a', 'b', 'c', 'd', 'e']
```
|
Use [`random.choice()`](https://docs.python.org/library/random.html#random.choice):
```
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
```
For [cryptographically secure](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) random choices (e.g., for generating a passphrase from a wordlist), use [`secrets.choice()`](https://docs.python.org/library/secrets.html#secrets.choice):
```
import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
```
`secrets` is new in Python 3.6. On older versions of Python you can use the [`random.SystemRandom`](https://docs.python.org/library/random.html#random.SystemRandom) class:
```
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
```
|
If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using `random.sample` instead.
```
import random
group_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
```
If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax `random.sample(some_list, 1)[0]` instead of `random.choice(some_list)`.
Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though `random.choice(tuple(some_set))` may be an option for getting a single item from a set.
**EDIT: Using Secrets**
As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:
```
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
group_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
```
**EDIT: Pythonic One-Liner**
If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.
```
import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)
```
|
How can I randomly select (choose) an item from a list (get a random element)?
|
[
"",
"python",
"list",
"random",
""
] |
I am really new to Python and I have been looking for an example on how to write a Web Service (XML - SOAP) in Python with Google App Engine with no luck.
Can anyone point me to an article or give me an example on how to do this?
|
I was curious about this myself and not finding anything I decided to try to get something to work. The short answer is that it turns out a SOAP service can actually be done using the latest alpha [ZSI library](http://pywebsvcs.sourceforge.net/zsi.html). However it isn't simple and I didn't do much more than a simple request so it could fall apart with a complex type. I'll try to find time to write a tutorial on how to do it and edit this answer with more detail.
Unless this is a hard requirement I would do what jamtoday says and go with a REST or RPC service. The SOAP way could be filled with trouble.
Update: For anyone interested I've written a [tutorial on how to deploy a SOAP service to the Google App Engine](http://www.ioncannon.net/web-services/180/soap-on-the-google-app-engine-platform/). It is long process so I'm just linking to it instead of pasting it all here.
|
If you want to do something with App Engine specifically, there are libraries that will make it much faster on your end. I'd recommend looking at the XML-RPC and REST examples.
<http://appengine-cookbook.appspot.com/recipe/xml-rpc-server-using-google-app-engine/>
<http://github.com/fczuardi/gae-rest/tree/master>
|
How to write a Web Service for Google App Engine?
|
[
"",
"python",
"xml",
"web-services",
"google-app-engine",
"soap",
""
] |
I don't have too much experience with C# so if someone could point me in the right direction I would greatly appreciate it. I have a foreach loop that references a variable of an object. I wish to make another foreach loop inside the main one that compares (or performs actions on) the current variable to the rest of the variables in the array of the object.
I have the following code:
```
// Integrate forces for each body.
foreach (RigidBodyBase body in doc.Bodies)
{
// Don't move background-anchored bodies.
if (body.anchored) continue;
// This is where we will add Each Body's gravitational force
// to the total force exerted on the object.
// For each other body, get it's point and it's mass.
// Find the gravitational force exterted between target body and looped body.
// Find distance between bodies.
// vector addition
// Force = G*mass1*mass2/distance^2
// Find vector of that force.
// Add Force to TotalGravityForce
// loop until there are no more bodies.
// Add TotalGravityForce to body.totalForce
}
```
|
Each time you execute foreach, (even while nesting them) the internal Enumerator should "new" up a new iterator for you, there should not be any issue with that. The issues come about when you are adding, or removing items from the collection while you are still iterating...
Remember, in the inner foreach, to check to make sure you are not on the same item as the outer for each is on
```
foreach( RigidBodyBase body in doc.Bodies)
foreach ( RigidBodyBase otherBody in doc.Bodies)
if (!otherBody.Anchored && otherBody != body) // or otherBody.Id != body.Id -- whatever is required...
// then do the work here
```
by the way, the best place to put this code would be in a GravityForce property of the RigidBodyBase class, Then you could just write:
```
foreach (RigidBodyBase body in doc.Bodies)
body.TotalForce += body.GravityForce;
```
although depending on what you're doing here (moving all objects?) they're may be even more opportunity for refactoring... I'd also consider having a separate property for the "other" forces, and have TotalForce Property do the summing of the Gravity Force and the "other" Forces?
|
IMHO it should be possible, although you should really consider Kibbee's suggestion. Maybe you can optimize it that way too (for example, like this:)
```
int l = doc.Bodies.Count;
for ( int i = 0; i < l; i++ )
for ( int j = i + 1; j < l; j++ )
// Do stuff
```
|
C# foreach within a foreach loop
|
[
"",
"c#",
""
] |
I am currently starting my Java VM with the **`com.sun.management.jmxremote.*`** properties so that I can connect to it via JConsole for management and monitoring. Unfortunately, it listens on all interfaces (IP addresses) on the machine.
In our environment, there are often cases where there is more than one Java VM running on a machine at the same time. While it's possible to tell JMX to listen on different TCP ports (using `com.sun.management.jmxremote.port`), it would be nice to instead have JMX use the standard JMX port and just bind to a specific IP address (rather than all of them).
This would make it much easier to figure out which VM we're connecting to via JConsole (since each VM effectively "owns" its own IP address). Has anyone figured out how to make JMX listen on a single IP address or hostname?
|
If anyone else will be losing his nerves with this ... After 10 years, they finally fixed it!
Since Java 8u102 `-Dcom.sun.management.jmxremote.host` binds to the selected IP
see: <https://bugs.openjdk.java.net/browse/JDK-6425769>
|
Fernando already provided a link to [my blog post](http://vafer.org/blog/20061010091658) :) ..it's not trivial. You have to provide your own RMIServerSocketFactoryImpl that creates sockets on the wanted address.
If internal/external interfaces are the problem and you have local access setting up a local firewall might be easier.
|
How to have JMX bind to a specific interface?
|
[
"",
"java",
"rmi",
"jmx",
"jconsole",
""
] |
I'm looking for the fastest way to determine if a `long` value is a perfect square (i.e. its square root is another integer):
1. I've done it the easy way, by using the built-in [`Math.sqrt()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#sqrt(double))
function, but I'm wondering if there is a way to do it faster by
restricting yourself to integer-only domain.
2. Maintaining a lookup table is impractical (since there are about
231.5 integers whose square is less than 263).
Here is the very simple and straightforward way I'm doing it now:
```
public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
```
Note: I'm using this function in many [Project Euler](http://projecteuler.net/) problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.
---
I've tried the different solutions to the problem:
* After exhaustive testing, I found that adding `0.5` to the result of Math.sqrt() is not necessary, at least not on my machine.
* The [fast inverse square root](https://en.wikipedia.org/wiki/Fast_inverse_square_root) was faster, but it gave incorrect results for n >= 410881. However, as suggested by [BobbyShaftoe](https://stackoverflow.com/users/38426/bobbyshaftoe), we can use the FISR hack for n < 410881.
* Newton's method was a good bit slower than `Math.sqrt()`. This is probably because `Math.sqrt()` uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles.
* A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than `Math.sqrt()`.
* Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.
* According to John's tests, using `or` statements is faster in C++ than using a `switch`, but in Java and C# there appears to be no difference between `or` and `switch`.
* I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or `or` statement, I would just say `if(lookup[(int)(n&0x3F)]) { test } else return false;`. To my surprise, this was (just slightly) slower. This is because [array bounds are checked in Java](https://stackoverflow.com/questions/299079/why-is-this-code-with-several-or-statements-slightly-faster-than-using-a-lookup-t#299205).
|
I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don't know how the Java factor will play out.
My approach is threefold:
1. First, filter out obvious answers. This includes negative numbers and looking at the last 4 bits. (I found looking at the last six didn't help.) I also answer yes for 0. (In reading the code below, note that my input is `int64 x`.)
```
if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )
return false;
if( x == 0 )
return true;
```
2. Next, check if it's a square modulo 255 = 3 \* 5 \* 17. Because that's a product of three distinct primes, only about 1/8 of the residues mod 255 are squares. However, in my experience, calling the modulo operator (%) costs more than the benefit one gets, so I use bit tricks involving 255 = 2^8-1 to compute the residue. (For better or worse, I am not using the trick of reading individual bytes out of a word, only bitwise-and and shifts.)
```
int64 y = x;
y = (y & 4294967295LL) + (y >> 32);
y = (y & 65535) + (y >> 16);
y = (y & 255) + ((y >> 8) & 255) + (y >> 16);
// At this point, y is between 0 and 511. More code can reduce it farther.
```
To actually check if the residue is a square, I look up the answer in a precomputed table.
```
if( bad255[y] )
return false;
// However, I just use a table of size 512
```
3. Finally, try to compute the square root using a method similar to [Hensel's lemma](http://en.wikipedia.org/wiki/Hensel%27s_lemma). (I don't think it's applicable directly, but it works with some modifications.) Before doing that, I divide out all powers of 2 with a binary search:
```
if((x & 4294967295LL) == 0)
x >>= 32;
if((x & 65535) == 0)
x >>= 16;
if((x & 255) == 0)
x >>= 8;
if((x & 15) == 0)
x >>= 4;
if((x & 3) == 0)
x >>= 2;
```
At this point, for our number to be a square, it must be 1 mod 8.
```
if((x & 7) != 1)
return false;
```
The basic structure of Hensel's lemma is the following. (Note: untested code; if it doesn't work, try t=2 or 8.)
```
int64 t = 4, r = 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
// Repeat until t is 2^33 or so. Use a loop if you want.
```
The idea is that at each iteration, you add one bit onto r, the "current" square root of x; each square root is accurate modulo a larger and larger power of 2, namely t/2. At the end, r and t/2-r will be square roots of x modulo t/2. (Note that if r is a square root of x, then so is -r. This is true even modulo numbers, but beware, modulo some numbers, things can have even more than 2 square roots; notably, this includes powers of 2.) Because our actual square root is less than 2^32, at that point we can actually just check if r or t/2-r are real square roots. In my actual code, I use the following modified loop:
```
int64 r, t, z;
r = start[(x >> 3) & 1023];
do {
z = x - r * r;
if( z == 0 )
return true;
if( z < 0 )
return false;
t = z & (-z);
r += (z & t) >> 1;
if( r > (t >> 1) )
r = t - r;
} while( t <= (1LL << 33) );
```
The speedup here is obtained in three ways: precomputed start value (equivalent to ~10 iterations of the loop), earlier exit of the loop, and skipping some t values. For the last part, I look at `z = r - x * x`, and set t to be the largest power of 2 dividing z with a bit trick. This allows me to skip t values that wouldn't have affected the value of r anyway. The precomputed start value in my case picks out the "smallest positive" square root modulo 8192.
Even if this code doesn't work faster for you, I hope you enjoy some of the ideas it contains. Complete, tested code follows, including the precomputed tables.
```
typedef signed long long int int64;
int start[1024] =
{1,3,1769,5,1937,1741,7,1451,479,157,9,91,945,659,1817,11,
1983,707,1321,1211,1071,13,1479,405,415,1501,1609,741,15,339,1703,203,
129,1411,873,1669,17,1715,1145,1835,351,1251,887,1573,975,19,1127,395,
1855,1981,425,453,1105,653,327,21,287,93,713,1691,1935,301,551,587,
257,1277,23,763,1903,1075,1799,1877,223,1437,1783,859,1201,621,25,779,
1727,573,471,1979,815,1293,825,363,159,1315,183,27,241,941,601,971,
385,131,919,901,273,435,647,1493,95,29,1417,805,719,1261,1177,1163,
1599,835,1367,315,1361,1933,1977,747,31,1373,1079,1637,1679,1581,1753,1355,
513,1539,1815,1531,1647,205,505,1109,33,1379,521,1627,1457,1901,1767,1547,
1471,1853,1833,1349,559,1523,967,1131,97,35,1975,795,497,1875,1191,1739,
641,1149,1385,133,529,845,1657,725,161,1309,375,37,463,1555,615,1931,
1343,445,937,1083,1617,883,185,1515,225,1443,1225,869,1423,1235,39,1973,
769,259,489,1797,1391,1485,1287,341,289,99,1271,1701,1713,915,537,1781,
1215,963,41,581,303,243,1337,1899,353,1245,329,1563,753,595,1113,1589,
897,1667,407,635,785,1971,135,43,417,1507,1929,731,207,275,1689,1397,
1087,1725,855,1851,1873,397,1607,1813,481,163,567,101,1167,45,1831,1205,
1025,1021,1303,1029,1135,1331,1017,427,545,1181,1033,933,1969,365,1255,1013,
959,317,1751,187,47,1037,455,1429,609,1571,1463,1765,1009,685,679,821,
1153,387,1897,1403,1041,691,1927,811,673,227,137,1499,49,1005,103,629,
831,1091,1449,1477,1967,1677,697,1045,737,1117,1737,667,911,1325,473,437,
1281,1795,1001,261,879,51,775,1195,801,1635,759,165,1871,1645,1049,245,
703,1597,553,955,209,1779,1849,661,865,291,841,997,1265,1965,1625,53,
1409,893,105,1925,1297,589,377,1579,929,1053,1655,1829,305,1811,1895,139,
575,189,343,709,1711,1139,1095,277,993,1699,55,1435,655,1491,1319,331,
1537,515,791,507,623,1229,1529,1963,1057,355,1545,603,1615,1171,743,523,
447,1219,1239,1723,465,499,57,107,1121,989,951,229,1521,851,167,715,
1665,1923,1687,1157,1553,1869,1415,1749,1185,1763,649,1061,561,531,409,907,
319,1469,1961,59,1455,141,1209,491,1249,419,1847,1893,399,211,985,1099,
1793,765,1513,1275,367,1587,263,1365,1313,925,247,1371,1359,109,1561,1291,
191,61,1065,1605,721,781,1735,875,1377,1827,1353,539,1777,429,1959,1483,
1921,643,617,389,1809,947,889,981,1441,483,1143,293,817,749,1383,1675,
63,1347,169,827,1199,1421,583,1259,1505,861,457,1125,143,1069,807,1867,
2047,2045,279,2043,111,307,2041,597,1569,1891,2039,1957,1103,1389,231,2037,
65,1341,727,837,977,2035,569,1643,1633,547,439,1307,2033,1709,345,1845,
1919,637,1175,379,2031,333,903,213,1697,797,1161,475,1073,2029,921,1653,
193,67,1623,1595,943,1395,1721,2027,1761,1955,1335,357,113,1747,1497,1461,
1791,771,2025,1285,145,973,249,171,1825,611,265,1189,847,1427,2023,1269,
321,1475,1577,69,1233,755,1223,1685,1889,733,1865,2021,1807,1107,1447,1077,
1663,1917,1129,1147,1775,1613,1401,555,1953,2019,631,1243,1329,787,871,885,
449,1213,681,1733,687,115,71,1301,2017,675,969,411,369,467,295,693,
1535,509,233,517,401,1843,1543,939,2015,669,1527,421,591,147,281,501,
577,195,215,699,1489,525,1081,917,1951,2013,73,1253,1551,173,857,309,
1407,899,663,1915,1519,1203,391,1323,1887,739,1673,2011,1585,493,1433,117,
705,1603,1111,965,431,1165,1863,533,1823,605,823,1179,625,813,2009,75,
1279,1789,1559,251,657,563,761,1707,1759,1949,777,347,335,1133,1511,267,
833,1085,2007,1467,1745,1805,711,149,1695,803,1719,485,1295,1453,935,459,
1151,381,1641,1413,1263,77,1913,2005,1631,541,119,1317,1841,1773,359,651,
961,323,1193,197,175,1651,441,235,1567,1885,1481,1947,881,2003,217,843,
1023,1027,745,1019,913,717,1031,1621,1503,867,1015,1115,79,1683,793,1035,
1089,1731,297,1861,2001,1011,1593,619,1439,477,585,283,1039,1363,1369,1227,
895,1661,151,645,1007,1357,121,1237,1375,1821,1911,549,1999,1043,1945,1419,
1217,957,599,571,81,371,1351,1003,1311,931,311,1381,1137,723,1575,1611,
767,253,1047,1787,1169,1997,1273,853,1247,413,1289,1883,177,403,999,1803,
1345,451,1495,1093,1839,269,199,1387,1183,1757,1207,1051,783,83,423,1995,
639,1155,1943,123,751,1459,1671,469,1119,995,393,219,1743,237,153,1909,
1473,1859,1705,1339,337,909,953,1771,1055,349,1993,613,1393,557,729,1717,
511,1533,1257,1541,1425,819,519,85,991,1693,503,1445,433,877,1305,1525,
1601,829,809,325,1583,1549,1991,1941,927,1059,1097,1819,527,1197,1881,1333,
383,125,361,891,495,179,633,299,863,285,1399,987,1487,1517,1639,1141,
1729,579,87,1989,593,1907,839,1557,799,1629,201,155,1649,1837,1063,949,
255,1283,535,773,1681,461,1785,683,735,1123,1801,677,689,1939,487,757,
1857,1987,983,443,1327,1267,313,1173,671,221,695,1509,271,1619,89,565,
127,1405,1431,1659,239,1101,1159,1067,607,1565,905,1755,1231,1299,665,373,
1985,701,1879,1221,849,627,1465,789,543,1187,1591,923,1905,979,1241,181};
bool bad255[512] =
{0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,
1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,
0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,
1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,
1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,
1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,
0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,
1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,
0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,
1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,
1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,
1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,
0,0};
inline bool square( int64 x ) {
// Quickfail
if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )
return false;
if( x == 0 )
return true;
// Check mod 255 = 3 * 5 * 17, for fun
int64 y = x;
y = (y & 4294967295LL) + (y >> 32);
y = (y & 65535) + (y >> 16);
y = (y & 255) + ((y >> 8) & 255) + (y >> 16);
if( bad255[y] )
return false;
// Divide out powers of 4 using binary search
if((x & 4294967295LL) == 0)
x >>= 32;
if((x & 65535) == 0)
x >>= 16;
if((x & 255) == 0)
x >>= 8;
if((x & 15) == 0)
x >>= 4;
if((x & 3) == 0)
x >>= 2;
if((x & 7) != 1)
return false;
// Compute sqrt using something like Hensel's lemma
int64 r, t, z;
r = start[(x >> 3) & 1023];
do {
z = x - r * r;
if( z == 0 )
return true;
if( z < 0 )
return false;
t = z & (-z);
r += (z & t) >> 1;
if( r > (t >> 1) )
r = t - r;
} while( t <= (1LL << 33) );
return false;
}
```
|

I'm pretty late to the party, but I hope to provide a better answer; shorter and (assuming my [benchmark](https://www.dropbox.com/s/ad4r6oxfcilqkch/IsSquareBenchmark.java?dl=0) is correct) also much [faster](https://microbenchmarks.appspot.com/runs/185f228a-fd9b-44b4-8a7a-48d12101aece).
```
long goodMask; // 0xC840C04048404040 computed below
{
for (int i=0; i<64; ++i) goodMask |= Long.MIN_VALUE >>> (i*i);
}
public boolean isSquare(long x) {
// This tests if the 6 least significant bits are right.
// Moving the to be tested bit to the highest position saves us masking.
if (goodMask << x >= 0) return false;
final int numberOfTrailingZeros = Long.numberOfTrailingZeros(x);
// Each square ends with an even number of zeros.
if ((numberOfTrailingZeros & 1) != 0) return false;
x >>= numberOfTrailingZeros;
// Now x is either 0 or odd.
// In binary each odd square ends with 001.
// Postpone the sign test until now; handle zero in the branch.
if ((x&7) != 1 | x <= 0) return x == 0;
// Do it in the classical way.
// The correctness is not trivial as the conversion from long to double is lossy!
final long tst = (long) Math.sqrt(x);
return tst * tst == x;
}
```
The first test catches most non-squares quickly. It uses a 64-item table packed in a long, so there's no array access cost (indirection and bounds checks). For a uniformly random `long`, there's a 81.25% probability of ending here.
The second test catches all numbers having an odd number of twos in their factorization. The method `Long.numberOfTrailingZeros` is very fast as it gets JIT-ed into a single i86 instruction.
After dropping the trailing zeros, the third test handles numbers ending with 011, 101, or 111 in binary, which are no perfect squares. It also cares about negative numbers and also handles 0.
The final test falls back to `double` arithmetic. As `double` has only 53 bits mantissa,
the conversion from `long` to `double` includes rounding for big values. Nonetheless, the test is correct (unless the [proof](https://math.stackexchange.com/questions/237865/show-that-floating-point-sqrtx-cdot-x-geq-x-for-all-long-x) is wrong).
Trying to incorporate the mod255 idea wasn't successful.
|
Fastest way to determine if an integer's square root is an integer
|
[
"",
"java",
"math",
"optimization",
"perfect-square",
""
] |
I have a nice and lovely Django site up and running, but have noticed that my `error.log` file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like `http://mysite.com/ie` or `http://mysite.com/~admin.php` etc.
Since Django uses URL rewriting, it is looking for templates to fit these requests, which raises a `TemplateDoesNotExist` exception, and then a 500 message (Django does this, not me). I have debug turned off, so they only get the generic 500 message, but it's filling up my logs very quickly.
Is there a way to turn this behavior off? Or perhaps just block the IP's doing this?
|
Um, perhaps, use [logrotate](http://linuxcommand.org/man_pages/logrotate8.html) to rotate and compress the logs periodically, if it isn't being done already.
|
If you can find a pattern in UserAgent string, you may use `DISALLOWED_USER_AGENT` setting. Mine is:
```
DISALLOWED_USER_AGENTS = (
re.compile(r'Java'),
re.compile(r'gigamega'),
re.compile(r'litefinder'),
)
```
See the description in [Django docs](http://docs.djangoproject.com/en/dev/ref/settings/#disallowed-user-agents).
|
Spambots are cluttering my log file [Django]
|
[
"",
"python",
"django",
"apache",
"spam-prevention",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.