Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm dabbling with a linguistics Javascript project. I'd like to build it using objects to represent Nouns and functions to store Verbs as this makes conceptualizing my project less difficult. I'm using functions as keys to an object (I've written an example below). Will it be possible to serialize this with JSON when it comes time to save the data.
```
function verbFn() {
//do something
}
var nouns = {};
nouns[verbFn] = 'some value';
```
In this example, will JSON be able to serialize "nouns"?
---
Uh... after reflecting on my original question and reading the comments I've come to the conclusion that trying to do things this way is just very wrong and silly. | No, [JSON](http://json.org/) can't do this.
The keys have to be double-quoted strings.
Also it looks like you're not actually using the function as a key - it's being converted to a string:
```
<script>
var x = {};
x[window.open] = true;
for (var i in x)
alert(typeof i + '\n' + i); // typeof i == string
</script>
``` | According to the [standards](http://www.json.org/) no you can't. The key has to be a string | can JSON serialize an array that uses *functions* as keys? | [
"",
"javascript",
"json",
"semantics",
""
] |
I've created a class, called vir, with a function move:
```
class vir
{
public:
vir(int a,int b,char s){x=a;y=b;sym=s;}
void move(){}
};
```
(It's derived from a class with variables int x, int y, and char sym)
I have derived a class from this, called subvir:
```
class subvir:public vir
{
public:
subvir(int a,int b,char s){x=a;y=b;sym=s;}
void move();
};
subvir::move()
{
x++;
return;
}
```
And then I created an array of vir, and put a subvir into it
```
subvir sv1(0,0,'Q');
vir vir_RA[1]={sv1};
```
But when I try to use sv1.move():
vir\_RA[0].move();
It uses the vir move ({}) rather than the subvir move ({x++}). I have tried making sv1 a vir and vir\_RA a vir, and it works, and it also works when I make them both subvir, but I need them to be different. I tried making vir::move() a pure virtual, but then I get an error substantiating the array. Does anyone know how I can get move() to work when I use it from the array? | You need an array of pointers in this case, rather than an array of instances. Use vir\*[] instead of vir[] | You are running into a problem called [slicing](http://en.wikipedia.org/wiki/Object_slicing). Use an array of pointers, or something like [Boost.ptr\_container](http://www.boost.org/doc/libs/1_39_0/libs/ptr_container/doc/reference.html). | Why won't a derived class work in an array? (C++) | [
"",
"c++",
"arrays",
"class",
"inheritance",
"polymorphism",
""
] |
We have a system with a web app and a bunch of Windows Services doing some background work.
Whenever we need to make a more substantial change to the system, we end up having to issue an IIS Reset, and then manually restart all relevant Windows services.
Is there any way at all to be notified of such IISReset events in C# code, so that our Windows Services could restart themselves, whenever they detect such an IISReset command being executed?
Thanks!
Marc | You could also plug into Windows Instrumentation with you own custom Windows Query Language expression.
I've never used it for IIS directly, but I expect that there would be objects you can listen to, which lets you be aware of such changes.
You can check this out : <http://www.csharphelp.com/archives2/archive334.html> as a starting point for research. | Couldn't you just write a batch file to call IIS Reset and then restart the Windows Services?
I think the way to start a Windows Service is:
```
NET START "SERVICE NAME"
``` | Be notified of an IIS Reset? | [
"",
"c#",
"iis",
"windows-services",
""
] |
We have a JSON response which can contain null values (e.g. { myValue: null }) - we assign this value to a textbox on a form: (actually, we use JQuery, but this is equivalent
```
var nullString = null;
document.getElementById('myInput').value = nullString;
```
If we assign this value to an HTML textbox value, the behaviour seems browser-dependent:
* Firefox and Chrome both display an empty text box, and when you read 'value' back you get null.
* IE puts the string 'null' into the text box, and when you read 'value' back, you get the string "null" (i.e. setting 'value' and reading it back has modified the data)
(It's here: <http://jsbin.com/uleno/edit> if anyone wants to try it)
Which browser is doing the right thing here, or is this undefined behaviour? And is there a cleverer more elegant workaround than doing a lot of (myValue == null ? '' : myValue) stuff? | What's actually happening is the null object is being stringified, like null.toString(). In an alert() message box, the browser usually interprets the object instead of simply stringifying it, so the result will be different. And, of course, browsers (especially IE) interpret and stringify differently.
For what it's worth, there is a logic to returning null when a string is expected. Whatever is returning this value probably does so in order to provide a false value for easy conditional testing, while still indicating that the result is empty rather than, eg undefined. DOM methods that return collection objects do the same. Further, while an empty string literal ('') is a false value, an empty String object (new String('')) is not; and the latter can be created from the former accidentally with further processing. So the "safe" way to prevent the consuming code from accidentally discarding a valid string is to return a string literal or String object in one case, and null in another. | Actually, the simplest thing to do is this:
```
document.getElementById('myInput').value = nullString || '';
```
You know that value must gets a string assigned so if its any other 'falsy'\* value, you return the empty string.
\* null, undefined, 0, false, '' | What's should setting an HTML textbox value to null do? | [
"",
"javascript",
"html",
"forms",
""
] |
**Does anyone know of some global state variable that is available so that I can check if the code is currently executing in design mode (e.g. in Blend or Visual Studio) or not?**
It would look something like this:
```
//pseudo code:
if (Application.Current.ExecutingStatus == ExecutingStatus.DesignMode)
{
...
}
```
The reason I need this is: when my application is being shown in design mode in Expression Blend, I want the ViewModel to instead use a "Design Customer class" which has mock data in it that the designer can view in design mode.
However, when the application is actually executing, I of course want the ViewModel to use the real Customer class which returns real data.
Currently I solve this by having the designer, before he works on it, go into the ViewModel and change "ApplicationDevelopmentMode.Executing" to "ApplicationDevelopmentMode.Designing":
```
public CustomersViewModel()
{
_currentApplicationDevelopmentMode = ApplicationDevelopmentMode.Designing;
}
public ObservableCollection<Customer> GetAll
{
get
{
try
{
if (_currentApplicationDevelopmentMode == ApplicationDevelopmentMode.Developing)
{
return Customer.GetAll;
}
else
{
return CustomerDesign.GetAll;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
``` | I believe you are looking for [GetIsInDesignMode](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.getisindesignmode.aspx), which takes a DependencyObject.
Ie.
```
// 'this' is your UI element
DesignerProperties.GetIsInDesignMode(this);
```
**Edit:** When using Silverlight / WP7, you should use [`IsInDesignTool`](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.isindesigntool%28v=VS.95%29.aspx) since `GetIsInDesignMode` can sometimes return false while in Visual Studio:
```
DesignerProperties.IsInDesignTool
```
**Edit:** And finally, in the interest of completeness, the equivalent in WinRT / Metro / Windows Store applications is [`DesignModeEnabled`](http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.designmode.designmodeenabled.aspx):
```
Windows.ApplicationModel.DesignMode.DesignModeEnabled
``` | You can do something like this:
```
DesignerProperties.GetIsInDesignMode(new DependencyObject());
``` | Is there a way to check if WPF is currently executing in design mode or not? | [
"",
"c#",
"wpf",
"expression-blend",
""
] |
I want to add some new functions to the core `string` helper, which is found in `system/helpers` folder. I think there was a 'right' way to do this using `MY_String_helper`, or something of that sort. I can't remember exactly how it was done though. Any thoughts on this issue? | I found it. Make a file with a name such as this, in the `application/helpers` directory:
```
MY_xx_helper.php
```
E.g:
```
MY_string_helper.php
```
Then you can call
```
$this->load->helper('string');
```
And it should load all the existing helper functions as well as the new ones you add. | Doing that you can not only add new functions but replace exising helper functions. | How to Extend a Helper in CodeIgniter? | [
"",
"php",
"codeigniter",
""
] |
I have 3 base representations for positive integer numbers:
1. Decimal, in unsigned long variable (e.g. *unsigned long int NumDec = 200*).
2. Hex, in string variable (e.g. *string NumHex = "C8"*)
3. Binary, in string variable (e.g. *string NumBin = "11001000"*)
I want to be able to convert between numbers in all 3 representations in the most efficient way. I.e. to implement the following 6 functions:
```
unsigned long int Binary2Dec(const string & Bin) {}
unsigned long int Hex2Dec(const string & Hex) {}
string Dec2Hex(unsigned long int Dec) {}
string Binary2Hex(const string & Bin) {}
string Dec2Binary(unsigned long int Dec) {}
string Hex2Binary(const string & Hex) {}
```
What is the most efficient approach for each of them? I can use C and C++, but not boost.
Edit: By "efficiency" I mean time efficiency: Shortest execution time. | As others have pointed out, I would start with [`sscanf()`](http://en.cppreference.com/w/cpp/io/c/fscanf), [`printf()`](http://en.cppreference.com/w/cpp/io/c/fprintf) and/or [`strtoul()`](http://en.cppreference.com/w/cpp/string/byte/strtoul). They are fast enough for most applications, and they are less likely to have bugs. I will say, however, that these functions are more generic than you might expect, as they have to deal with non-ASCII character sets, with numbers represented in any base and so forth. For some domains it is possible to beat the library functions.
So, measure first, and if the performance of these conversion is really an issue, then:
1) In some applications / domains certain numbers appear very often, for example zero, 100, 200, 19.95, may be so common that it makes sense to optimize your functions to convert such numbers with a bunch of if() statements, and then fall back to the generic library functions.
2) Use a table lookup if the most common 100 numbers, and then fall back on a library function. Remember that large tables may not fit in your cache and may require multiple indirections for shared libraries, so measure these things carefully to make sure you are not decreasing performance.
You may also want to look at boost lexical\_cast functions, though in my experience the latter are relatively compared to the good old C functions.
Tough many have said it, it is worth repeating over and over: do not optimize these conversions until you have evidence that they are a problem. If you do optimize, measure your new implementation to make sure it is faster *and* make sure you have a ton of unit tests for your own version, because you will introduce bugs :-( | I would suggest just using [sprintf](http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/) and [sscanf](http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/).
Also, if you're interested in how it's implemented you can take a look at the [source code](http://ftp.gnu.org/gnu/glibc/) for [glibc, the GNU C Library](http://www.gnu.org/software/libc/). | Efficiently convert between Hex, Binary, and Decimal in C/C++ | [
"",
"c++",
"c",
"binary",
"decimal",
"hex",
""
] |
I need a quick checksum (as fast as possilbe) for small strings (20-500 chars).
I need the source code and that must be small! (about 100 LOC max)
If it could generate strings in Base32/64. (or something similar) it would be perfect. Basically the checksums cannot use any "bad" chars.. you know.. the usual (){}[].,;:/+-\| etc
*Clarifications*
It could be strong/weak, that really doesn't matter since it is only for behind-the-scenes purposes.
It need not contain all the data of the original string since I will be only doing comparison with generated checksums, I don't expect any sort of "decryption". | Quick implementation in C, no copyrights from my side, so use it as you wish. But please note that this is a very weak "checksum", so don't use it for serious things :) - but that's what you wanted, isn't it?
This returns an 32-bit integer checksum encoded as an string containing its hex value.
If the checksum function doesn't satisfy your needs, you can change the `chk += ((int)(str[i]) * (i + 1));` line to something better (f.e. multiplication, addition and bitwise rotating would be much better).
EDIT: Following hughdbrown's advice and [one of the answers he linked](https://stackoverflow.com/questions/3388029/strlen-function/3388126#3388126), I changed the `for` loop so it doesn't call `strlen` with every iteration.
```
#include <stdio.h>
#include <stdlib.h>
#include <string>
char* hextab = "0123456789ABCDEF";
char* encode_int(int i) {
char* c = (char*)malloc(sizeof(char) * 9);
for (int j = 0; j < 4; j++) {
c[(j << 1)] = hextab[((i % 256) >> 4)];
c[(j << 1) + 1] = hextab[((i % 256) % 16)];
i = (i >> 8);
}
c[8] = 0;
return c;
}
int checksum(char* str) {
int i;
int chk = 0x12345678;
for (i = 0; str[i] != '\0'; i++) {
chk += ((int)(str[i]) * (i + 1));
}
return chk;
}
int main() {
char* str1 = "Teststring";
char* str2 = "Teststring2";
printf("string: %s, checksum string: %s\n", str1, encode_int(checksum(str1)));
printf("string: %s, checksum string: %s\n", str2, encode_int(checksum(str2)));
return 0;
}
``` | schnaader's implementation is indeed very fast. Here it is in Javascript:
```
function checksum(s)
{
var chk = 0x12345678;
var len = s.length;
for (var i = 0; i < len; i++) {
chk += (s.charCodeAt(i) * (i + 1));
}
return (chk & 0xffffffff).toString(16);
}
```
Using Google Chrome, this function takes just 5ms to run for 1-megabyte strings, versus 330ms using a crc32 function. | Fast open source checksum for small strings | [
"",
"javascript",
"string",
"base64",
"checksum",
"base32",
""
] |
I have the following table:
```
CREATE TABLE `events` (
`evt_id` int(11) NOT NULL AUTO_INCREMENT,
`evt_name` varchar(50) NOT NULL,
`evt_description` varchar(100) DEFAULT NULL,
`evt_startdate` date NOT NULL,
`evt_enddate` date DEFAULT NULL,
`evt_starttime` time DEFAULT NULL,
`evt_endtime` time DEFAULT NULL,
`evt_amtpersons` int(11) DEFAULT NULL,
`sts_id` int(11) NOT NULL,
`adr_id` int(11) DEFAULT NULL,
`evt_amtPersonsSubs` int(11) DEFAULT NULL,
`evt_photo` varchar(50) DEFAULT NULL,
`sys-mut-dt` timestamp NULL DEFAULT NULL,
`sys-mut-user` varchar(20) DEFAULT NULL,
`sys-mut-id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`evt_id`),
KEY `sts_id` (`sts_id`),
KEY `adr_id` (`adr_id`),
CONSTRAINT `sts_id` FOREIGN KEY (`sts_id`) REFERENCES `statusses` (`sts_id`) O
N DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1
```
Now I have got two problems:
Here is my query:
```
INSERT INTO `events`(`evt_name` , `evt_description` , `evt_startdate` , `evt_enddate` , `evt_starttime` , `evt_endtime` , `evt_amtpersons` , `sts_id` , `adr_id` , `evt_amtPersonsSubs` , `evt_photo` , `sys-mut-user` , `sys-mut-id`) VALUES ('asf' , 'asf' , '2009-04-02' , '2009-04-22' , '00:00:00' , '00:00:00' , '3' , '1' , '' , '' , '' , 'test' , '1')
```
1. When I execute this query through my php programs I get no error. But when I execute the query in a shell directly on the mysql database I get two warnings. How can I get PHP to alert me when there are warnings because if there are warnings mysql doesn't do the insert.
2. About the warnings:
| Warning | 1366 | Incorrect integer value: '' for column 'adr\_id' at row 1
| Warning | 1366 | Incorrect integer value: '' for column 'evt\_amtPersonsSubs' a t row 1
How can I get rid of these warnings. Tried to make some changes but it didn't work out so far. | You are inserting an empty string. You should remove the '' and put a number in that field
As you said, the column does not have to have a value specified when you insert. The fact is indicated by the "DEFAULT NULL" for that column at table creation. This fact, however, means that if you *do* *not* specify the column name in your list of columns while doing INSERT (and therefore you will not specify the corresponding value either), then the tuple can be inserted anyway, and for that column value you will get a NULL automagically by default.
However, in your query you specify that you are going to insert that column value, and the column value you say is '' (an empty string). This is of course not valid, because that column accepts integers (or NULL, because you havent' declared the column NOT NULL), and an empty string is an empty string, not an integer.
The SQL server is generous and accepts the empty string anyway (probably it casts it to zero) but reports you a warning. If you set a strict mode for the server (something I strongly suggest you to do), you will get an error and the insert will fail.
Please note that if you follow my suggestion of setting strict mode, this is server wide, involving all your databases and all your tables (at least with the mysql released one year ago). If you have awfully written software that need a forgiving server, then you cannot use it. | The error message tells you that that the empty string ('') is not a valid value for an integer field - in this case the fields `adr_id` and `evt_amtPersonsSubs`. Did you mean to put NULL instead?
In PHP, you can retrieve the error or warning message, for the most recent query only, using the [mysql\_error()](https://www.php.net/manual/en/function.mysql-error.php) function. | mysql warnings | [
"",
"sql",
"mysql",
""
] |
I have a SQL statement from my application. I'd like to know which locks that statement acquires; how can I do that with SQL server?
The statement has been involved in a deadlock, which I'm trying to analyze; I cannot reproduce the deadlock.
I'm running on MS SQL Server 2005. | I would suggest that you turn on the Deadlock Detection Trace Flags in the first instance, rather than running a Profiler Trace indefinitely.
This way, the event details will be logged to the SQL Server Error Log.
Review the following Books Online reference for details of the various trace flags. You need to use 1204 and/or 1222
<http://msdn.microsoft.com/en-us/library/ms188396(SQL.90).aspx>
Be sure to enable the trace flags with server scope and not just the current session. For example use:
```
DBCC TRACEON(1222,-1)
``` | You can run the statement in a transaction, but not commit the transaction. Since the locks will be held until the transaction is committed, this gives you time to inspect the locks. (Not indefinitely, but like 5 minutes by default.)
Like:
```
BEGIN TRANSACTION
select * from table
```
Then open Management Studio and check the locks. They're in Management -> Activity Monitor -> Locks by Object or Locks by Process. After you're done, run:
```
COMMIT TRANSACTION
```
to free the locks. | Finding out which locks that are acquired in a query on SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?
For example:
```
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
``` | ## PHP 8.0 and higher
Since PHP 8.0 you can use:
[`str_starts_with`](https://www.php.net/manual/en/function.str-starts-with) and
[`str_ends_with`](https://www.php.net/manual/en/function.str-ends-with)
##### Example
```
var_dump(str_starts_with('|apples}', '|'));
var_dump(str_ends_with('|apples}', '}'));
```
## PHP before 8.0
```
function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
```
```
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
``` | ### PHP < 8
You can use [`substr_compare`](https://www.php.net/manual/en/function.substr-compare.php) function to check start-with and ends-with:
```
function startsWith($haystack, $needle) {
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
```
This should be one of the fastest solutions on PHP 7 ([benchmark script](https://gist.github.com/salmanarshad2000/99ce15b5be1bd12d7523939397eec20c)). Tested against 8KB haystacks, various length needles and full, partial and no match cases. `strncmp` is a touch faster for starts-with but it cannot check ends-with. | startsWith() and endsWith() functions in PHP | [
"",
"php",
"string",
""
] |
we have a problem [cit.]
I need to assign a callback dynamically within a class, in base of a variable param: my goal is to have **just one** class (and not a main class and many extender sub-class), and inside this class if a value is X, then the funcitonX must be used, if is Y, the functionY.
I know i cant explain well, i hope my example will do:
```
class plzComplicateMyLife{
public $vehicle;
public $kindVehicle;
public $dynamicFunction;
public function __construct($vehicle, $kindVehicle){
$this->kindVehicle = $kindVehicle;
$this->vehicle = $vehicle;
switch($kindVehicle){
case 'cycle':
$this->dynamicFunction = "isACycle";
break;
case 'car':
$this->dynamicFunction = "isACar";
break;
}
//here come the problem, i need to call the callback store in dynamicFunction.
//i tried:
//call_user_func($this->$this->dinamicFunction, $this->vehicle);
//error: Catchable fatal error: Object of class plzComplicateMyLife could not be converted to string in [...]
//call_user_func("plzComplicateMyLife::".$this->dynamicFunction);
//Warning: call_user_func(plzComplicateMyLife::isACar) [function.call-user-func]: First argument is expected to be a valid callback in [...]
//$this->dynamicFunction();
//Fatal error: Call to undefined method plzComplicateMyLife::dynamicFunction() in [...]
//so, how can i do that?
}
public function isACycle($vehicle){
echo 'im a cycle, model: '.$vehicle.'<br />';
}
public function isACar($vehicle){
echo 'im a car, model: '.$vehicle.'<br />';
}
//i know this has no sense, in this example at least.
public function printKind(){
//call_user_func($this->$this->dinamicFunction, $this->vehicle);
//call_user_func("plzComplicateMyLife::".$this->dynamicFunction);
//then?
}
}
$maserati = new plzComplicateMyLife('maserati4', 'car');
//then, maybe, outside the class i'll need to recover the callback:
$maserati->printKind();
```
**EDIT**:
As Rob said, polymorphism would be really a good solution.
But the problem is that, in this case, i really **must** have the same declaration for every class instance, changing only the parameters...e.g:
```
$maserati = new plzComplicateMyLife('maserati4', 'car');
$ducati = new plzComplicateMyLife('maserati4', 'cycle');
//is good
//becose i cant have:
$maserati = new plzComplicateMyLifeWithACar('maserati4');
$ducati = new plzComplicateMyLifeWithACycle('maserati4');
``` | In response to your edit, could you not do something like this instead?
```
abstract class MethodOfTransport {
protected $model;
public function __construct($model) {
$this->model = $model;
}
abstract public function printKind();
public static function create($model, $type) {
$object = new $type($model);
return $object;
}
}
class cycle extends MethodOfTransport {
public function printKind() {
echo 'im a cycle, model: '.$this->model.'<br />';
}
}
class car extends MethodOfTransport {
public function printKind() {
echo 'im a car, model: '.$this->model.'<br />';
}
}
$maserati = MethodOfTransport::create('maserati4', 'car');
$maserati->printKind();
$ducati = MethodOfTransport::create('maserati4', 'cycle');
$ducati->printKind();
``` | Polymorphism is the way to go here but for future reference you can also do this:
```
public function printKind() {
$this->{$this->dynamicFunction}($this->vehicle);
}
``` | PHP: 'Dynamic' callback from inside/outside a class | [
"",
"php",
"class",
"callback",
""
] |
I'm not really sure how to ask this question. Suppose I have a class that needs to access certain properties of a Control (for example, Visible and Location). Perhaps I want to use the same class to access properties of another item that have the same name, but the class might not derive from Control. So I tried making an interface:
```
public interface IThumbnail {
bool Visible { get; set; }
int Height { get; set; }
int Width { get; set; }
Image Image { get; set; }
Point Location { get; set; }
event EventHandler Click;
}
```
Note that, for example, PictureBox happens to implement this interface. However, because the class definition does not *say* that it implements IThumbnail, I can't cast PictureBoxes to IThumbnails--I get an InvalidCastException at runtime. But why can't the CLR 'figure out' that PictureBox really does implement IThumbnail (it just doesn't explicitly say it does).
Also, what should I do to handle this situation? I want a way to access *some* of the PictureBox's properties without having my class know it's modifying a PictureBox.
Thx, Sam
PS- I'm a newbie to interface programming, so I apologize if this is a stupid q. | It's not a stupid question, it's a good one. :)
What you're asking for on the interface is commonly referred to as "[duck-typing](http://en.wikipedia.org/wiki/Duck_typing)." It isn't supported right now, but C#4.0 will support it via the new "[`dynamic`](https://stackoverflow.com/questions/301479/show-me-the-way-to-use-new-dynamic-keyword-in-c-4-0)" keyword.
You've really got three choices that I'm aware of at this point:
1. You can go up the tree until you find the common ancestor (probably [`Component`](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx)) and then downcast to your supported types. If the downcast fails, you throw or handle appropriately.
**Pro:** Minimal code duplication.
**Con:** You're trading away compile-time type safety for runtime type safety. You have to add error checking/handling for invalid casts.
**Code:**
```
public void UseThumbnail(Component c)
{
PictureBox p = c as PictureBox;
if(p != null) // do whatever
// so forth
}
```
2. You can duplicate functionality as appropriate for everything that you need to implement this functionality for.
**Pro:** Maintain compile time type safety
**Con:** You're duplicating code for different types. This can grow into a significant maintenance burden, especially if you're handling more than two similar classes.
**Code:**
```
public void UsePictureBox(PictureBox p)
{
// Some code X
}
public void UseOtherControl(OtherControl p)
{
// Some code X
}
```
3. You can create your special interface and subclass the classes you want to support to expose that common functionality.
**Pro:** You get compile time safety and can program against your new interface.
**Con:** You have to add an empty subclass for everything you're dealing with, and you need to use them.
**Code:**
```
public class ThumbnailPictureBox : PictureBox, IThumbnail
{ }
``` | I guess you would have to make you own class that derives from PictureBox. That new class would also implement IThumbnail.
```
public class MyPictureBox : PictureBox, IThumbnail {
}
``` | Interfacing common functionality between controls | [
"",
"c#",
"interface",
""
] |
I wanted a number that would remain unique for a day (24 hours). Following is the code that I came up with; I was wondering about its fallacies/possible risks; 'I believe' this guarantees a 12 digit unique number for a day atleast.
Logic is to get the current date/time (hhmmssmmm) and concat the first four bytes of query performance counter result.
```
__forceinline bool GetUniqueID(char caUID[MAX_STRING_LENGTH])
{
//Logic: Add HHMMSSmmm with mid 3 bytes of performance counter.
//Guarantees that in a single milli second band (0 to 999) the three bytes
//of performance counter would always be unique.
//1. Get system time, and use
bool bStatus = false;
try
{
SYSTEMTIME localtime;
GetLocalTime(&localtime);//Get local time, so that we may pull out HHMMSSmmm
LARGE_INTEGER li;
char cNT[MAX_STRING_LENGTH];//new time.
memset(cNT, '\0', sizeof(cNT));
try
{
//Try to get the performance counter,
//if one is provided by the OEM.
QueryPerformanceCounter(&li);//This function retrieves the current value of the
//high-resolution performance counter if one is provided by the OEM
//We use the first four bytes only of it.
sprintf(cNT, "%u", li.QuadPart);
}
catch(...)
{
//Not provided by OEM.
//Lets go with the GetTickCounts();
//ddHHMMSS + 4 bytes of dwTicks
sprintf(cNT,"%04d", GetTickCount());
}
//Get the first four bytes.
int iSkipTo = 0;//This is incase we'd decide to pull out next four bytes, rather than first four bytes.
int iGetChars = 4;//Number of chars to get.
char *pSub = (char*) malloc(iGetChars+1);//Clear memory
strncpy(pSub, cNT + iSkipTo, iGetChars);//Get string
pSub[iGetChars] = '\0'; //Mark end.
//Prepare unique id
sprintf(caUID, "%02d%02d%02d%3d%s",
localtime.wHour,
localtime.wMinute,
localtime.wSecond,
localtime.wMilliseconds,
pSub); //First four characters concat.
bStatus = true;
}
catch(...)
{
//Couldnt prepare. There was some problem.
bStatus = false;
}
return bStatus;
}
```
Following is the output that I get:
Unique:[125907 462224]
Unique:[125907 462225]
Unique:[125907 462226]
Unique:[125907 462227]
Unique:[125907 462228]
Unique:[125907 462230]
Unique:[125907 462231]
Unique:[125907 462232]
Unique:[125907 462233]
Unique:[125907 462234]
Unique:[125907 462235]
Unique:[125907 462237]
Unique:[125907 462238]
Unique:[125907 462239]
Unique:[125907 462240]
Unique:[125907 462241]
Unique:[125907 462243]
Unique:[125907 462244]
Unique:[125907 462245]
Unique:[125907 462246]
Unique:[125907 462247]
Unique:[125907 462248]
Unique:[125907 462249]
Unique:[125907 462251]
Unique:[125907 462252]
Unique:[125907 462253]
Unique:[125907 462254]
Unique:[125907 462255]
Unique:[125907 462256]
Unique:[125907 462257]
Unique:[125907 462258]
Millisecond changed, 46
Unique:[125907 622261]
Unique:[125907 622262]
Unique:[125907 622263]
Unique:[125907 622264]
Unique:[125907 622265]
Unique:[125907 622267]
Unique:[125907 622268]
Unique:[125907 622269]
Unique:[125907 622270]
Unique:[125907 622271]
Unique:[125907 622273]
Unique:[125907 622274]
Unique:[125907 622275]
Unique:[125907 622276]
Unique:[125907 622277]
Unique:[125907 622278]
Unique:[125907 622279]
Unique:[125907 622281]
Unique:[125907 622282]
Unique:[125907 622283]
Unique:[125907 622284]
Unique:[125907 622285]
Unique:[125907 622286]
Unique:[125907 622288]
Unique:[125907 622289]
Unique:[125907 622290]
Unique:[125907 622291]
Unique:[125907 622292]
Unique:[125907 622293]
Unique:[125907 622295]
Unique:[125907 622296]
Unique:[125907 622297]
Unique:[125907 622298]
Unique:[125907 622299]
Unique:[125907 622300]
Unique:[125907 622301]
Unique:[125907 622302]
Unique:[125907 622304]
Unique:[125907 622305]
Unique:[125907 622306]
Millisecond changed, 62
Unique:[125907 782308]
Unique:[125907 782310]
Unique:[125907 782311]
Unique:[125907 782312]
Unique:[125907 782313]
Unique:[125907 782314]
Unique:[125907 782316]
Unique:[125907 782317]
Unique:[125907 782318]
Unique:[125907 782319]
Millisecond changed, 125
Unique:[1259071402495]
Unique:[1259071402497]
Unique:[1259071402498]
Unique:[1259071402499]
Unique:[1259071402500]
Unique:[1259071402502]
Unique:[1259071402503]
Unique:[1259071402504]
Unique:[1259071402505]
Unique:[1259071402507]
Now I am thinking of keeping the generated IDs in a list, and compare the new generated one with the existing ones in the list. If it already exist in the list, then well I can certainly skip the number and generate another, but certainly and clearly this logic would fail.
Would appreciate your comments/suggestions/updates/etc.
Thanks
JT. | My solution was to get the system time and add a counter to that (pseudo code):
```
static int counter = 0;
static Time lastTime;
String getNextId() {
Time now = System.getTime();
if (lastTime == now)
counter ++;
else
counter = 0;
return now+counter;
}
```
This would guarantee that I'd get a new ID even when I called the method more often than `getTime()` changes. | The logic seems sound to me if you're running it from one machine on a single-core processor. I don't know if the same holds for a multi-core processor for successive calls, however. The generated numbers will definitely not be unique across machines, however.
Out of curiosity, is there a reason you're not using GUIDs?
Or since you are considering keeping the generated IDs in a list to compare, why can't you create a generator? Since you suggest storage is an option, if you store the last used number and increment it every use... You can even store a date and reset the counter every day if you wish. | 12 Digit Unique ID - Code reliability | [
"",
"c++",
"unique",
"uniqueidentifier",
""
] |
How do I get the external IP Address of a NAT using the windows library? I am trying to find any information on INATExternalIPAddressCallback, but have only found one example in C++ using unavailable interfaces to C#. Any guidance would be much appreciated.
-Karl | Sorry, that I don't answer with an existing API from Windows that uses the UPNP service, but it migh help you
You could also use a STUN-server on the internet, there are many open ones, every VOIP provider has one.
<http://en.wikipedia.org/wiki/STUN>
<https://www.rfc-editor.org/rfc/rfc3489>
e.g. open an UDP-socket, connect to stun.gmx.net on port 3478 and send a paket like this:
```
using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace xxx
{
class STUNPacket
{
static RNGCryptoServiceProvider m_rand=new RNGCryptoServiceProvider();
private byte[] m_requestid=new byte[16];
public STUNPacket()
{
m_rand.GetBytes(m_requestid);
}
public byte[] CreateRequest()
{
byte[] packet=new byte[0x1c] {
//Header:
0x00,0x01, //Art des STUN-Pakets: 0x0001=Binding Request
0x00,0x08, //Länge des Pakets ohne Header
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, //Transkations-ID
//Message-Attribute:
0x00,0x03, //Typ: Change-Request
0x00,0x04, //Länge: 4 Bytes
0x00,0x00,0x00,0x00 //Weder IP, noch Port ändern
};
for(int i=0;i<16;i++)
packet[i+4]=m_requestid[i];
return packet;
}
public IPEndPoint ParseResponse(byte[] paket)
{
if (paket.Length<20)
throw new Exception("STUN-Response zu kurz, um einen Header zu haben");
if (paket[0]!=1||paket[1]!=1)
throw new Exception("STUN-Reposne hat falschen Typ, muss Binding-Response sein");
for (int i=0;i<16;i++)
if (paket[i+4]!=m_requestid[i])
throw new Exception("STUN-Antwort hat falsche Transkations-ID");
int size=paket[2]*256+paket[3];
int pos=20;
for(;;)
{
if (size<4)
throw new Exception("Verbleibende Nachricht zu kurz für weiteren Attributheader, "+
"Mapped-Adress-Attribut nicht gefunden");
int attrsize=paket[pos+2]*256+paket[pos+3];
if (pos+4+attrsize>paket.Length)
throw new Exception("Attributheader hat Länge, die nicht mehr ins Paket passt");
//Wenn kein Mapped-Adress-Attribut, dann überspringen
if (paket[pos]!=0||paket[pos+1]!=1)
{
pos+=attrsize;
continue;
}
if (attrsize<8)
throw new Exception("Mapped-Adress-Attribut ist zu kurz");
if (paket[pos+5]!=1)
throw new Exception("Adreßfamilie von Mapped-Adress ist nicht IPV4");
int port=paket[pos+6]*256+paket[pos+7];
IPAddress adress=new IPAddress(new byte[4] { paket[pos+8],paket[pos+9],paket[pos+10],paket[pos+11] });
return new IPEndPoint(adress,port);
}
}
}
```
}
The IP-address returned by ParseResponse should be your ip adress like the outside world sees it.
**Note that will not be able to get your external ip without either the help of an internet server or directly via upnp from your server** | On CodeProject the following article by harold aptroot describes what you want to do:
NAT traversal with UPnP in C#, without any libraries.
<http://www.codeproject.com/KB/IP/upnpnattraversal.aspx>
Off course this only works if your router supports UPnP.
from MSDN -- <http://msdn.microsoft.com/en-us/library/aa365074(VS.85).aspx>:
The INATExternalIPAddressCallback interface is implemented by the NAT application with UPnP technology. It provides a method that the system calls if the external IP address of the NAT computer **changes**.
Are you trying to get the external IP address once or do you want to be notified if it changes. You do not need to implement the callback for INATExternalIPAddressCallback if you just want to get the current external IP address | Trying to get NAT's external IPAddress with INATExternalIPAddressCallback in C# | [
"",
"c#",
"nat",
"upnp",
""
] |
I wrote a file parser for a game I'm writing to make it easy for myself to change various aspects of the game (things like the character/stage/collision data). For example, I might have a character class like this:
```
class Character
{
public:
int x, y; // Character's location
Character* teammate;
}
```
I set up my parser to read in from a file the data structure with syntax similar to C++
```
Character Sidekick
{
X = 12
Y = 0
}
Character AwesomeDude
{
X = 10
Y = 50
Teammate = Sidekick
}
```
This will create two data structures and put them in a map`<std::string, Character*>`, where the key string is whatever name I gave it (in this case Sidekick and AwesomeDude). When my parser sees a pointer to a class, like the teammate pointer, it's smart enough to look up in the map to fetch the pointer to that data structure. The problem is that I can't declare Sidekick's teammate to be AwesomeDude because it hasn't been placed into the Character map yet.
I'm trying to find the best way to solve this so that I can have my data structures reference objects that haven't yet been added to the map. The two easiest solutions that I can think of are (a) add the ability to forward declare data structures or (b) have the parser read through the file twice, once to populate the map with pointers to empty data structures and a second time to go through and fill them in.
The problem with (a) is that I also can decide which constructor to call on a class, and if I forward declare something I'd have to have the constructor be apart from the rest of the data, which could be confusing. The problem with (b) is that I might want to declare Sidekick and AwesomeDude in their own files. I'd have to make my parser be able to take a list of files to read rather than just one at a time (this isn't so bad I guess, although sometimes I might want to get a list of files to read from a file). (b) also has the drawback of not being able to use data structures declared later in the constructor itself, but I don't think that's a huge deal.
Which way sounds like a better approach? Is there a third option I haven't thought of? It seems like there ought to be some clever solution to this with pointer references or binding or something... :-/ I suppose this is somewhat subjective based on what features I want to give myself, but any input is welcome. | When you encounter the reference the first time, simply store it as a reference. Then, you can put the character, or the reference, or whatever on a list of "references that need to be resolved later".
When the file is done, run through those that have references and resolve them. | Well, you asked for a third option. You don't have to use XML, but if you follow the following structure, it would be very simple to use a SAX parser to build your data structure.
At any rate, instead of referencing a teammate, each character references a team (Blue team in this case). This will decouple the circular reference issue. Just make sure you list the teams before the characters.
```
<team>Blue</team>
<character>
<name>Sidekick</name>
<X>12</X>
<Y>0</Y>
<teamref>Blue</teamref>
</character>
<character>
<name>Sidekick</name>
<X>10</X>
<Y>50</Y>
<teamref>Blue</teamref>
</character>
``` | Generating data structures by parsing plain text files | [
"",
"c++",
"parsing",
"fileparsing",
""
] |
I just want to know how [DeviantArt.com](http://browse.deviantart.com/?order=24&offset=24) implemented the shadowing on each images.
If you look at the thumbnails, you'll see that the images are shadowed a bit. I think they done it with Javascript because when I turned off my Javascript the shadows were gone. And they are also using jQuery btw. | I believe its on the server side.
If you see: <http://sh.deviantart.com/x/170/100/logo3.png>
You can change the 'variables' to fit your dimensions.
Then I guess its just a background property on the image with some padding to place the image in the center. | Their javascript is obfuscated so it's pretty difficult to follow what's going on. If you inspect their images, you can see that they're encapsulated with a span with a class named "shadow" and it has a style of a background image like such :
```
<span style="background-image: url(http://sh.deviantart.com/x/150/134/logo3.png);" class="shadow">
```
---
But if you are looking for a client side way of adding shadows to images, check out this script: <http://www.netzgesta.de/corner/> | How did DeviantArt implemented the Shadowing in their images? | [
"",
"javascript",
"jquery",
""
] |
I am working on a problem where I need to perform a lot of embarrassingly parallelizable tasks. The task is created by reading data from the database but **a collection of all tasks would exceed the amount of memory** on the machine so tasks have to be created, processed and disposed. I am wondering what would be a good approach to solve this problem? I am thinking the following two approaches:
1. Implement a synchronized task queue. Implement a producer (task creater) that read data from database and put task in the queue (limit the number of tasks currently in the queue to a constant value to make sure that the amount of memory is not exceeded). Have multiple consumer processes (task processor) that read task from the queue, process task, store the result and dispose the task. What would be a good number of consumer processes in this approach?
2. Use .NET Parallel extension (PLINQ or parallel for), but I understand that a collection of tasks have to be created (Can we add tasks to the collection while processing in the parallel for?). So we will create a batch of tasks -- say N tasks at a time and do process these batch of tasks and read another N tasks.
What are your thoughts on these two approaches? | Use a ThreadPool with a bounded queue to avoid overwhelming the system.
If each of your worker tasks is CPU bound then configure your system initially so that the number of threads in your system is equal to the number of hardware threads that your box can run.
If your tasks aren't CPU bound then you'll have to experiment with the pool size to get an optimal solution for your particular situation
You may have to experiment with either approach to get to the optimal configuration.
Basically, test, adjust, test, repeat until you're happy. | I've not had the opportunity to actually use PLINQ, however I do know that PLINQ (like vanilla LINQ) is based on IEnumerable. As such, I think this might be a case where it would make sense to implement the task producer via C# iterator blocks (i.e. the yield keyword).
Assuming you are not doing any operations where the entire set of tasks must be known in advance (e.g. ordering), I would expect that PLINQ would only consume as many tasks as it could process at once. Also, [this article](http://msdn.microsoft.com/en-us/magazine/cc163329.aspx) references some strategies for controlling just how PLINQ goes about consuming input (the section titled "Processing Query Output").
**EDIT**: Comparing PLINQ to a ThreadPool.
According to [this MSDN article](http://msdn.microsoft.com/en-us/magazine/cc163340.aspx), efficiently allocating work to a thread pool is not at all trivial, and even when you do it "right", using the TPL generally exhibits better performance. | Embarrassingly parallelizable tasks in .NET | [
"",
"c#",
".net",
"parallel-processing",
""
] |
I need two functions that take a string and the number of characters to trim from the right and left side and return it. E.g.:
```
$str = "[test]";
$str = ltrim($str, 1); // Becomes 'test]'
$str = rtrim($str, 1); // Becomes 'test'
```
How can I do it? | ```
function my_rtrim($str, $count) {
return substr($str, 0, -$count);
}
function my_ltrim($str, $count) {
return substr($str, $count);
}
```
See [substr()](http://www.php.net/manual/en/function.substr.php). | [`substr`](http://php.net/substr):
```
substr("abcdef", 0, -1); // 'abcde'
substr("abcdef", 1); // 'bcdef'
```
But that's not how `ltrim`, `rtrim` functions usually work. They operate with substrings and not indexes.
And obviously
```
substr('abcdef', 1, -1)
```
does what you want in one go. | PHP ltrim() and rtrim() functions | [
"",
"php",
"string",
""
] |
When I declare a base class, should I declare all the functions in it as virtual, or should I have a set of virtual functions and a set of non-virtual functions which I am sure are not going to be inherited? | A function only needs to be virtual iff a derived class will implement that function in a different way.
For example:
```
class Base {
public:
void setI (int i) // No need for it to be virtual
{
m_i = i;
}
virtual ~Base () {} // Almost always a good idea
virtual bool isDerived1 () // Is overridden - so make it virtual
{
return false;
}
private:
int m_i;
};
class Derived1 : public Base {
public:
virtual ~Derived () {}
virtual bool isDerived1 () // Is overridden - so make it virtual
{
return true;
}
};
```
As a result, I would error the side of not having anything virtual unless you know in advance that you intend to override it or until you discover that you require the behaviour. The only exception to this is the destructor, for which its *almost* always the case that you want it to be virtual in a base class. | You should only make functions you intend and design to be overridden virtual. Making a method virtual is not free in terms of both maintenance and performance (maintenance being the much bigger issue IMHO).
Once a method is virtual it becomes harder to reason about any code which uses this method. Because instead of considering what one method call would do, you must consider what N method calls would do in that scenario. N represents the number of sub classes which override that method.
The one exception to this rule is destructors. They should be virtual in any class which is intended to be derived from. It's the only way to guarantee that the proper destructor is called during deallocation. | Should I declare all functions virtual in a base class? | [
"",
"c++",
""
] |
I need to convert large UTF-8 strings into ASCII. It should be reversible, and ideally a quick/lightweight algorithm.
How can I do this? I need the **source** code (using loops) or the **JavaScript** code. (should not be dependent on any platform/framework/library)
**Edit:** I understand that the ASCII representation will not look correct and would be larger (in terms of bytes) than its UTF-8 counterpart, since its an encoded form of the UTF-8 original. | You could use an ASCII-only version of Douglas Crockford's json2.js quote function. Which would look like this:
```
var escapable = /[\\\"\x00-\x1f\x7f-\uffff]/g,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
```
This will produce a valid ASCII-only, javascript-quoted of the input string
e.g. `quote("Doppelgänger!")` will be "Doppelg\u00e4nger!"
To revert the encoding you can just eval the result
```
var encoded = quote("Doppelgänger!");
var back = JSON.parse(encoded); // eval(encoded);
``` | Any UTF-8 string that is reversibly convertible to ASCII is already ASCII.
UTF-8 can represent any unicode character - ASCII cannot. | How to convert large UTF-8 strings into ASCII? | [
"",
"javascript",
"utf-8",
"character-encoding",
"ascii",
""
] |
1. I have a listbox with runat=server
2. Items are added to this listbox on the client side, using javascript
3. I would want to retrieve the items on the server side on the click of a button
The problem is in the Buttons's server side click handler, I cannot see the new items added to the listbox. Only the items that were there on page\_load are displayed. How do i accomplish what i want to do
# Edit 1
My Code Is like this
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["gameID"] == null)
{
//Populate Listbox
//Set gameid in viewstate
}
//Add javascript handlers to buttons
btnSomeButton.Attributes.Add("onclick", "aJavaScriptFunction");
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
ListItemCollection x = ListBoxRanks.Items;
//Here items is has just those items that are added to the listbox on page load
}
``` | Ah when abstractions leek :)
Web server controls are serialised to view state before the response is sent, the control is recreated on postback and the options all put back from view state.
When you add option items client side they are not added to viewstate. The only way is to use your own hidden field to serialise client side additions and read them on postback or ajax the additions serverside. | You should use ajax to add items to the dropdown list. It will ensure your viewstate is in sync with the serverside dropdown control. | Access list box items added on client side | [
"",
"c#",
"asp.net",
""
] |
I have an open source Java database migration tool (<http://www.liquibase.org>) which I am considering porting to .Net.
The majority of the tool (at least from a complexity side) is around logic like "if you are adding a primary key and the database is Oracle use this SQL. If database is MySQL use this SQL. If the primary key is named and the database is Postgres use this SQL".
I could fork the Java codebase and covert it (manually and/or automatically), but as updates and bug fixes to the above logic come in I do not want to have to apply it to both versions. What I would like to do is move all that logic into a form that can be compiled and used by both Java and .Net versions naively.
The code I am looking to convert does not contain any advanced library usage (JDBC, System.out, etc) that would vary significantly from Java to .Net, so I don't think that will be an issue (at worst it can be designed around).
So what I am looking for is:
* A language in which I can code common parts of my app in and compile it into classes usable by the "standard" languages on the target platform
* Does not add any runtime requirements to the system
* Nothing *so* strange that it scares away potential contributors
I know Python and Ruby both have implementations on for the JVM and CLR. How well do they fit my requirements? Has anyone been successful (or unsuccesful) using this technique for cross-platform applications? Are there any gotcha's I need to worry about? | Check out the [Fantom programming language](http://fantom.org/). It has its own Java-like/C#-like syntax but can target either the Java VM or .NET CLR.
Their ["Why Fantom"](http://fantom.org/doc/docIntro/WhyFantom.html) page gives a high-level overview of their approach to portability versus dynamic languages running on a VM. | You might have some luck using [IKVM.NET](http://en.wikipedia.org/wiki/IKVM). I'm not sure on its exact status, but it's worth a try if you're insistent on running Java code on the .NET Framework. It includes a .NET implementation of the Java base class library, so it seems reasonably complete.
The only other option I might suggest is porting the code to the [J#](http://en.wikipedia.org/wiki/J_Sharp) language, a full .NET language (although not first class in the sense that C# or VB.NET is). The language was designed so that the differences with Java were minimal. | JVM/CLR Source-compatible Language Options | [
"",
"java",
".net",
"programming-languages",
""
] |
Maybe it's just doesn't exist, as I cannot find it. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported? | The logging module doesn't appear to support this. In the long run you'd probably be better off creating a new module, and adding this feature via sub-classing the items in the existing logging module to add the features you need, but you could also achieve this behavior pretty easily with a decorator:
```
class CallCounted:
"""Decorator to determine number of calls for a method"""
def __init__(self,method):
self.method=method
self.counter=0
def __call__(self,*args,**kwargs):
self.counter+=1
return self.method(*args,**kwargs)
import logging
logging.error = CallCounted(logging.error)
logging.error('one')
logging.error('two')
print(logging.error.counter)
```
Output:
```
ERROR:root:one
ERROR:root:two
2
``` | You can also add a new Handler to the logger which counts all calls:
```
class MsgCounterHandler(logging.Handler):
level2count = None
def __init__(self, *args, **kwargs):
super(MsgCounterHandler, self).__init__(*args, **kwargs)
self.level2count = {}
def emit(self, record):
l = record.levelname
if (l not in self.level2count):
self.level2count[l] = 0
self.level2count[l] += 1
```
You can then use the dict afterwards to output the number of calls. | How many times was logging.error() called? | [
"",
"python",
"logging",
"python-logging",
""
] |
I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision!
Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And it seems to work.
My question is: if it happens that the program needs to ask the user for a choice, how can I return this value to my python script? To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ?
The second and most important question is: how can I return a value from a web page to my "original" python module? In python I would simply make a
```
return choice
```
but with a web page I have no idea how to do it.
Recap:
1. Starting from a web page, I run a cgi script ! Done
2. This CGI script runs my python program... Done
3. If the program is not able to take a decision,
3a create a web page with the possible choices I can do it
3b display the created web page ????????
3c return the response to the original python module ???????? | "Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ??"
This is all very simple.
However, you need to read about what the web really *is*. You need to read up on web servers, browsers and the HTTP protocol.
Here's the golden rule: **A web server responds to HTTP requests with a web page.**
The second part of that rules is: **A Request is a URL and a method (GET or POST).** There's more to a request, but that's the important part.
That's all that ever happens. So, you have to recast your use case into the above form.
Person clicks a bookmark; browser makes an empty request (to a URL of "/") and gets a form.
Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets one of two things.
* If your script worked, they get their page that says it all worked.
* If your script needed information, they get another form.
Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets the final page that says it all worked.
You can do all of this from a "CGI" script. Use mod\_wsgi and plug your stuff into the Apache web server.
Or, you can get a web framework. Django, TurboGears, web.py, etc. You'll be happier with a framework even though you think your operation is simple. | I think you could modify the Python script to return an error if it needs a choice and accept choices as arguments. If you do that, you can check the return value from your cgi script and use that to call the python script appropriately and return the information to the user.
Is there a reason why you can't call the python script directly? I suspect you'd end up with a neater implementation if you were to avoid the intermediate CGI.
What webserver are you using? What cgi language? Perl maybe? | CGI & Python - return choice to python script | [
"",
"python",
"cgi",
""
] |
Is there any browser I could embedd in C++ application on Windows?
I need all features typical browser has (HTTP client, cookies support, DOM style HTML parser, JavaScript engine) **except** rendering.
Because I don't need rendering capability (and that's rather big part of a browser) I would prefer a browser with non monolithic design so I wouldn't have to include rendering stuff into my project.
It would be nice if it had C++ rather than C API.
I need this embedded browser mainly because I have much trouble finding C++ HTML parser which could handle broken HTML like browsers do.
If you know any, please answer [Library Recommendation: C++ HTML Parser](https://stackoverflow.com/questions/489522/library-recommendation-c-html-parser) SO question or at least vote on it to increase a chance someone will give a good answer. | I'm a bit confused by your question regarding embedding a web browser for which you don't need rendering capabilities. A web browser is rendering web pages by definition, unless you just need HTTP and XML with JavaScript capabilities which is a subset of a browser functionalities?
If you need a web browser to embed in your C++ application, I would suggest to consider Qt that comes with the WebKit plugin. It is C++, LGPL and has a very nice IDE (Qt Creator). I tried Qt with Qt Creator on unix (Ubuntu) and it was very impressive. The debugger is a bit light but it is just the first version. The adapter of Qt into visual c++ 2008 is now free. | Sounds like all you need is something like [libcurl](http://curl.haxx.se/libcurl/) which is an HTTP library and will let you do GET/POST/etc.
When I think browser I generally think rendering/JavaScript and not HTTP library.
**Edit**
In that case I'd look at [WebKit](http://webkit.org/) (which I think has a C++ API) and hope you don't have to pull too much in.
**Edit Again**
On second thought (since rendering is such a big part of what browsers do), you might be better off using a stand-alone JS engine like [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) and a stand-alone XML parser like [Xerces-C](http://xerces.apache.org/xerces-c/) (plus maybe [tidy](http://tidy.sourceforge.net/) to make your HTML into XML). | What embedded browser for C++ project? | [
"",
"c++",
"browser",
""
] |
I'm getting linkage errors of the following type:
> Festival.obj : error LNK2019:
> unresolved external symbol "public:
> void \_\_thiscall Tree::add(class Price &)"
> (?add@?$Tree@VPrice@@@@QAEXAAVPrice@@@Z)
> referenced in function
> \_\_catch$?AddBand@Festival@@QAE?AW4StatusType@@HHH@Z$0
I used to think it has to do with try-catch mechanism, but since been told otherwise. This is an updated version of the question.
I'm using Visual Studio 2008, but I have similar problems in g++.
The relevant code:
In Festival.cpp
```
#include "Tree.h"
#include <exception>
using namespace std;
class Band{
public:
Band(int bandID, int price, int votes=0): bandID(bandID), price(price), votes(votes){};
...
private:
...
};
class Festival{
public:
Festival(int budget): budget(budget), minPrice(0), maxNeededBudget(0), priceOffset(0), bandCounter(0){};
~Festival();
StatusType AddBand(int bandID, int price, int votes=0);
...
private:
Tree<Band> bandTree;
...
};
StatusType Festival::AddBand(int bandID, int price, int votes){
if ((price<0)||(bandID<0)){
return INVALID_INPUT;
}
Band* newBand=NULL;
try{
newBand=new Band(bandID,price-priceOffset,votes);
}
catch(bad_alloc&){return ALLOCATION_ERROR;}
if (bandTree.find(*newBand)!=NULL){
delete newBand;
return FAILURE;
}
bandTree.add(*newBand);
....
}
```
In Tree.h:
```
template<class T>
class Tree{
public:
Tree(T* initialData=NULL, Tree<T>* initialFather=NULL);
void add(T& newData);
....
private:
....
};
```
Interestingly enough I do not have linkage errors when I try to use Tree functions when type T is a primitive type like an int. | Is there Tree.cpp? If there is, maybe you forgot to link it? Where is the implementation of Tree::add?
In addition I don't see where you call Tree::add. I guess it should be inside the try statement, right after the new?
Just a reminder:
For most compilers (i.e. those that practice separate compilation) the implementation of the member functions of a template class has to be visible during the compilation of the source file that uses the template class. Usually people follow this rule by putting the implementation of the member functions inside the header file.
Maybe Tree::add isn't inside the header? Then a possible solution in the discussed case will be to put Tree::add implementation inside the header file.
The difference between regular classes and template classes exists because template classes are not "real" classes - it is, well, a template. If you had defined your Tree class as a regular class, the compiler could have used your code right away. In case of a template the compiler first "writes" for you the real class, substituting the template parameters with the types you supplied. Now, compiler compiles cpp files one by one. He is not aware of other cpp files and can use nothing from other cpp files. Let's say your implementation of Tree:add looks like this:
```
void Tree::add(T& newData)
{
newData.destroyEverything();
}
```
It is totally legitimate as long as your T has method destroyEverything. When the compiler compiles Class.cpp it wants to be sure that you don't do with T anything it doesn't know. For example `Tree<int>` won't work because int doesn't have destroyEverything. The compiler will try to write your code with int instead of T and find out that the code doesn't compile. But since the compiler "sees" only the current cpp and everything it includes, it won't be able to validate add function, since it is in a separate cpp.
There won't be any problem with
```
void Tree::add(int& newData)
{
newData.destroyEverything();
}
```
implemented in a separate cpp because the compiler knows that int is the only acceptable type and can "count on himself" that when he gets to compile Tree.cpp he will find the error. | Update: using Tree functions with a primitive type doesn't result in a linking error.
I updated my question in light of some of the things that were said. | Throw-catch cause linkage errors | [
"",
"c++",
"visual-studio-2008",
"templates",
"try-catch",
"linker-errors",
""
] |
What should go into the top level namespace? For example, if I have MyAPI.WebLogic, MyAPI.Compression, etc. If I put classes into the top level namespace, am I violating the principle of encapsulation? | Depends what the classes are.
One guideline I try to follow is that dependencies between namespaces shouldn't follow a cycle. In other words, low-level namespaces can't access types from higher-level namespaces.
This means that the top-level MyAPI namespace must contain either:
* High-level code: code that's allowed to look inside MyAPI.WebLogic and MyAPI.Compression
* Or, low-level code: code that's used by MyAPI.WebLogic and/or MyAPI.Compression
Patrick Smacchia has written a lot on the advantages of structuring your code in this way, including on this site: [Detecting dependencies between namespaces in .NET](https://stackoverflow.com/questions/304967/detecting-dependencies-between-namespaces-in-net) | Namespaces are not for OOP related concepts like encapsulation. They're for organization, so organize it in a way that what makes sense to your application. Most the work I do on websites has a business library and most often it's all tucked under a single namespace. | What should go into a top level namespace? | [
"",
"c#",
".net",
"vb.net",
"namespaces",
"oop",
""
] |
I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
```
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";
```
I don't get any error, but the script isn't run. When I run the script manually, I see the result. | Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.
```
private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
{
ProcessStartInfo startInfo;
Process process;
string ret = "";
try
{
startInfo = new ProcessStartInfo(@"c:\python25\python.exe");
startInfo.WorkingDirectory = workingDirectory;
if (pyArgs.Length != 0)
startInfo.Arguments = script + " " + pyArgs;
else
startInfo.Arguments = script;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
process = new Process();
process.StartInfo = startInfo;
process.Start();
// write to standard input
foreach (string si in standardInput)
{
process.StandardInput.WriteLine(si);
}
string s;
while ((s = process.StandardError.ReadLine()) != null)
{
ret += s;
throw new System.Exception(ret);
}
while ((s = process.StandardOutput.ReadLine()) != null)
{
ret += s;
}
return ret;
}
catch (System.Exception ex)
{
string problem = ex.Message;
return problem;
}
}
``` | [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) should work. if it doesn't, would you post your code and the error you are getting? | How to shell execute a file in C#? | [
"",
"c#",
".net",
""
] |
Recently I started reading (just a bit) the [current draft](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2857.pdf) for the future C++11 standard.
There are lots of new features, some of them already available via Boost Libs. Of course, I'm pretty happy with this new standard and I'd like to play with all the new features as soon as possibile.
Anyway, speaking about this draft with some friends, long-time C++ devs, some worries emerged. So, I ask you (to answer them):
**1) The language itself**
This update is huge, maybe too huge for a single standard update. Huge for the compiler vendors (even if most of them already started implementing some features) but also for the end-users.
In particular, a friend of mine told me "*this is a sort of new language*".
* Can we consider it a brand new language after this update?
* Do you plan to switch to the new standard or keep up with the "old" standard(s)?
**2) Knowledge of the language**
* How the learning curve will be impacted by the new standard?
* Teaching the language will be more difficult?
* Some features, while pretty awesome, seem a bit too "academic" to me (as definition I mean). Am I wrong?
* Mastering all these new additions could be a nightmare, couldn't it? | In short, no, we can't consider this a new language. It's the same language, new features. But instead of being bolted on by using the Boost libs, they're now going to be standard inclusions if you're using a compiler that supports the 0x standard.
One doesn't *have* to use the new standard while using a compiler that supports the new standard. One will have to learn and use the new standard if certain constraints exist on the software being developed, however, but that's a constraint with any software endeavor. I think that the new features that the 0x standard brings *will* make doing certain things easier and less error prone, so it's to one's advantage to learn what the new features are, and how they will improve their design strategy for future work. One will also have to learn it so that when working on software developed with it, they will understand what's going on and not make large boo-boos.
As to whether I will "*switch to the new standard*", if that means that I will learn the new standard and use it where applicable and where it increases my productivity, then yes, I certainly plan to *switch*. However, if this means that I will *limit* myself to only working with the new features of the 0x standard, then no, since much of my work involves code written before the standard and it would be a colossal undertaking to redesign everything to use the new features. Not only that, but it may introduce new bugs and performance issues that I'm not aware of without experience.
Learning C++ has always been one of the more challenging journeys a programmer can undertake. Adding new features to the language will not change the difficulty of learning its syntax and how to use it effectively, but the approach will change. People will still learn about pointers and how they work, but they'll also learn about smart pointers and how they're managed. In some cases, people will learn things differently than before. For example, people will still need to learn how to initialize things, but now they'll learn about Uniform Initialization and Initializer Lists as primary ways to do things. In some cases, perhaps understanding things will be easier with the addition of the new for syntax for ranges or the auto return type in a function declaration. I think that overall, C++ will become easier to learn and use while at the same time becoming easier to teach.
Mastering a language is a long-term goal, it can not be done over night. It's silly to think that one can have mastery over something as complex as C++ quickly. It takes practice, experience and debugging code to really hammer something in. Academically learning is one thing, but putting to use that knowledge is an entire different monster. I think that if one already has mastery of the C++ language, the new concepts will not pose too much of a burden, but a new comer may have an advantage in that they won't bother learning some of the more obsolete ways of doing things. | **1) The language itself**
As far as I'm aware, there are really no breaking changes between
C++'03 and C++'0x. The only one I can think of here relates to using
`auto` as a storage class specifier, but since it had no semantic
meaning I don't see that being an issue.
There are a lot of other academic fixes to the standard which are very
necssary, for example better descriptions for the layout of member
data. Finally, with multi-core/cpu architectures becoming the norm,
fixing the memory model was a must.
**2) Knowledge of the language**
Personally, I feel that for 99.9% of C++ developers the newer language is going to be easier to use. I'm specifically thinking of features such as auto, lambda's and constexpr. These features really should make using the language more enjoyable.
At a more advanced level, you have other features such as variadic
templates etc that help the more advanced users.
But there's nothing new here, I'm still surprised at the amount of
everyday C++ developers that haven't used (or even heard of) the STL.
From a personal perspective, the only feature I'm a bit concerned about in the new standard is that of concepts. As it is such a large change, the same problems that occurred with templates (ie. completely broken implementations) is a real danger.
**Update post FDIS going out for voting:**
As it happens, 'concepts' was dropped for C++ 0x and will be taken up again for C++ 1x. In the end there are *some* changes other than `auto` which could break your code, but in practise they'll probably be pretty rare. The key differences can be found in Appendix C.2 of the [FDIS (pdf)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3290.pdf). | C++11: a new language? | [
"",
"c++",
"c++11",
""
] |
I'm using Jbos AS 5 and the DatabaseServerLoginModule for the authorization. I've my application policy defined as (for example only, not the actual code):
```
<application-policy name = "jbossmq">
<authentication>
<login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule"
flag = "required">
<module-option name = "unauthenticatedIdentity">guest</module-option>
<module-option name = "dsJndiName">java:/MyDatabaseDS</module-option>
<module-option name = "principalsQuery">SELECT PASSWD FROM JMS_USERS WHERE USERID=?</module-option>
<module-option name = "rolesQuery">SELECT ROLEID, 'Roles' FROM JMS_ROLES WHERE USERID=?</module-option>
</login-module>
</authentication>
</application-policy>
```
Once the user is successfully authorized, how can I retrieve the user roles from my servlet? In the above code snippet, the roles are selected from the database, but where are they being stored? In session !? If yes, under which session variables?
Also, is it possible to use Ldap Authentication and Database Authorization combinely in JBoss? | Clinton is basically right, the
```
boolean HttpServletRequest.isUserInRole(String role)
```
method can be used to check if a user has a certain roles assigned. **However**, this method is intended to check for the J2EE roles defined byt the application (in EAR's descriptor, the application.xml).
During deploy, or by packaing an AS-specific descriptor within your EAR file, you need to specify mapping of the application server's user roles (these you set to principals in your login module) to the J2EE app. roles. | I am aware of the method:
```
boolean HttpServletRequest.isUserInRole(String role)
```
I know that doesn't give you a list of all the roles, but would it serve your purpose? | How to get the user roles in Servlet? | [
"",
"java",
"authentication",
"jboss",
""
] |
Right now I have a simple class that handles the parsing of XML files into ints that are useful to me. Looks something like this:
```
int* DataParser::getInts(){
*objectNumbers = new int[getSize()];
for (int i=0;i<getSize();i++){
objectNumbers[i]=activeNode->GetNextChild()->GetContent();
}
return objectNumbers;
}
```
In the main part of the program, I receive this by doing:
```
int* numbers= data->getInts();
///Do things to numbers[]
delete numbers;
```
Everything works fine until the delete command, which crashes everything. What is the proper way of doing this? | Part of the problem is that you are not pairing new[] with delete[]. This probably isn't the root of your bug here but you should get in the habbit of doing this.
The bug is almost certainly related to the code that you left commented out. Can you add some more context there so we can see what you're doing with the numbers value?
In general, I find it's **much** easier to use a vector for this type of problem. It takes the memory management out of the equation and has the added benefit of storing the size with the dynamic memory.
```
void DataParser::getInts(std::vector<int>& objectNumbers){
for (int i=0;i<getSize();i++){
objectNumbers.push_back(activeNode->GetNextChild()->GetContent());
}
}
...
std::vector<int> numbers;
data.getInts(numbers);
``` | You need to
```
delete [] numbers;
```
The rules is whenever you
```
ptr = new Type[...];
```
make sure you
```
delete [] ptr;
```
instead of the regular
```
delete ptr;
```
which will result in undefined behavior (thanks Neil Butterworth) and is intended for deletion of a single instance where ptr points, not an array. | How to handle passing runtime-sized arrays between classes in C++ | [
"",
"c++",
"arrays",
"memory",
""
] |
I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.
I saw NetworkX and igraph, but didn't see a way to output to ascii.
Do you have experience in this?
Thanks a lot!
Patrick
EDIT 1:
I actually found a library doing what I need, but it's in perl [Graph::Easy](http://bloodgate.com/perl/graph/manual/output.html) . I could call the code from python but I don't like the idea too much... still looking for a python solution :) | When you say 'simple network graph in ascii', do you mean something like this?
```
.===. .===. .===. .===.
| a |---| b |---| c |---| d |
'===' '===' '---' '==='
```
I suspect there are probably better ways to display whatever information it is that you have than to try and draw it on the console. If it's just a pipeline, why not just print out:
```
a-b-c-d
```
If you're sure this is the route, one thing you could try would be to generate a decent graph using [Matplotlib](http://matplotlib.sourceforge.net) and then post the contents to one of [the many image-to-ascii converters](https://www.ohloh.net/tags/ascii/python) you can find on the web. | [ascii-plotter](http://www.algorithm.co.il/blogs/index.php/ascii-plotter/) might do what you want... | Python ASCII Graph Drawing | [
"",
"python",
"graph",
"ascii",
""
] |
I have this simple code that records appends a log to a text file:
```
public static void RecordToFile(string filename, Log log)
{
TextWriter textWriter = new StreamWriter(Constants.APP_PATH +
"\\" + filename, true);
textWriter.WriteLine(log.ToString());
textWriter.Close();
}
```
This works perfectly in a Windows Forms application. However, using the [instsrv and srvany](http://support.microsoft.com/kb/137890) trick, I made this a Windows Service. The service runs fine, accesses the database, performs queries and all... Except for this StreamWriter. The log just doesn't get updated as it should. Any ideas why? | Most likely the service is running under user credentials that does not have access rights to that directory.
So check the properties dialog for the service, and check the Log On tab to see what it logs on as. | Possible Reasons:
1. Constants.APP\_PATH is pointing to a mapped drive - services don't run in the same environment as a logged-in user, so the path may not be valid
2. Permissions - depending on what user the service is running as, it may not have access to the same set of directories that the WinForms app did | Why doesn't StreamWriter work in a Windows Service? | [
"",
"c#",
".net",
"service",
"streamwriter",
""
] |
I want to check which CPU architecture is the user running, is it
i386 or X64 or AMD64. I want to do it in C#.
I know i can try WMI or Registry. Is there any other way apart from these two?
My project targets .NET 2.0! | You could also try (only works if it's not manipulated):
```
System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
``` | I know that this question is from the past, but as of 2017, there is now a simple method to know the architecture of the current process, in .net standard :
```
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture
```
The value returned is one of X86, X64, ARM, ARM64 and gives the architecture of the process it's running in. `OSArchitecture` returns the architecture of the installed operating system instead.
Links to the docs (pretty useless though...):
RuntimeInformation.ProcessArchitecture:
<https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation.processarchitecture?view=netstandard-1.4>
Architecture enumeration:
<https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.architecture?view=netstandard-1.4> | Identifying the CPU architecture type using C# | [
"",
"c#",
"architecture",
"cpu",
"identify",
""
] |
The following code snippet is from book Effective C#,
```
public event AddMessageEventHandler Log;
public void AddMsg ( int priority, string msg )
{
// This idiom discussed below.
AddMessageEventHandler l = Log;
if ( l != null )
l ( null, new LoggerEventArgs( priority, msg ) );
}
```
The AddMsg method shows the proper way to raise events. ***The temporary variable to reference the log event handler is an important safeguard against race conditions in
multithreaded programs. Without the copy of the reference, clients could remove event handlers between the if statement check and the execution of the event handler. By
copying the reference, that can't happen.***
Why can a temporary variable stop the client from removing event handler? I must be missing something here. | Delegate chains are immutable. Therefore, if another thread accesses "Log" and removes an eventhandler, Log gets assigned a new delegate chain. Therefore, when l is accessed, even if an eventhandler is removed from Log, it won't effect l as it will no longer be "pointing" to the same delegate chain. So yes, it does protect against race conditions, however you might end up with a scenario where one thread unsubscribes, but the evanthandler will still be called. | It doesn't stop the client from removing the event handler - it just means that you'll call that event handler anyway.
The important bit you may be missing is that delegates are immutable - when an event handler is removed, the value of `Log` will change to be the new delegate or `null`. That's okay though, because by that stage you're using `1` instead of `Log`. | Why can a temporary variable stop the client from removing event handler? | [
"",
"c#",
"multithreading",
"events",
""
] |
Duplicate:
> [website screenshots using php](https://stackoverflow.com/questions/757675/website-screenshots-using-php/757721)
Is it possible to take a screenshot of the current page using PHP? | If you're on windows. There's [imagegrabscreen()](http://is.php.net/manual/en/function.imagegrabscreen.php) | PHP doesn't render the page, the browser does.
[Here is a list of tools](http://mashable.com/2007/08/24/web-screenshots/) that let you do what you're after. | Screenshot of current page using PHP | [
"",
"php",
"mysql",
""
] |
I have two dynamic tables (tabx and taby) which are created and maintained through a php interface where columns can be added, deleted, renamed etc.
I want to read all columns simulataneously from the two tables like so;-
select \* from tabx,taby where ... ;
I want to be able to tell from the result of the query whether each column came from either tabx or taby - is there a way to force mysql to return fully qualified column names e.g. tabx.col1, tabx.col2, taby.coln etc? | In PHP, you can get the field information from the result, like so (stolen from a project I wrote long ago):
```
/*
Similar to mysql_fetch_assoc(), this function returns an associative array
given a mysql resource, but prepends the table name (or table alias, if
used in the query) to the column name, effectively namespacing the column
names and allowing SELECTS for column names that would otherwise have collided
when building a row's associative array.
*/
function mysql_fetch_assoc_with_table_names($resource) {
// get a numerically indexed row, which includes all fields, even if their names collide
$row = mysql_fetch_row($resource);
if( ! $row)
return $row;
$result = array();
$size = count($row);
for($i = 0; $i < $size; $i++) {
// now fetch the field information
$info = mysql_fetch_field($resource, $i);
$table = $info->table;
$name = $info->name;
// and make an associative array, where the key is $table.$name
$result["$table.$name"] = $row[$i]; // e.g. $result["user.name"] = "Joe Schmoe";
}
return $result;
}
```
Then you can use it like this:
```
$resource = mysql_query("SELECT * FROM user JOIN question USING (user_id)");
while($row = mysql_fetch_assoc_with_table_names($resource)) {
echo $row['question.title'] . ' Asked by ' . $row['user.name'] . "\n";
}
```
So to answer your question directly, the table name data is always sent by MySQL -- It's up to the client to tell you where each column came from. If you really want MySQL to return each column name unambiguously, you will need to modify your queries to do the aliasing explicitly, like @Shabbyrobe suggested. | ```
select * from tabx tx, taby ty where ... ;
``` | how to identify the source table of fields from a mysql query | [
"",
"php",
"mysql",
""
] |
Hello people I've been struggling to use sqlite in my C#2.0 application and I have finally decided to get rid of assumptions and ask really basic questions.
When I created a database say iagency with table users, from external tools like firefox plugging and another sqladmin tool I can't query it from sqlicommand inside vs2005 it displays `System.Data.SQLite.SQLiteException:Sqlite Error no such table users`, please be assured that I've made reference to `system.data.sqlite` installed with SQLite-1.0.61.0-setup
When I do the opposite like create a database and a table from VS server explorer and VS database gui tools it can't be queried neither but can be seen by other tools, but tables created through query from VS using stringbuilder eg create table bla bla. it can be display in a datagrid but none of the tools can see and display that table.
> WHAT DO I NEED EXACTLY TO MAKE SQLITE WORK IN MY APPLICATION?
I've tried to add `sqlite3.dll` of sqlitedll-3\_6\_14.zip downloaded from sqlite site under section precompiled binaries for windows as reference to my application but it fails with `make sure it's accessible an it's a valid assembly or com component`. | I downloaded this [SQLite-1.0.61.0-setup.exe](http://sourceforge.net/projects/sqlite-dotnet2/) Ran the installation then I wrote this to access the firefox favorites sqlite db.
```
using System.Data.SQLite; // Dont forget to add this to your project references
// If the installation worked you should find it under
// the .Net tab of the "Add Reference"-dialog
namespace sqlite_test
{
class Program
{
static void Main(string[] args)
{
var path_to_db = @"C:\places.sqlite"; // copied here to avoid long path
SQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_db + ";Version=3;New=True;Compress=True;");
SQLiteCommand sqlite_command = sqlite_connection.CreateCommand();
sqlite_connection.Open();
sqlite_command.CommandText = "select * from moz_places";
SQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader();
while (sqlite_datareader.Read())
{
// Prints out the url field from the table:
System.Console.WriteLine(sqlite_datareader["url"]);
}
}
}
}
``` | Try opening up the database in the command line SQLite tool (from [SQLite.org](http://www.sqlite.org/)), and check the schema.
You can check the schema in this way:
```
.schema
```
This will dump out all the SQL necessary to create the tables in the database. Make sure the table is there, with the name you assume it should have.
You do not need the .dll file from SQLite.org, all you need is the assemblies from [System.Data.SQLite](http://sqlite.phxsoftware.com/). | sqlite3.dll and system.data.sqlite.dll | [
"",
"c#",
"sqlite",
""
] |
So a friend was telling me how a game was hacked and how the technique worked. He then asked whats the best way to prevent that kind of attack. The most straight forward way i knew was to A) the shuffle the bits of important value B) hash the values and compare them every time (an int that holds the score or money is likely to be checked rarely).
Then i tried the implementation in C#, i couldnt overload the = operator. How can i do this?
ex code.
```
class EncryptVal <T>
{
T v;
public T operator = (T v2)
{
//shuffle bits
}
public T operator ()()
{
//return unshuffle bits
}
}
``` | You can encapsulate the value in the class and overload the implicit conversions to and from the class:
```
public class EncryptVal<T> {
private T _value;
private EncryptVal(T value) {
_value = value;
}
public static implicit operator EncryptVal<T>(T value) {
//shuffle bits
return new EncryptVal<T>(value);
}
public static implicit operator T(EncryptVal<T> value) {
//unshuffle bits
return value._value;
}
}
```
Usage:
```
// implicit conversion from int
EncryptVal<int> e = 42;
// implicit conversion to int
int i = e;
``` | You're looking for the `implicit` and `explicit` operator, rather than saying `=`. This allows you to define how things will work when cast implicitly (ie, just an assignment) and explicitly (ie, there's a casting operator).
```
public static implicit operator Type1(Type2 p) {}
public static explicit operator Type1(Type2 p) {}
``` | overload operator = in C#. How can i accept other types? | [
"",
"c#",
"operator-overloading",
""
] |
I've got multiple classes that, for certain reasons, do not follow the official `Equals` contract. In the overwritten `GetHashCode()` these classes simply return 0 so they can be used in a Hashmap.
Some of these classes implement the same interface and there are Hashmaps using this interface as key. So I figured that every class should at least return a different (but still constant) value in `GetHashCode()`.
The question is how to select this value. Should I simply let the first class return 1, the next class 2 and so on? Or should I try something like
```
class SomeClass : SomeInterface {
public overwrite int GetHashCode() {
return "SomeClass".GetHashCode();
}
}
```
so the hash is distributed more evenly? (Do I have to cache the returned value myself or is Microsoft's compiler able to optimize this?)
**Update:** It is not possible to return an individual hashcode for each object, because Equals violates the contract. Specifially, I'm refering to [this problem](https://stackoverflow.com/questions/580905/is-there-a-way-to-get-a-hashcode-of-a-float-with-epsilon). | I ran into this exact problem when writing a vector class. I wanted to compare vectors for equality, but float operations give rounding errors, so I wanted approximate equality. Long story short, overriding equals is a bad idea unless your implementation is symmetric, reflexive, and transitive.
Other classes are going to assume equals has those properties, and so will classes using those classes, and so you can end up in weird cases. For example a list might enforce uniqueness, but end up with two elements which evaluate as equal to some element B.
A hash table is the perfect example of unpredictable behavior when you break equality. For example:
```
//Assume a == b, b == c, but a != c
var T = new Dictionary<YourType, int>()
T[a] = 0
T[c] = 1
return T[b] //0 or 1? who knows!
```
Another example would be a Set:
```
//Assume a == b, b == c, but a != c
var T = new HashSet<YourType>()
T.Add(a)
T.Add(c)
if (T.contains(b)) then T.remove(b)
//surely T can't contain b anymore! I sure hope no one breaks the properties of equality!
if (T.contains(b)) then throw new Exception()
```
I suggest using another method, with a name like ApproxEquals. You might also consider overriding the == operator, because it isn't virtual and therefore won't be used accidentally by other classes like Equals could be.
If you really can't use reference equality for the hash table, don't ruin the performance of cases where you can. Add an IApproxEquals interface, implement it in your class, and add an extension method GetApprox to Dictionary which enumerates the keys looking for an approximately equal one, and returns the associated value. You could also write a custom dictionary especially for 3-dimensional vectors, or whatever you need. | I'm curious what the reasoning would be for overriding `GetHashCode()` and returning a constant value. Why violate the idea of a hash rather than just violating the "contract" and not overriding the `GetHashCode()` function at all and leave the default implementation from `Object`?
**Edit**
If what you've done is that so you can have your objects match based on their contents rather than their reference then what you propose with having different classes simply use different constants can WORK, but is highly inefficient. What you want to do is come up with a hashing algorithm that can take the contents of your class and produce a value that balances speed with even distribution (that's hashing 101).
I guess I'm not sure what you're looking for...there isn't a "good" scheme for choosing constant numbers for this paradigm. One is not any better than the other. Try to improve your objects so that you're creating a real hash. | C# How to select a Hashcode for a class that violates the Equals contract? | [
"",
"c#",
"hash",
"equals",
"gethashcode",
""
] |
I'm working on a simple JavaScript validation function for a html form, but have run into issues with it using IE7. I don't get any error messages, the form simply submits without validating. Firefox, and Opera work fine, so I'm really not sure what i am doing wrong here. I've googled around, but not found anything helpful, or maybe not Googling the right keywords.
\*Also, if anyone could recommend a good tool to use for debugging JavaScript in IE.
Any help will be appreciated.
```
<html>
<head>
<title>Hello!</title>
<style type="text/css">
.error {
font-family: Tahoma;
font-size: 8pt;
color: red;
margin-left: 50px;
display:none;
}
</style>
<script type="text/javascript">
function checkForm() {
age = document.getElementById("age").value;
name = document.getElementById("name").value;
comment = document.getElementById("comment").value;
parent = document.getElementById("parent").value;
phone = document.getElementById("phone").value;
sig = document.getElementById("sig").value;
player = document.getElementById("player").value;
iagree = document.getElementById("iagree").value;
if (age == "") {
hideAllErrors();
document.getElementById("ageError").style.display = "inline";
document.getElementById("age").select();
document.getElementById("age").focus();
return (false);
} else if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
return (false);
} else if (comment == "") {
hideAllErrors();
document.getElementById("commentError").style.display = "inline";
document.getElementById("comment").select();
document.getElementById("comment").focus();
return (false);
} else if (parent == "") {
hideAllErrors();
document.getElementById("parentError").style.display = "inline";
document.getElementById("parent").select();
document.getElementById("parent").focus();
return (false);
} else if (phone == "") {
hideAllErrors();
document.getElementById("phoneError").style.display = "inline";
document.getElementById("phone").select();
document.getElementById("phone").focus();
return (false);
} else if (sig == "") {
hideAllErrors();
document.getElementById("sigError").style.display = "inline";
document.getElementById("sig").select();
document.getElementById("sig").focus();
return (false);
} else if (player == "") {
hideAllErrors();
document.getElementById("playerError").style.display = "inline";
document.getElementById("player").select();
document.getElementById("player").focus();
return (false);
} else if (iagree != "I agree") {
hideAllErrors();
document.getElementById("iagreeError").style.display = "inline";
document.getElementById("iagree").select();
document.getElementById("iagree").focus();
return (false);
}
return (true);
}
function hideAllErrors() {
document.getElementById("ageError").style.display = "none"
document.getElementById("nameError").style.display = "none"
document.getElementById("commentError").style.display = "none"
document.getElementById("parentError").style.display = "none"
document.getElementById("phoneError").style.display = "none"
document.getElementById("sigError").style.display = "none"
document.getElementById("playerError").style.display = "none"
document.getElementById("iagreeError").style.display = "none"
}
</script>
</head>
<body>
<form onsubmit="return checkForm();" action="contact.php" method="post">
<div style="background: #ffffe5; padding:5px;">
<label for="isnew"><b>I am a new member:</b></label><input type="checkbox" id="isnew" name="isnew" value="New Member" /><br />
(If you are re-registering for the year, please leave this box unchecked)
</div>
<table>
<tr>
<td></td>
</tr>
<tr>
<td>
<b><label for="age">Your Age:</label></b><br />
<input type="text" id="age" name="age" maxlength="3" style="width:40px; background: #ffffe5;" value="" />
<div class="error" id="ageError">
Required: Please enter your age<br />
</div>
</td>
<td><b>Girl or Boy?:</b><br />
<select name="gender" size="1">
<option value="-1" selected="selected">
Choose One
</option>
<option value="Girl">
Girl
</option>
<option value="Boy">
Boy
</option>
</select></td>
</tr>
<tr>
<td><b><label for="name">Your Name:</label></b></td>
</tr>
<tr>
<td>
<input type="text" name="name" id="name" maxlength="40" value="" />
<div class="error" id="nameError">
Required: Please enter your name<br />
</div>
</td>
</tr>
<tr>
<td><b>Home Address:</b></td>
</tr>
<tr>
<td>
<textarea name="address" id="comment">
</textarea><br />
<div class="error" id="commentError">
Required: Please enter your address<br />
</div>
</td>
</tr>
<tr>
<td><b><label for="parent">Parent/Guardian Name:</label></b></td>
</tr>
<tr>
<td>
<input type="text" name="parent" id="parent" maxlength="40" value="" />
<div class="error" id="parentError">
Required: Please enter your parent or guardian's name<br />
</div>
</td>
</tr>
<tr>
<td><b>Address(If different from above):</b></td>
</tr>
<tr>
<td>
<textarea name="altaddress">
</textarea></td>
</tr>
<tr>
<td><b>Phone Details:</b></td>
</tr>
<tr>
<td>
<b><label for="phone">Best Contact Number:</label></b><br />
<input type="text" id="phone" name="contactphone" maxlength="40" value="" />
<div class="error" id="phoneError">
Required: Please enter a phone number<br />
</div>
</td>
<td><b>Mobile:</b><br />
<input type="text" name="contactmob" maxlength="40" /></td>
</tr>
<tr style="background: #ffffe5;">
<td><b>Medical Conditions:</b></td>
</tr>
<tr style="background: #ffffe5;">
<td>
<textarea name="medical">
</textarea></td>
<td><small>(If there are any medical conditions that trainers, and the club should know about, please list them here).</small></td>
</tr>
<tr>
<td><b>Player Agreement:</b></td>
</tr>
</table>
<div style="border: 1px solid #e0e0e0; padding:5px;">
(If under the age of 18 years of age, a parent or legal guardian must sign)<br />
I, <input type="text" name="agreename" id="sig" maxlength="40" style="border:none; background:#ffffe5;" value="" />
<div class="error" id="sigError">
<-(Required: Please enter your parent or guardian's name)
</div>being the parent/legal guardian of <input type="text" name="playername" maxlength="40" style="border:none; background:#ffffe5;" id="player" value="" />
<div class="error" id="playerError">
<-(Required: Please enter your child's name)
</div>hereby give consent for the above named player to register to play Australian Football.<br />
<br />
</div><br />
<br />
<div style="background: #ffffe5; padding:5px;">
By submitting this form, and signing in the field below, I hereby agree that I am <b>over 18yr's of age</b> and/or have all nessecary permissions to legally process this document.
<div style="maring:0; padding: 0;">
<div style="margin-bottom:5px;">
<b><label for="iagree">Please type this in the field below: <input type="text" style="background: #e0e0e0; width:45px; color:#000000;" disabled="disabled" value="I agree" /></label></b><br />
<br />
<input type="text" name="iagree" value="" id="iagree" />
<div class="error" id="iagreeError">
<-(Required: You must confirm this documents legality)
</div>
</div><br />
</div>
</div>
<div>
<input type="submit" name="submitreg" value="Join Our Club!" />
</div>
</form>
</body>
</html>
``` | The problem (bizarrely) is caused by having a global variable called "parent", which you're creating here:
```
parent = document.getElementById("parent").value;
```
JavaScript has its own variable called "parent", and you're overwriting it, and hence confusing the browser. You should declare yours as a local variable, like this:
```
var parent = document.getElementById("parent").value;
```
and that will make it work . It's good practice to always use "var" for that sort of variable anyway - do it for all the variables you're using.
As for a JavaScript debugger, you can use [FireBug](http://getfirebug.com/) to debug in FireFox. In Internet explorer, Visual Studio is good but expensive. Or you can use [Visual Web Developer](http://msdn.microsoft.com/en-gb/express/default.aspx) for free, via the instructions here: <http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/> | At a quick glance the problem seems to occur @ the line
document.getElementById("parent").value
You should really be using `var parent` here to explicitly declare it as a local variable.
At any rate, you've alot of code in their that could be sanity checked and refactored + you've got no exception handling at all...
This block repeats 8 times... for each var...
```
if (age == "") {
hideAllErrors();
document.getElementById("ageError").style.display = "inline";
document.getElementById("age").select();
document.getElementById("age").focus();
return (false);
}
```
That could easily be made
```
if(age == "") {
DoMyFunction("age", "ageError");
}
...
function DoMyFunction(a, b)
{
hideAllErrors();
document.getElementById(b).style.display = "inline";
document.getElementById(a).select();
document.getElementById(a).focus();
return (false);
}
```
And anywhere you have a document.getElementById("").value
You should really be doing a check here to make sure the getElementById doesn't return null.
```
var name = "";
var nametemp = document.getElementById("name");
if (nametemp != null)
name = nametemp.value;
``` | Onsubmit form validation function not working in IE | [
"",
"javascript",
"html",
"dom-events",
""
] |
Is there any trick to run .PHP files in windows XP from any folder by double clicking like HTML file ?
I use XAMPP but in this we need to put files ina special htdocs folder. I want to run file from any folder, desktop by double clicking. | After searching a lot I found a easy way to do this
> PHPScriptNet – Great portable application for those who learning PHP. PHPScriptNet can run your PHP script anywhere in Windows machine without installing PHP or any webserver.

<http://www.digitalcoding.com/free-software/webmaster-tools/PHPScriptNet-Portable-application-to-run-PHP-Script-from-windows.html> | There is a significant difference in viewing HTML files vs. PHP files:
**HTML** files are static files interpreted by the browser. When you open them, the PATH to the HTML file is passes as an argument to the default browser which interprets and displays the file.
**PHP** files on the other hand are required to be interpreted by a PHP interpreter (XAMPP, in your case) before the resulting HTML is rendered by a browser. In this case, the local file PATH would have to be translated to the corresponding local URL, then sent to the browser.
**Sample Solution**
You could write a simple script that replaces '/var/www/' with '<http://localhost:8888/>' (with a regular expression, for example) and passes that to the browser. Then, associate PHP files with your script. | how to run php file by double clicking from any folder like html files in windows xp? | [
"",
"php",
"wordpress",
"windows-xp",
""
] |
Do you have a favorite site or homegrown page in your toolbox to help you during development of your Javascript?
Something to help you:
* validate
* run
* debug, inspect
* unit test
Looking for somewhere to paste my JS into, click a Run button, and have it evaluate the statements. This might be for simple snippets for manipulation of numbers, strings, custom objects, etc.
**ANSWER** (since no answers before the question was closed actually address the requirements:
* [turb0js](http://www.turb0js.com/) - lets you step through the code without having to open the browser's console and hunt for the right JavaScript file. Also allows adding an HTML description to the code snippet, and comments from other users. DOM and Console methods don't work.
* jsbin with [`// noprotect`](http://jsbin.com/blog/protection#comment-1590869196) at the beginning of the code, to enable debugging in the browser console
Non-answers: Codepen (can't debug due to its autorun on edit creating a new script); JSFiddle (no direct support for the browser console) | Give a look to [JsBin](http://jsbin.com) it's a great online tool for collaborative JavaScript debugging...
You can easily incorporate the most popular JavaScript libraries, and you can even use it for Ajax Request Debugging...
Check the [introductory videos](http://jsbin.com/videos)... | [jsfiddle.net](http://jsfiddle.net/) is what you need | online Javascript code evaluation tools | [
"",
"javascript",
"debugging",
""
] |
Consider this string
```
hello awesome <a href="" rel="external" title="so awesome is cool"> stuff stuff
```
What regex could I use to match any occurence of `awesome` which doesn't appear within the title attribute of the anchor?
So far, this is what I've came up with (it doesn't work sadly)
```
/[^."]*(awesome)[^."]*/i
```
## **Edit**
I took [Alan M's advice](https://stackoverflow.com/questions/805625/pregreplace-help-in-php/805785#805785) and used a regex to capture every word and send it to a callback. Thanks Alan M for your advice. Here is my final code.
```
$plantDetails = end($this->_model->getPlantById($plantId));
$botany = new Botany_Model();
$this->_botanyWords = $botany->getArray();
foreach($plantDetails as $key=>$detail) {
$detail = preg_replace_callback('/\b[a-z]+\b/iU', array($this, '_processBotanyWords'), $detail);
$plantDetails[$key] = $detail;
}
```
And the \_processBotanyWords()...
```
private function _processBotanyWords($match) {
$botanyWords = $this->_botanyWords;
$word = $match[0];
if (array_key_exists($word, $botanyWords)) {
return '<a href="' . PATH_BASE . 'articles/botany-words/#botany-word-' . str_replace(' ', '-', strtolower($word)) . '" title="' . trim($botanyWords[$word]) . '">' . $word . '</a>';
} else {
return $word;
}
}
```
Hope this well help someone else some day! Thanks again for all your answers. | Asssuming this is related to the question you posted and deleted a little while ago (that was you, wasn't it?), it's your fundamental approach that's wrong. You said you were generating these HTML links yourself by replacing words from a list of keywords. The trouble is that keywords farther down the list sometimes appear in the generated title attributes and get replaced by mistake--and now you're trying to fix the mistakes.
The underlying problem is that you're replacing each keyword using a separate call to `preg_replace`, effectively processing the entire text over and over again. What you should do is process the text *once*, matching every single word and looking it up in your list of keywords; if it's on the list, replace it. I'm not set up to write/test PHP code, but you probably want to use `preg_replace_callback`:
```
$text = preg_replace_callback('/\b[A-Za-z]+\b/', "the_callback", $text);
```
"the\_callback" is the name of a function that looks up the word and, if it's in the list, generates the appropriate link; otherwise it returns the matched word. It may sound inefficient, processing every word like this, but in fact it's a great deal *more* efficient than your original approach. | This subject comes up pretty much every day here and basically the issue is this: you shouldn't be using regular expressions to parse or alter HTML (or XML). That's what HTML/XML parsers are for. The above problem is just one of the issues you'll face. You may get something that mostly works but there'll still be corner cases where it doesn't.
Just use an HTML parser. | preg_replace() help in PHP | [
"",
"php",
"regex",
""
] |
I am working on a Silverlight client and associated ASP.NET web services (not WCF), and I need to implement some features containing user preferences such as a "favourite items" system and whether they'd like word-wrapping or not. In order to make a pleasant (rather than infuriating) user experience, I want to persist these settings across sessions. A brief investigation suggests that there are two main possibilities.
1. Silverlight isolated storage
2. ASP.NET-accessible database
I realise that option 2 is probably the best option as it ensures that even if a user disables isolated storage for Silverlight, their preferences still persist, but I would like to avoid the burden of maintaining a database at this time, and I like the idea that the preferences are available for loading and editing even when server connectivity is unavailable. However, I am open to reasoned arguments why it might be preferrable to take this hit now rather than later.
What I am looking for is suggestions on the best way to implement settings persistence, in either scenario. For example, if isolated storage is used, should I use an XML format, or some other file layout for persisting the settings; if the database approach is used, do I have to design a settings table or is there a built-in mechanism in ASP.NET to support this, and how do I serve the preferences to the client?
So:
Which solution is the better solution for user preference persistence? How might settings be persisted in that solution, and how might the client access and update them?
### Prior Research
Note that I have conducted a little prior research on the matter and found the following links, which seem to advocate either solution depending on which article you read.
* <http://www.ddj.com/windows/208300036>
* <http://tinesware.blogspot.com/2008/12/persisting-user-settings-in-silverlight.html>
### Update
It turns out that Microsoft have provided settings persistence in isolated storage as a built-in part of Silverlight (I somehow missed it until after implementing an alternative). [My answer below](https://stackoverflow.com/questions/826613/persisting-user-preferences-in-silverlight/832332#832332) has more details on this.
I'm keeping the question open as even though Microsoft provides client-side settings persistence, it doesn't necessarily mean this is the best approach for persisting user preferences and I'd like to canvas more opinions and suggestions on this. | After investigating some more and implementing my own XML file-based settings persistence using [IsolatedStorage](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage(VS.95).aspx), I discovered the [IsolatedStorageSettings](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(VS.95).aspx) class and the [IsolatedStorageSettings.ApplicationSettings](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings.applicationsettings(VS.95).aspx) object that is a key/value collection specifically for storing user-specific, application settings.
It all seems obvious now. Of course, in the long term, a mechanism for backing up and restoring settings using a server database would be a good enhancement to this client-side settings persistence. | If it is an important feature for you that users have access to their preferences while offline, then it looks like isolated storage is the way to go for you. If it's more important that users be able to save preferences even if they have turned off isolated storage (is this really a problem? I'd be tempted to call YAGNI on this, but I'm not terribly experienced with the Silverlight platform...) then you need to host a database. If both are important, then you're probably looking at some kind of hybrid solution; using isolated storage if available, then falling back to a database.
In other words, I think the needs of your application are more important than some abstract best practice. | Persisting user preferences in Silverlight | [
"",
"c#",
"asp.net",
"persistence",
"silverlight-2.0",
"preferences",
""
] |
i have this code snippet
```
private List<string> FolderOne(string Folder)
{
string filena;
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName);
filena = file.FullName;
filena.Replace("*.mp3", "*.jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString()); //I receive a error "Parameter is not valid."
}
}
return str;
}
```
My purpose was to make read the picture box the file.fullname ".mp3" in the same folder but end with ".jpg",infact i have 2 file in a folder the first one is a song "firstsong.mp3" and the second one a picture "firstsong.jpg" the difference between them is the final extension so i try to make read to picturebox the same filename but with extension ".\*jpg" and i receive an error "Parameter is not valid." in the line code "pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString());".
How i can work out that?
Thanks for your attention
Nice Regards | Switch to:
```
filena = filena.Replace(".mp3", ".jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena);
}
```
The main problem is with `filena.Replace("*.mp3", "*.jpg");`
There are two issues in that line.
First, you're searching on "\*.mp3" instead of just ".mp3". The individual filenames do not have the \* character, and string.Replace doesn't use regular expressions, just string matching.
Second, strings in .NET are immutable. They cannot be changed once they're created. This means that you can't replace the value of a string in place - you always return a new string. So string.Replace(...) will return a new string. | There are some other issues with your code. First off, you are storing all the mp3 file names, but only displaying the last image loaded.
As far as replacing the extension, use `Path`'s method to do that:
```
string musicFile = "mysong.mp3";
string imageFile = Path.ChangeExtension(musicFile, "jpg");
``` | How replace 2 files? | [
"",
"c#",
".net",
"winforms",
""
] |
I want to be able to insert data from a table with an identity column into a temporary table in SQL Server 2005.
The TSQL looks something like:
```
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
...
END
```
The above code created #Tmp\_Table with an identity column, and the insert subsequently fails with an error "An explicit value for the identity column in table '#Tmp\_MyTable' can only be specified when a column list is used and IDENTITY\_INSERT is ON."
Is there a way in TSQL to drop the identity property of the column in the temporary table **without listing all the columns explicitly**? I specifically want to use "SELECT \*" so that the code will continue to work if new columns are added to MyTable.
I believe dropping and recreating the column will change its position, making it impossible to use SELECT \*.
**Update:**
I've tried using IDENTITY\_INSERT as suggested in one response. It's not working - see the repro below. What am I doing wrong?
```
-- Create test table
CREATE TABLE [dbo].[TestTable](
[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)
GO
-- Insert some data
INSERT INTO TestTable
(Name)
SELECT 'One'
UNION ALL
SELECT 'Two'
UNION ALL
SELECT 'Three'
GO
-- Create empty temp table
SELECT *
INTO #Tmp
FROM TestTable
WHERE 1=0
SET IDENTITY_INSERT #Tmp ON -- I also tried OFF / ON
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
SET IDENTITY_INSERT #Tmp OFF
GO
-- Drop test table
DROP TABLE [dbo].[TestTable]
GO
```
Note that the error message *"An explicit value for the identity column in table '#TmpMyTable' can only be specified **when a column list is used** and IDENTITY\_INSERT is ON."* - I specifically don't want to use a column list as explained above.
**Update 2**
Tried [the suggestion from Mike](https://stackoverflow.com/questions/713960/how-to-drop-identity-property-of-column-in-sql-server-2005/714247#714247) but this gave the same error:
```
-- Create empty temp table
SELECT *
INTO #Tmp
FROM (SELECT
m1.*
FROM TestTable m1
LEFT OUTER JOIN TestTable m2 ON m1.ID=m2.ID
WHERE 1=0
) dt
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
```
As for why I want to do this: MyTable is a staging table which can contain a large number of rows to be merged into another table. I want to process the rows from the staging table, insert/update my main table, and delete them from the staging table in a loop that processes N rows per transaction. I realize there are other ways to achieve this.
**Update 3**
I couldn't get [Mike's solution](https://stackoverflow.com/questions/713960/how-to-drop-identity-property-of-column-in-sql-server-2005/714247#714247) to work, however it suggested the following solution which does work: prefix with a non-identity column and drop the identity column:
```
SELECT CAST(1 AS NUMERIC(18,0)) AS ID2, *
INTO #Tmp
FROM TestTable
WHERE 1=0
ALTER TABLE #Tmp DROP COLUMN ID
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
```
Mike's suggestion to store only the keys in the temporary table is also a good one, though in this specific case there are reasons I prefer to have all columns in the temporary table. | IF you are just processing rows as you describe, wouldn't it be better to just select the top N primary key values into a temp table like:
```
CREATE TABLE #KeysToProcess
(
TempID int not null primary key identity(1,1)
,YourKey1 int not null
,YourKey2 int not null
)
INSERT INTO #KeysToProcess (YourKey1,YourKey2)
SELECT TOP n YourKey1,YourKey2 FROM MyTable
```
The keys should not change very often (I hope) but other columns can with no harm to doing it this way.
get the @@ROWCOUNT of the insert and you can do a easy loop on TempID where it will be from 1 to @@ROWCOUNT
and/or
just join #KeysToProcess to your MyKeys table and be on your way, with no need to duplicate all the data.
**This runs fine on my SQL Server 2005, where MyTable.MyKey is an identity column.**
```
-- Create empty temp table
SELECT *
INTO #TmpMikeMike
FROM (SELECT
m1.*
FROM MyTable m1
LEFT OUTER JOIN MyTable m2 ON m1.MyKey=m2.MyKey
WHERE 1=0
) dt
INSERT INTO #TmpMike
SELECT TOP 1 * FROM MyTable
SELECT * from #TmpMike
```
**EDIT**
THIS WORKS, with no errors...
```
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM (SELECT
m1.*
FROM MyTable m1
LEFT OUTER JOIN MyTable m2 ON m1.KeyValue=m2.KeyValue
WHERE 1=0
) dt
...
WHILE ...
BEGIN
...
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
...
END
```
**however, what is your real problem?** Why do you need to loop while inserting "\*" into this temp table? You may be able to shift strategy and come up with a much better algorithm overall. | You could try
```
SET IDENTITY_INSERT #Tmp_MyTable ON
-- ... do stuff
SET IDENTITY_INSERT #Tmp_MyTable OFF
```
This will allow you to select into `#Tmp_MyTable` even though it has an identity column.
But this **will not** work:
```
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
SET IDENTITY_INSERT #Tmp_MyTable ON
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
SET IDENTITY_INSERT #Tmp_MyTable OFF
...
END
```
(results in the error "An explicit value for the identity column in table '#Tmp' can only be specified when a column list is used and IDENTITY\_INSERT is ON.")
It seems there is no way without actually dropping the column - but that would change the order of columns as OP mentioned. Ugly hack: Create a new table based on #Tmp\_MyTable ...
I suggest you write a stored procedure that creates a temporary table based on a table name (`MyTable`) with the same columns (in order), but with the identity property missing.
You could use following code:
```
select t.name as tablename, typ.name as typename, c.*
from sys.columns c inner join
sys.tables t on c.object_id = t.[object_id] inner join
sys.types typ on c.system_type_id = typ.system_type_id
order by t.name, c.column_id
```
to get a glimpse on how reflection works in TSQL. I believe you will have to loop over the columns for the table in question and execute dynamic (hand-crafted, stored in strings and then evaluated) alter statements to the generated table.
Would you mind posting such a stored procedure for the rest of the world? This question seems to come up quite a lot in other forums as well... | How to drop IDENTITY property of column in SQL Server 2005 | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I inherited a project that needs to be mutithreaded. There is three major classes that get used in the worker threads.
BASE CLASS - has an class level SqlDataAdapter and DataTable.
INHERITED CLASS ONE - Uses the inherited SqlDataAdapter and DataTable.
INHERITED CLASS TWO - Uses the inherited SqlDataAdapter and DataTable.
Every thing seams to work, but I only have two users testing at the same time.
Is having the SqlDataAdapter and DataTable be class level variables a bad idea?
**Update**
Sorry it's a SqlDataAdapter not a SqlTableAdapter. The language is C#. The SqlDataAdapter and DataTable are from the System.Data.SqlClient namespace.
Here is some of the base class:
```
public abstract class BaseSync
{
#region Variables
internal SqlDataAdapter stageDataAdapter;
internal DataTable stageDataTable;
#endregion //Variables
}
```
**Part Two**
There is also a singleton utility class that all the derived classes use. I don't know if it will cause problems or not. It looks like this:
```
public class Utility
{
private static readonly Utility _utility= new Utility();
private Utility()
{ }
public static Utility GetUtility()
{
return _utility;
}
public int GetAutoNumber(string tablename, string fieldname, string siteId)
{
string _tablename = tablename;
string _fieldname = fieldname;
...
}
internal MissingInfo NormalizeRow(DataRow dataRow)
{
MissingInfo retVal = MissingInfo.None;
//Num
if (dataRow["Num"] == DBNull.Value)
{
retVal =MissingInfo.Num;
dataRow["Num"] = 1;
}
...
}
}
``` | This depends on the access level of the objects. As long as they are not Static (Shared in VB.NET). You should be fine having them in the object, as long as each thread, has its own instance of the object.
Where you come into interesting situations are with the static members that are shared across all instances.
So the long and short of it is that we would need to see the code. | Having variables modified by different threads without syncronization is always a *really bad idea*.
You don't mention if this is the case though. If you thread, you need to plan and check what you're doing. | Is it bad to use class variables in a multithreaded app? | [
"",
"c#",
"multithreading",
"variables",
""
] |
I am using [Kohana](http://kohanaphp.com/) but this question applies to Rails, CI, or any other MVC web development framework. Where is the best place to stick one's server side AJAX scripts?
I was *planning* on creating an Ajax\_Controller and using a method/action per individual script.
For example, a login form on the home page **`index.php/home`** would send an XMLHttpRequest to **`index.php/ajax/login`**, and the edit profile form **`index.php/profile/edit`** would send an XMLHttpRequest to **`index.php/ajax/editprofile`**. What's the best practice? | I don't use Kohana but what I do in my framework is that AJAX scripts are controllers. I try to treat them as standalone controllers but in the end they are just controllers. | I tend to put my ajax actions in the same controller as the non-ajax actions for any given model.
When I can, I try to use the same actions and only change the output type. Most tasks should have a non-ajax version anyway, so this tends to work quite well. Very handy for reducing logic duplication. | Kohana - where do you put AJAX scripts? | [
"",
"php",
"ajax",
"model-view-controller",
"design-patterns",
""
] |
This question is a matter of style, since you can always write a for loop or something similar; however, is there a less obtrusive STL or BOOST equivalent to writing:
```
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
```
?
Something like (imagined) this:
```
call_for_each(container.begin(), container.end(), &Type::func);
```
I think it would be 1) less typing, 2) easier to read, 3) less changes if you decided to change base type/container type.
EDIT:
Thanks for your help, now, what if I wanted to pass some arguments to the member function? | I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:
```
#include <iostream>
#include <functional>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
struct Foo {
Foo(int value) : value_(value) {
}
void func(int value) {
std::cout << "member = " << value_ << " argument = " << value << std::endl;
}
private:
int value_;
};
int main() {
std::vector<Foo> foo_vector;
for (int i = 0; i < 5; i++)
foo_vector.push_back(Foo(i));
std::for_each(foo_vector.begin(), foo_vector.end(),
boost::bind(&Foo::func, _1, 1));
}
``` | ```
#include <algorithm> // for_each
#include <functional> // bind
// ...
std::for_each(container.begin(), container.end(),
std::bind(&Type::func));
```
See [`std::for_each`](http://en.cppreference.com/w/cpp/algorithm/for_each) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind) documentation for details.
Missed your edit: Anyway here is another way of achieving what you want without using Boost, if ever need be:
```
std::for_each(foo_vector.begin(), foo_vector.end(),
std::bind(&Foo::func, std::placeholders::_1));
``` | Call member function on each element in a container | [
"",
"c++",
"stl",
"boost",
"coding-style",
""
] |
So, I have a situation where I need to pass in three values into a serial BlockingQueue queue:
```
(SelectableChannel, ComponentSocketBasis, Integer).
```
They don't actually need to be hash mapped at all, and to use a HashMap is ridiculous as there will always be only one key for each entry; it'd be fine if they were just in some sort of ordered set. For lack of a known alternative, however, I used a HashMap in my implementation and produced this obfuscated generics composition:
```
private LinkedBlockingQueue<HashMap<HashMap<SelectableChannel, ComponentSocketBasis>, Integer>> deferredPollQueue = new LinkedBlockingQueue<HashMap<HashMap<SelectableChannel, ComponentSocketBasis>, Integer>>();
```
This seems really ridiculous. I must be a terrible n00b. Surely there is a better way to do this that doesn't require me to decompose the key when retrieving the values or waste the (theoretical--in practice, Java's always bloated :) algorithmic complexity on a useless hash computation I don't need because I have a key space of 1 and don't even want to relationally map the three references, but merely to group them? With this implementation, I have to pull out the values thusly:
```
while(deferredPollQueue.size() > 0) {
System.out.println("*** Draining new socket channel from queue");
HashMap<HashMap<SelectableChannel, ComponentSocketBasis>, Integer> p = deferredPollQueue.take();
SelectableChannel chan = null;
ComponentSocketBasis sock = null;
int ops = 0;
HashMap<SelectableChannel, ComponentSocketBasis> q = p.keySet().iterator().next();
chan = q.keySet().iterator().next();
sock = q.get(chan);
ops = p.get(q).intValue();
SelectionKey k = chan.register(selector, ops);
if(!channelSupervisorMap.containsKey(k))
channelSupervisorMap.put(k, sock);
}
```
I am pretty sure every being capable of sentient reason here probably thinks this is a ridiculous way to do it, so the question is - what's the right way? :) I can't find evidence of a java.util.Pair or java.util.Triplet anywhere.
I suppose an Orthodox Way(TM) would be to do a custom class or interface just for the purpose of housing this triplet, but for such a small task in such a large system this seems preposterously verbose and unecessary--though, then again, that's Java itself.
By the same token, perhaps the values can be put onto an ArrayList or a Vector or derivative thereof, but in Java this does not yield a more terse way of addressing them than I'm getting out of this HashMap here, though it does solve the algorithmic complexity issue perhaps.
Back in Perl land, we'd just do this by using an array reference as a value inside an array:
```
push(@$big_queue_array, [$elem1, \%elem2, \@elem3]);
```
What's the best equivalent in Java? | Why not just create your own generic Pair or Triple classes? Pretty much every Java 5+ project ends up having them in their own util classes! | You say that a custom class to hold the triplet would be bloated and unnecessary, but this really is the way to do it, that's how object-oriented modelling works. A custom class is explicit and readable, and takes up no more runtime resources than a generic holder class would. | How to insert a "Pair" or n-size into a list collection instead of composing HashMaps? | [
"",
"java",
"collections",
"dictionary",
"dataset",
"queue",
""
] |
I need to replace
```
GET("any_name")
```
with
```
String str_any_name = getFunction("any_name");
```
The hard part is how to trim off the quote marks. Possible? Any ideas? | How about:
```
#define UNSAFE_GET(X) String str_##X = getFunction(#X);
```
Or, to safe guard against nested macro issues:
```
#define STRINGIFY2(x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define PASTE2(a, b) a##b
#define PASTE(a, b) PASTE2(a, b)
#define SAFE_GET(X) String PASTE(str_, X) = getFunction(STRINGIFY(X));
```
Usage:
```
SAFE_GET(foo)
```
And this is what is compiled:
```
String str_foo = getFunction("foo");
```
Key points:
* Use ## to combine macro parameters into a single token (token => variable name, etc)
* And # to stringify a macro parameter (very useful when doing "reflection" in C/C++)
* Use a prefix for your macros, since they are all in the same "namespace" and you don't want collisions with any other code. (I chose MLV based on your user name)
* The wrapper macros help if you nest macros, i.e. call MLV\_GET from another macro with other merged/stringized parameters (as per the comment below, thanks!). | In answer to your question, no, you can't "strip off" the quotes in C++. But as other answers demonstrate, you can "add them on." Since you will always be working with a string literal anyway (right?), you should be able to switch to the new method. | C++ Macros: manipulating a parameter (specific example) | [
"",
"c++",
"c",
"c-preprocessor",
""
] |
For some performance reasons, I am trying to find a way to select only sibling nodes of the selected node.
For example,
```
<div id="outer">
<div id="inner1"></div>
<div id="inner2"></div>
<div id="inner3"></div>
<div id="inner4"></div>
</div>
```
If I selected inner1 node, is there a way for me to access its siblings, `inner2-4` nodes? | Well... sure... just access the parent and then the children.
```
node.parentNode.childNodes[]
```
or... using jQuery:
```
$('#innerId').siblings()
```
**Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:**
```
function getChildren(n, skipMe){
var r = [];
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 && n != skipMe)
r.push( n );
return r;
};
function getSiblings(n) {
return getChildren(n.parentNode.firstChild, n);
}
``` | ```
var sibling = node.nextSibling;
```
This will return the sibling immediately after it, or null no more siblings are available. Likewise, you can use `previousSibling`.
**[Edit]** On second thought, this will not give the next `div` tag, but the whitespace after the node. Better seems to be
```
var sibling = node.nextElementSibling;
```
There also exists a `previousElementSibling`. | Is there a way to select sibling nodes? | [
"",
"javascript",
"html",
"dom",
"siblings",
""
] |
I'm using a System.Windows.Forms.DataGrid. It is populated with about 3000 rows and redraws very slowly. If I minimize and maximize my Form all the other controls just display but I end up watching the DataGrid redraw line by line. Everything in this DataGrid is readonly if that makes a difference.
**Update:**
I'm not really sure how to properly implement the CellValueNeeded() event for my project, or if it would help the performance of the DataGrid in my case.
I'm creating a User Control that contains a DataGridView (see the code bellow). When the SetProject() method is called my control is set to a specific instance of my Project class. Then the control uses a static method Informa.Data.GetProjectDataTable(Project proj) to extract a DataTable from the Project. The DataSource property of the DataGrid is then set to the returned DataTable.
This is the first time I've done anything with ADO or DataGrids, so bear with me. It looks like CellValueNeed() allows me to override how a DataGrid finds a value for one of it's cells, but in my case this a lot more complicated then the examples on MSDN. The actual source of my data is a tree structure of various Node objects, the root of which is the Project instance. Each Node can have a variable set of properties, which can also be expanded by the user at runtime. Then there is a bunch of other complexities with Nodes inheriting property values from their parent nodes, and totaling other properties from their child nodes.
Informa.Data.GetProjectDataTable() cuts through all this craziness and generates a single flat DataTable of all the properties of all the Nodes. At this point I don't care about being able to relate any change of this Table back to the original Tree structure, or updating specific parts of the table when the tree structure changes. All I want to do is display the data to the user in a DataGrid.
So do I implement CellValueNeeded() to read from the DataTable provided by the Project? I would think a DataGrid would already know how to efficiency use a DataTable as a DataSource?
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Informa;
namespace Informa
{
public partial class ProjectGridControl : UserControl
{
private Project proj;
public ProjectGridControl()
{
InitializeComponent();
}
public void SetProject(Project proj)
{
this.proj = proj;
UpdateGridControl();
}
public void UpdateGridControl()
{
if (this.proj == null)
{
this.dataGrid.DataSource = null;
}
else
{
//Extracts a DataTable from the project and sets it as the
//DataSource of the property grid
this.dataGrid.DataSource = Informa.Data.GetProjectDataTable(proj);
}
}
}
```
} | Once there was a little Wolf named MacroSoft, that spend some time with Vidia the Sheep. They made slowest Text and Grid rendering on the planet and pushed all the work onto the CPU in boom year of hardware advance; all while the Sheep made sure to slow it down even further.
If I'm right, you owe a letter to the lot :-)
You are running NVidia card and their crappy drivers or similar as well as seeing MSFT refusing to fix up GDI+ to hardware accelerate along with friendly vendors (even Mono will have it done before they decide to give you some energy saving and proper hardware reuse; you know decent engineering ).
Wrap your DataGridView into a new type (ie. inherit ) and set its DoubleBuffered property to true, change the designer code to use that new type.
Visible "Line by line" rendering is how bad this industry is 2009/2010 with supercomputers on the desktop and single DLL a big company is refusing to fix but will gladly charge for having it execute even slower on Mounta-Dismounta-Vista. Jokers.. | Do you have auto-sizing for columns turned on? I've had users experience massive slowdown in our app with as few as 10 rows because auto-sizing was enabled. Basically, one grid allowed a user to check/uncheck a box to add a row to another grid, and the second grid would experience an exponential slowdown with each added row.
After some profiling, I found it was taking ~12 seconds to add 5 rows to the second table. Finally tried turning off the auto-sizing of columns, and it's instantaneous now. | DataGrid slow to Redraw | [
"",
"c#",
"datagrid",
""
] |
I'm trying to debug something and I'm wondering if the following code could ever return true
```
public boolean impossible(byte[] myBytes) {
if (myBytes.length == 0)
return false;
String string = new String(myBytes, "UTF-8");
return string.length() == 0;
}
```
Is there some value I can pass in that will return true? I've fiddled with passing in just the first byte of a 2 byte sequence, but it still produces a single character string.
To clarify, this happened on a PowerPC chip on Java 1.4 code compiled through GCJ to a native binary executable. This basically means that most bets are off. I'm mostly wondering if Java's 'normal' behaviour, or Java's spec made any promises. | According to the javadoc for java.util.String, the behavior of new String(byte[], "UTF-8") is not specified when the bytearray contains invalid or unexpected data. If you want more predictability in your resultant string use <http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/CharsetDecoder.html>. | Possibly.
From the Java 5 API docs "The behavior of this constructor when the given bytes are not valid in the given charset is unspecified."
I guess that it depends on :
Which version of java you're using
Which vendor wrote your JVM (Sun, HP, IBM, the open source one, etc)
Once the docs say "unspecified" all bets are off
Edit: Beaten to it by [Trey](https://stackoverflow.com/users/50603/trey)
Take his advice about using a CharsetDecoder | Can a empty java string be created from non-empty UTF-8 byte array? | [
"",
"java",
"string",
"utf-8",
""
] |
I would like to use interfaces in c++ like in java or in c#. I decided to use purely abstract classes with multiple inheritance, but something is terribly wrong when I specialize the interface:
```
class Interface
{
public:
virtual int method() = 0;
};
// Default implementation.
class Base: virtual public Interface
{
public:
virtual int method() {return 27;}
};
// specialized interface
class Interface2: public Interface
{
public:
virtual int method() = 0;
// some other methods here
};
// concrete class - not specialised - OK
class Class: public virtual Interface, public virtual Base
{
};
// concrete class - specialised
class Class2: public Interface2, public Base
{
};
int main()
{
Class c;
Class2 c2;
return 0;
}
```
Warning 1 warning C4250: 'Class' : inherits 'Base::Base::method' via dominance 30
Error 2 error C2259: 'Class2' : cannot instantiate abstract class 42
What is the proper way to do this? | Heh heh, this problem tickles something buried deep in my head somewhere. I can't quite put my finger on it but I think it's to do with defining an interface heirarchy and then inheriting both an interface and an implementation. You then avoid having to implement all functions with by forwarding calls to a base class. I think.
I think this simple example shows the same thing, but is maybe a bit easier to understand because it uses things that can be easily visualized: (please forgive the struct laziness)
```
#include <iostream>
using namespace std;
struct Vehicle
{
virtual void Drive() = 0;
};
struct VehicleImp : virtual public Vehicle
{
virtual void Drive()
{
cout << "VehicleImp::Drive\n";
}
};
struct Tank : virtual public Vehicle
{
virtual void RotateTurret() = 0;
};
struct TankImp : public Tank, public VehicleImp
{
virtual void RotateTurret()
{
cout << "TankImp::RotateTurret\n";
}
// Could override Drive if we wanted
};
int _tmain(int argc, _TCHAR* argv[])
{
TankImp myTank;
myTank.Drive(); // VehicleImp::Drive
myTank.RotateTurret(); // TankImp::RotateTurret
return 0;
}
```
TankImp has essentially inherited the Tank interface and the Vehicle implementation.
Now, I'm pretty sure this is a well known and acceptable thing in OO circles (but I don't know if it has a fancy name), so the dreaded diamond thing is ok in this case, and you can safely suppress the dominance warning because it's what you want to happen in this case.
Hope that somehow helps point you in the right direction!
BTW, your code didn't compile because you hadn't implemented the pure virtual "method" in Class2.
**EDIT:**
Ok I think I understand your problem better now and I think the mistake is in Interface2. Try changing it to this:
```
// specialized interface
class Interface2: public virtual Interface // ADDED VIRTUAL
{
public:
//virtual int method() = 0; COMMENTED THIS OUT
// some other methods here
};
```
Interface2 should not have the pure virtual defintion of method, since that is already in Interface.
The inheritance of Interface needs to be virtual otherwise you will have an ambiguity with Base::method when you derive from Interface2 and Base in Class2.
Now you should find it will compile, possibly with dominance warnings, and when you call c2.method(), you get 27. | Class2 inherits from an abstract class (Interface2) but does not implement the pure virtual method, so it remains as an abstract class. | Interfaces in c++ | [
"",
"c++",
""
] |
I have the following algorithm implemented in Java which uses TCP/IP:
```
-Client request a file
-Server checks if the file exists
- if do: send contents of the file to the client
- if not: send "file not found" msg to the client
```
Now I`m having trouble implementing that using UDP Datapackets. Here is my code:
---
### CLIENT:
```
package br.com.redes.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import br.com.redes.configuration.CommonKeys;
public class TCPClient {
public static void exibirCabecalho(){
System.out.println("-------------------------");
System.out.println("TCP CLIENT");
System.out.println("-------------------------");
}
public static void main(String[] args) throws IOException {
TCPClient.exibirCabecalho();
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
if (args.length != 1){
System.out.println("O Programa deve ser chamado pelo nome + nome do servidor");
System.out.println("Ex: java TCPClient localhost");
System.exit(1);
}
System.out.println("Conectando ao servidor...");
try {
echoSocket = new Socket( args[0] , CommonKeys.PORTA_SERVIDOR);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket
.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Host não encontrado (" + args[0] + ")");
System.exit(1);
} catch (IOException e) {
System.err.println("Erro ao inicializar I/O para conexao");
System.exit(1);
}
System.out.println("Conectado, digite 'sair' sem as aspas para finalizar");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
String inputLine = in.readLine();
if (inputLine == null){
System.out.println("Servidor terminou a conexão.");
System.out.println("Saindo...");
break;
}
System.out.println("Servidor: " + inputLine.replace("\\n", "\n"));
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
```
---
### SERVER:
```
package br.com.redes.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import br.com.redes.configuration.CommonKeys;
public class TCPServer {
public static void exibirCabecalho(){
System.out.println("-------------------------");
System.out.println("TCP SERVER");
System.out.println("-------------------------");
}
public static void main(String[] args) throws IOException {
TCPServer.exibirCabecalho();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket( CommonKeys.PORTA_SERVIDOR );
} catch (IOException e) {
System.err.println("Erro ao iniciar servidor na porta: " + CommonKeys.PORTA_SERVIDOR );
System.exit(1);
}
System.out.println("Iniciando servidor na porta: " + CommonKeys.PORTA_SERVIDOR);
System.out.println("Aguardando cliente...");
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Erro ao receber conexoes.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
System.out.println("Cliente conectado, aguardando caminhos pra leitura...");
while ((inputLine = in.readLine()) != null) {
if (inputLine.equalsIgnoreCase("sair")) {
System.out.println("Sair detectado, fechando servidor...");
break;
}
outputLine = processar(inputLine);
out.println(outputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
private static String processar(String inputLine) {
final String ARQUIVO_NAO_ENCONTRADO = "arquivo não encontrado.";
final String ARQUIVO_IO = "erro ao ler arquivo.";
System.out.println("Procurando arquivo: " + inputLine);
File f = new File(inputLine);
try {
BufferedReader input = new BufferedReader(new FileReader(f));
String linha = null;
StringBuffer retorno = new StringBuffer();
retorno.append("\\n");
retorno.append("Arquivo encontrado, lendo conteudo: " + inputLine + "\\n");
while (( linha = input.readLine()) != null){
retorno.append(linha + "\\n");
}
retorno.append("fim da leitura do arquivo\\n");
return retorno.toString();
} catch (FileNotFoundException e) {
return ARQUIVO_NAO_ENCONTRADO;
} catch (IOException e) {
return ARQUIVO_IO;
}
}
}
``` | This certainly can be done using UDP datagrams. However, it is going to be a bit more difficult since UDP itself does not offer reliability or ordered packet delivery. Your application needs these features to deliver a file to the client. If you choose to use UDP, you will need to write extra code to accomplish this. Are you sure you really want to use UDP at all?
If you choose TCP much like your example above, you won't need to worry about bytes getting there and in the correct order.
I would begin by examining some examples at [Sun Datagram Tutorial](http://java.sun.com/docs/books/tutorial/networking/datagrams/index.html) | I recommend to review the UDP protocol ([RFC 768](http://www.faqs.org/rfcs/rfc768.html)) and then use some base example. There are lots of example with UDP and Java (e.g. [Java Tutorials -> Networking](http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html)) | Transfer a file through UDP in java | [
"",
"java",
"sockets",
"udp",
"tcp",
""
] |
I have a main page into which i load a user control with a grid and add/edit link buttons.
If I bind the grid by setting the datasource and calling the databind() method in the page load event then it sets properly. However, I want to keep the selected row between postbacks, so I wrap the bind code in "if (!Page.IsPostBack) {}" as usual. My problem is the page load always registers it as a postback and my code never runs.
I am using the 2.0 framework, and my grid is an 2008.1 Infragistics for the 2.0 framework.
I thinking this must be something simple.... or hoping anyway!
Thanks in advance | The two ways I found round this were:
1. to load the user controls when the page is first loaded and then hide them until user selected what they need to see.
2. to load a new page into an iframe on the main page allowing it to have its own page control meaning when its loaded in at first its not a postback.
Not the greatest, but gets by.
Thanks for the help. | If you place your control into an UpdatePanel, then you should check for **[Page.IsCallback](http://msdn.microsoft.com/en-us/library/system.web.ui.page.iscallback.aspx)** instead of **[Page.IsPostBack](http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx)**. | Using Page.IsPostback Within a User Control Wrapped in an Update Panel | [
"",
"c#",
"asp.net",
"ajax",
"asp.net-ajax",
"infragistics",
""
] |
I have made a tiny application that responds to changes to files in a folder. But when I edit the file in Visual Studio 2008, it never detects anything. If I edit the file in Notepad instead, everything works as expected.
Surely Visual Studio saves the file at some point, but the watcher does not even trigger when I close the studio. Do you have any idea what I'm missing here?
This sample code (C#) should illustrate the problem:
```
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\Test", "*.cs");
WaitForChangedResult changed = fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);
Console.Out.WriteLine(changed.Name);
```
I found a [blog post by Ayende](http://ayende.com/Blog/archive/2006/02/20/FileSystemWatcherVisualStudio2005.aspx) that describes the same problem, but unfortunately no solution. | This was really mind boggling... when you try my example program below and change the file in VS, you will notice two lines in your output window:
> Deleted
>
> Renamed
So Visual Studio does never *change* an existing file, it saves the constents to a new file with a temporary name, then deletes the original file and renames the new file to the old name.
Actually, this is a good practice, because if you do it the usual way (just writing the changed file, which would cause the `Changed` event to be fired), the event handler may be called before the writing process is complete. If the event handler processes the file contents, this may cause problems because it would process an incomplete file.
In other words: *It's not a bug, it's a feature* ;-)
```
static class Program
{
[STAThread]
static void Main()
{
FileSystemWatcher FSW = new FileSystemWatcher("c:\\", "*.cs");
FswHandler Handler = new FswHandler();
FSW.Changed += Handler.OnEvent;
FSW.Created += Handler.OnEvent;
FSW.Deleted += Handler.OnEvent;
FSW.Renamed += Handler.OnEvent;
FSW.EnableRaisingEvents = true;
System.Threading.Thread.Sleep(555000);
// change the file manually to see which events are fired
FSW.EnableRaisingEvents = false;
}
}
public class FswHandler
{
public void OnEvent(Object source, FileSystemEventArgs Args)
{
Console.Out.WriteLine(Args.ChangeType.ToString());
}
}
}
``` | Solved by specifying NotifyFilter property:
```
FileSystemWatcher w = new FileSystemWatcher();
w.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.CreationTime;
``` | Why doesn't FileSystemWatcher detect changes from Visual Studio? | [
"",
"c#",
"visual-studio-2008",
"filesystemwatcher",
""
] |
I have a simple Java POJO that I would copy properties to another instance of same POJO class.
I know I can do that with BeanUtils.copyProperties() but I would like to avoid use of a third-party library.
So, how to do that simply, the proper and safer way ?
By the way, I'm using Java 6. | I guess if you look at the source code of BeanUtils, it will show you how to do this without actually using BeanUtils.
If you simply want to create a copy of a POJO (not quite the same thing as copying the properties from one POJO to another), you could change the source bean to implement the clone() method and the Cloneable interface. | I had the same problem when developing an app for Google App Engine, where I couldn't use BeanUtils due to commons Logging restrictions. Anyway, I came up with this solution and worked just fine for me.
```
public static void copyProperties(Object fromObj, Object toObj) {
Class<? extends Object> fromClass = fromObj.getClass();
Class<? extends Object> toClass = toObj.getClass();
try {
BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
BeanInfo toBean = Introspector.getBeanInfo(toClass);
PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
List<PropertyDescriptor> fromPd = Arrays.asList(fromBean
.getPropertyDescriptors());
for (PropertyDescriptor propertyDescriptor : toPd) {
propertyDescriptor.getDisplayName();
PropertyDescriptor pd = fromPd.get(fromPd
.indexOf(propertyDescriptor));
if (pd.getDisplayName().equals(
propertyDescriptor.getDisplayName())
&& !pd.getDisplayName().equals("class")) {
if(propertyDescriptor.getWriteMethod() != null)
propertyDescriptor.getWriteMethod().invoke(toObj, pd.getReadMethod().invoke(fromObj, null));
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
```
Any enhancements or recomendations are really welcome. | How to copy properties from one Java bean to another? | [
"",
"java",
"javabeans",
""
] |
I realize this is probably caused by some \_dllexport() somewhere, not in my code but in some third-party piece. (Qt, Boost, OpenSG, ...)
Is there a simple linker option to disable this? I've searched but not found anywhere. | * To disable generation of `.lib` use `/NOIMPLIB` linker switch.
* To disable generation of `.exp` files use `/NOEXP` linker switch. | AFAIK, no, because the relevant #pragma's override the linker settings. | How do I disable exp/lib generation when building an exe? | [
"",
"c++",
"visual-studio",
"win32ole",
""
] |
i am using a BindingSource.Filter to list only certain elements of the datasource.
especially i use it like this a lot:
```
m_bindingSourceTAnimation.Filter = "Name LIKE '" + FilterText + "'";
```
now my question is, if it is somehow possible to use regular expressions with these filters.
i would especially need multiple wildcard (\*) characters like
```
*hello*world*
```
thanks! | You can query the DataTable with LINQ pretty easily and then you can use a actual Regex within the query to filter it anyway you like.
Something like this...
```
var source = myDataTable.AsEnumerable();
var results = from matchingItem in source
where Regex.IsMatch(matchingItem.Field<string>("Name"), "<put Regex here>")
select matchingItem;
//If you need them as a list when you are done (to bind to or something)
var list = results.ToList();
```
This will get you the rows that match based on an actual Regex, I don't know what you need to do with the information, but this would allow you to get the rows based on a Regex.
\*\*\*\*Update\*\* - Trying to clarify based on comment
I don't know what you are using this for so I don't have a great context, but from what I can guess you are using a DataTable to data bind to a Grid or something like that. If this is the case, I think that you should be able to assign "list" from the snippet I put in here as the DataSource (assuming you are using a BindingSource) and I think that it will work. I don't use DataTables, I usually stick to objects for working with my data so I am not exactly sure how it will handle the list of rows, but I would think that it would work (or be close enough that a little google searching would do it). | `BindingSource` relies on [`IBindingListView.Filter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglistview.filter.aspx) for this functionality. The behaviour depends *entirely* on the specific list implementation. Is this a `DataTable`/`DataView`? If so, this maps to [`DataView.RowFilter`](http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx), with syntax listed [here](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(vs.71).aspx).
The `DataView` implementation has no regex support, but supports `LIKE` via `*` - i.e. where `FilterText` is something like `"Foo*Bar*"`. At least, that is my understanding.
---
I'm still assuming that you are using `DataTable`/`DataView`... a pragmatic alternative might be to introduce an extra (bool) column for the purpose. Set/clear that marker as the predicate (using a regex or any other complicated logic), and just use the row-filter to say "where set". Not very clean, maybe, but a lot simpler than implementing a custom data-view / binding-source.
---
If you are using objects (rather than `DataTable`), then another option might be the [Dynamic LINQ Library](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx). I don't know the full range of what it supports, but it (`Where(string)`) certainly has some / much of the `RowFilter` capability. And since the code is available in the sample project, it is *possible* you could educate it to apply a regex? | .NET BindingSource.Filter with regular expressions | [
"",
"c#",
".net",
"regex",
"bindingsource",
""
] |
I've created a Windows service in C#, installed it on a server and it is running fine.
Now I want to install the same service again, but running from a different working directory, having a different config file etc. Thus, I would like to have *two* (or more) instances of the same service running simultaneously.
Initially, this isn't possible since the installer will complain that there's already a service with the given name installed.
I can overcome this by changing my code, setting the `ServiceBase.ServiceName` property to a new value, then recompiling and running InstallUtil.exe again. However, I would much prefer if I could set the service name at install-time, i.e. ideally I would do something like
> InstallUtil.exe /i
> /servicename="MyService Instance 2"
> MyService.exe
If this isn't achievable (I very much doubt it), I would like to be able to inject the service name when I build the service. I thought it might be possible to use some sort of build event, use a clever msbuild or nant trick or something along those lines, but I haven't got a clue.
Any suggestions would be greatly appreciated.
Thank you for your time. | I tried accessing a configuration using
```
ConfigurationManager.OpenExeConfiguration(string exePath)
```
in the installer, but couldn't get it to work.
Instead I decided to use `System.Environment.GetCommandLineArgs()` in the installer like this:
```
string[] commandlineArgs = Environment.GetCommandLineArgs();
string servicename;
string servicedisplayname;
ParseServiceNameSwitches(
commandlineArgs,
out servicename,
out servicedisplayname);
serviceInstaller.ServiceName = servicename;
serviceInstaller.DisplayName = servicedisplayname;
```
Now I can install my services using
> InstallUtil.exe /i
> InstallableService.dll
> /servicename="myserviceinstance\_2"
> /servicedisplayname="My Service
> Instance 2"
I wrote up a more elaborate explanation [here](http://www.runeibsen.dk/?p=153). | You can't pass this in as a command line arg, since InstallUtil doesn't provide the right hooks for that.
However, you can make your service installer read the ServiceName from a config file. If you [look at some code](http://www.codeproject.com/Articles/14353/Creating-a-Basic-Windows-Service-in-C) for a typical ServiceInstaller, you'll see it's just a matter of having the appropriate DisplayName and ServiceName properties setup at runtime. These could easily be read from a configuration file instead of being hard-coded. | How do I configure the name of a Windows service upon installation (or easily at compile time)? | [
"",
"c#",
".net",
"windows-services",
"windows-installer",
""
] |
I have the following problem. I have C code that acquires a PNG image as basically raw data and keeps it in memory. I would like this raw data to be translated to a BufferedImage in Java, through the use of JNI. Does anyone know any way of doing this or has done this before? | I'll assume you know the basics of how to call functions with JNI. It's not that complicated, although it can be a pain in the ass.
If you want to get it done quickly, just write the PNG to a temp file, pass the file name up through JNI and load it using ImageIO.
If you want to get more sophisticated, and avoid needing a file path, you can use [ImageIO.read(InputStream)](https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#read(javax.imageio.stream.ImageInputStream)) on a [ByteArrayInputStream](https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html) that wraps a byte array you pass in through JNI. You can call [NewByteArray()](http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/functions.html#wp17318) from C and then use [SetByteArrayRegion](http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/functions.html#wp22933) to set the data.
Finally, you might consider using HTTP to transfer the data, Apache [has a set of components you can use](http://hc.apache.org/) that include a little web server, you can POST from your C code to Java. | if you've never used JNI before, I'd recommend you to take a look at the [JNI Programmer's Guide and Specification](http://java.sun.com/docs/books/jni/html/titlepage.html).
in summary, what you have to do is:
1. create a Java method with the `native` keyword, with no implementation.
2. use the command `javah` on the class with the native method to generate a header file (.h). `javah` comes with a JDK installation.
3. implement your native Java function in C/C++.
1. search the class java.awt.image.BufferedImage.
2. search the constructor you want to use.
3. create a BufferedImage object with the specified constructor.
4. search the setPixel method.
5. run that method to set each pixel value in your image. you'll need to run it *height* x *width* times.
6. return the object.
4. compile your native file into a shared library.
5. load your shared library inside your Java class.
6. run your Java class indicating, linking your shared library.
there are other ways of copying the raw data of your image, but this way I explained should be enough. | Load a PNG image into Java as BufferedImage through JNI C code | [
"",
"java",
"java-native-interface",
"bufferedimage",
""
] |
I'm trying to subclass `str`, but having some difficulties due to its immutability.
```
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
derived = DerivedClass('a')
print derived.upper() #'A123'
print type(derived.upper()) #<class '__main__.DerivedClass'>
print derived.lower() #'a'
print type(derived.lower()) #<type 'str'>
```
For inherited methods that don't require any new functionality, such as `derived.lower()`, is there a simple, pythonic way to return an object of type `DerivedClass` (instead of `str`)? Or am I stuck manually overriding each str.method(), as I did with `derived.upper()`?
Edit:
```
#Any massive flaws in the following?
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
att = super(DerivedClass, self).__getattribute__(name)
if not callable(att):
return att
def call_me_later(*args, **kwargs):
result = att(*args, **kwargs)
if isinstance(result, basestring):
return DerivedClass(result)
return result
return call_me_later
``` | You can do this by overriding `__getattribute__` as Zr40 suggests, but you will need to have getattribute return a callable function. The sample below should give you what you want; it uses the `functools.partial` wrapper to make life easier, though you could implement it without partial if you like:
```
from functools import partial
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')
def __getattribute__(self, name):
func = str.__getattribute__(self, name)
if name == 'upper':
return func
if not callable(func):
return func
def call_me_later(*args, **kwargs):
result = func(*args, **kwargs)
# Some str functions return lists, ints, etc
if isinstance(result, basestring:
return DerivedClass(result)
return result
return partial(call_me_later)
``` | Good use for a class decorator -- roughly (untested code):
```
@do_overrides
class Myst(str):
def upper(self):
...&c...
```
and
```
def do_overrides(cls):
done = set(dir(cls))
base = cls.__bases__[0]
def wrap(f):
def wrapper(*a, **k):
r = f(*a, **k)
if isinstance(r, base):
r = cls(r)
return r
for m in dir(base):
if m in done or not callable(m):
continue
setattr(cls, m, wrap(getattr(base, m)))
``` | Extending Python's builtin Str | [
"",
"python",
"oop",
"inheritance",
"overriding",
"immutability",
""
] |
I have a singly linked list and I need to sort it in constant space due to memory limitations (in other words, no extra space should be used that is proportional to the number of items in the list).
The structure of the linked list is:
* `head.item` = the payload you want to sort on; and
* `head.next` = the next item.
The requirement for constant space discounts solutions where I build another list, I need to do it in-place.
How can I do that? | Sorting a linked list in constant space is easy, you just have to adjust the pointers. The easiest way to do this is to use a sort algorithm that only swaps adjacent elements. I'm going to provide a bubble-sort, just because you've made no requirement for efficiency:
```
# Enter loop only if there are elements in list.
swapped = (head <> null)
while swapped:
# Only continue loop if a swap is made.
swapped = false
# Maintain pointers.
curr = head
next = curr.next
prev = null
# Cannot swap last element with its next.
while next <> null:
# Swap if items in wrong order.
if curr.item > next.item:
# Notify loop to do one more pass.
swapped = true
# Swap elements (swapping head is special case).
if curr == head:
head = next
temp = next.next
next.next = curr
curr.next = temp
curr = head
else:
prev.next = curr.next
curr.next = next.next
next.next = curr
curr = next
endif
endif
# Move to next element.
prev = curr
curr = curr.next
next = curr.next
endwhile
endwhile
``` | For in-place sorting of a linked list, I would suggest merge sort. It's stable, and runs in NlgN time. | How can I sort a singly linked list in constant space? | [
"",
"c++",
"sorting",
"linked-list",
""
] |
I'm sure it's something really stupid, but I just don't see it..
`pData.LocationHours` is of type `BaseLocationHoursDataSet.LocationHoursDataTable`. Yet when I hover the cursor over `l`, all I see is "`(range variable) TSource l`" - why is that?? Why doesn't linq know what it's dealing with? I try the same thing with a different DataTable and everything works fine.... not this guy. What could be the problem?
```
protected ListItem[] GetHoursTypesListItems(BaseLocationHoursDataSet pData)
{
return (
from l in pData.LocationHours // putting cursor over the l here shows: (range variable) TSource l
select new ListItem
{
Value = l, //ignore the fact that I didn't specify a property - that's the problem, that none of the properties of the object show up.
Text = l
}
).ToArray<ListItem>();
}
```
.
**UPDATE:**
The problem is that it doesn't know what l is. Instead of showing me the correct type (I expect to see LocationHoursRow), I see "TSource l".. What is that? Why doesn't it knwo what l is in the "`from l in pData.LocationHours`" line? | I think maybe you would need l.Field:
```
select new ListItem
{
Value = l.Field,
Text = l.Field2
}
```
Okay how about something like this:
Since you are using a data set your query may need to be similar to the following:
```
var query = pData.Tables["Name"].AsEnumerable()
```
then do your LINQ off of the query object
Also, found this code snippet that might help. It is using generic dataset for reference.
```
DataSet ds = new DataSet();
FillOrders(ds);
DataTable orders = ds.Tables["SalesOrderHeader"];
var ordersQuery = orders.ToQueryable();
var query = from o in ordersQuery
where o.Field<bool>("OnlineOrderFlag") == true
select new { SalesOrderID = o.Field<int>("SalesOrderID"),
OrderDate = o.Field<DateTime>("OrderDate") };
``` | > I see "TSource l".. What is that?
First, the compiler translates the query from query form into method call form. This query becomes
```
pData.LocationHours.Select(l=>new ... )
```
Second, the compiler attempts to determine what "pData.LocationHours.Select" means. If the type of pData.LocationHours does not have a Select method then the compiler starts looking for extension methods. Presumably it finds the extension method
```
IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source, Func<TSource, TResult> projection)
```
Or perhaps it finds the IQueryable version of the same.
Now the compiler says "but what are the type parameters TSource and TResult?"
I do not know what your problem is, but it is highly likely that the problem is occurring at this phase. The type inference engine is unable to determine what TSource is, for some reason.
Now you hover over "l". What happens? The intellisense engine asks the semantic analyzer what the type of "l" is. The semantic analyzer reports that "l" is known to be a parameter in a function that takes a TSource and returns a TResult, but that the method type inferrer was unable to determine what actual type TSource corresponds to.
So the intellisense engine does the best it can with what its got and tells you that l is of type TSource. The intellisense engine also notes that "l" is the range variable of a query, and tells you that fact as well.
> Why
> doesn't it know what l is in the "from
> l in pData.LocationHours" line?
I don't know but clearly *something* is broken in your code. Without knowing the types of all of the expressions and exactly what extension methods are available, it is hard for me to say what exactly has gone horribly wrong.
When the code is broken and cannot compile, intellisense still does the best it can. I agree that in this case the result is a bit confusing, but at least you know that its getting as far as type inference before something goes wrong. | What's wrong with this linq query? | [
"",
"c#",
".net",
"asp.net",
"linq",
""
] |
Is it possible to access the Windows 7 Sensor and Location platform from Silverlight? In particular I would like to know about the location data (GPS) and the ambient light sensor.
Edit: I would assume that the way to do this would be with C# in the code behind file. | With the new features in Silverlight 4, specifically out of browser and com-inter-op this is definitely possible.
I still don't know about Silverlight 3. | No. Silverlight is supposed to be cross-platform and the Sensor and Location stuff in Win7 is not available anywhere other than Win7. You could try some complicated mix of Silverlight + .NET, but then it would be silly to use Silverlight when the whole .NET/WPF platform is available. | Can one access the Windows 7 Sensor and Location platform from Silverlight? | [
"",
"c#",
"windows",
"silverlight",
"sensors",
""
] |
I'd like to change the value of the `onclick` attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the `onclick` attribute in HTML.) Here are a few things I tried:
* Using jQuery `attr("onclick", js)` doesn't work with both Firefox and IE6/7.
* Using `setAttribute("onclick", js)` works with Firefox and IE8, but not IE6/7.
* Using `onclick = function() { return eval(js); }` doesn't work because you are not allowed to use `return` is code passed to `eval()`.
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
```
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
<a href="http://www.google.com/" id="anchor" onclick="alert('A'); return false;">Click</a>
</body>
</html>
``` | You shouldn't be using `onClick` any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See [`.click()`](http://api.jquery.com/click)
```
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
```
That should cancel the `onClick` function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the `onclick=""` from the `<a>` element in the HTML code and switch to using the [**Unobtrusive**](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) method of binding an event to click.
You also said:
> Using `onclick = function() { return eval(js); }` doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but `onclick = eval("(function(){"+js+"})");` will wrap the 'js' variable in a function enclosure. `onclick = new Function(js);` works as well and is a little cleaner to read. (note the capital F) -- see [documentation on `Function()` constructors](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function) | BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
```
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
```
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance. | JavaScript: changing the value of onclick with or without jQuery | [
"",
"javascript",
"jquery",
"onclick",
"attributes",
""
] |
Is there a way to read ahead one line to test if the next line contains specific tag data?
I'm dealing with a format that has a start tag but no end tag.
I would like to read a line add it to a structure then test the line below to make sure it not a new "node" and if it isn't keep adding if it is close off that struct and make a new one
the only solution i can think of is to have two stream readers going at the same time kinda suffling there way along lock step but that seems wastefull (if it will even work)
i need something like peek but peekline | The problem is the underlying stream may not even be seekable. If you take a look at the stream reader implementation it uses a buffer so it can implement TextReader.Peek() even if the stream is not seekable.
You could write a simple adapter that reads the next line and buffers it internally, something like this:
```
public class PeekableStreamReaderAdapter
{
private StreamReader Underlying;
private Queue<string> BufferedLines;
public PeekableStreamReaderAdapter(StreamReader underlying)
{
Underlying = underlying;
BufferedLines = new Queue<string>();
}
public string PeekLine()
{
string line = Underlying.ReadLine();
if (line == null)
return null;
BufferedLines.Enqueue(line);
return line;
}
public string ReadLine()
{
if (BufferedLines.Count > 0)
return BufferedLines.Dequeue();
return Underlying.ReadLine();
}
}
``` | You could store the position accessing StreamReader.BaseStream.Position, then read the line next line, do your test, then seek to the position before you read the line:
```
// Peek at the next line
long peekPos = reader.BaseStream.Position;
string line = reader.ReadLine();
if (line.StartsWith("<tag start>"))
{
// This is a new tag, so we reset the position
reader.BaseStream.Seek(pos);
}
else
{
// This is part of the same node.
}
```
This is a lot of seeking and re-reading the same lines. Using some logic, you may be able to avoid this altogether - for instance, when you see a new tag start, close out the existing structure and start a new one - here's a basic algorithm:
```
SomeStructure myStructure = null;
while (!reader.EndOfStream)
{
string currentLine = reader.ReadLine();
if (currentLine.StartsWith("<tag start>"))
{
// Close out existing structure.
if (myStructure != null)
{
// Close out the existing structure.
}
// Create a new structure and add this line.
myStructure = new Structure();
// Append to myStructure.
}
else
{
// Add to the existing structure.
if (myStructure != null)
{
// Append to existing myStructure
}
else
{
// This means the first line was not part of a structure.
// Either handle this case, or throw an exception.
}
}
}
``` | Reading a line from a streamreader without consuming? | [
"",
"c#",
"readline",
"streamreader",
"gedcom",
""
] |
I'm using WAMP on windows, which installs PHP, Apache and MySQL.
I'm now working on something new that requires PostgreSQL. The current install won't do it for me, as I keep getting these errors:
> Call to undefined function pg\_query()
Always
> undefined function
I've installed PostgreSQL 8.3.7-1 for windows, added `php_pgsql.dll`,`php_pdo_pgsql.dll` and even `libpq.dll`, which a note on the PHP page for postgreSQL says Windows users need starting from PHP 5.2.6
Still, I keep getting these errors...
Can someone advise the best course of action? Or should I just uninstall apache and everything else, and do a fresh install of each component seperatly? | xampp doesn't "tell" apache/php which php.ini to use. Therefore php uses its default lookup strategy to find the .ini file. If you haven't changed anything this will be the one in the directory where the apache binary is located, xampp/apache/bin/php.ini. Did you edit this file and removed the semicolon before extension=php\_pgsql.dll ?
When in doubt ask
```
echo 'php.ini: ', get_cfg_var('cfg_file_path');
```
which file you have to edit.
xampp installs php as a module by default and you have to restart the apache in order to get php to read the php.ini again.
After that
```
echo extension_loaded('pgsql') ? 'yes':'no';
```
should print *yes*. If it doesn't stop the apache service, open a command shell, go to your xampp directory and enter
```
apache_start.bat
```
This will start the apache as a console application and you can see startup errors in this console (instead of windows' event manager). If a dll is missing you will get a message box. | Did you enable it in the php ini file?
What does a call to phpinfo() say is installed for extensions? | PostgreSQL trouble on windows PHP | [
"",
"php",
"postgresql",
"wamp",
""
] |
I pass a variable to domain.com/index.php?user=username
In my page (index.php) contains others pages like about.php, profile.php, contact.php etc..
My question is, is it possible that i pass variable to index.php, then about.php, profile.php can also retrieve the variable using $\_GET['user']; method??(actually i tried, its failed, give me "undefined index:..."
If this method failed, is there any other way?
EDIT:
yeah, i can use SESSION. How about I want to display others profile? means other username? | You can save the variable in a session.
In your index.php file.
```
session_start();
$_SESSION["user"] = $_GET["user"];
```
And then in your following files you can start the session and call `$_SESSION["user"]`
EDIT:
If you need to display different content that can take the same arguments, then you need to have those arguments in that url.
EDIT 2:
BTW this is sort of guessing since I don't know your code or skill level.
Lets assume you have this index.php page. Which you access by index.php?user=john
And in this page you list friends of john. And you can access their profile also by doing index.php?user=alex and index.php?user=tim
Then you can reference the url of their friends with. (assuming you have arrays of friends in a standard mysql\_fetch\_\* way)
```
<?php
echo "<a href='index.php?user=".$friend["name"]."'>".$friend["name"]."</a>
?>
```
And fetch your link by using the $\_GET variable
```
<?php
echo "<a href='index.php?user=".$_GET["user"]."'>".$_GET["user"]."</a>
?>
``` | i am assuming that you want to pass "username" as different user identities on your website so that users may be able to view their profile, like:
profile.php?user=peter
profile.php?user=olafur
is this correct?
one way is sessions, but if you like, you can also just pass them as GET vars to all links inside the pages.
eg. if the user started with index.php?user=peter
you just save this as $this\_user = $\_GET["user"];
and inside index.php, when you render the links you just assign the $this\_user variable, something like:
< a href="profile.php?user=< ?=$this\_user? >" >Profile< /a >
i hope this helps. | Can i get this variable value in this case? (php) | [
"",
"php",
"variables",
""
] |
I have a form in my project that is showing up as a class in Solution Explorer. This is causing a problem since I can't get to the designer. Any ideas on how to fix this? | Try seeing if there are any hidden files by using the the 'Show All Files' button. Sounds like your project file might not have all of the files added to it. | You can fix the problem manually by editing your csproj file.
Open it in notepad and search for the filename of the class. You should see something like this...
```
<Compile Include="frmTest.cs" />
```
Add a subtype called 'Form' like this...
```
<Compile Include="frmTest.cs">
<SubType>Form</SubType>
</Compile>
```
Reload the project. Visual Studio should now identify the file correctly. | Form showing as a class in Solution Explorer | [
"",
"c#",
".net",
"winforms",
""
] |
I stumbled across this code.
```
std::ostringstream str;
/// (some usage)
assert( ! str );
```
What does **`ostringstream`** signify when used in a **`bool`** context?
Is this possibly an incorrect usage that happens to compile and run? | It tells you if the stream is currently valid. This is something that all streams can do. A file stream, for example, can be invalid if the file was not opened properly.
As a side note, this functionality (testing a stream as a bool) is achieved by overloading `explicit operator bool` *in C++11 and later* and by overloading the `void*` cast operator in versions *before C++11*.
Here is a link containing [some examples of why a stream might fail](http://www.cppreference.com/wiki/io/fail "Stream failure at cppreference.com"). This isn't specific to string streams, but it does apply to them.
**Edit:** changed `bool` to `void*` after Martin York pointed out my mistake. | For reference: [ostringstream::operator void\*()](http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/) and [ostringstream::operator!()](http://www.cplusplus.com/reference/iostream/ios/operatornot/). | How would std::ostringstream convert to bool? | [
"",
"c++",
"casting",
"stream",
"boolean",
"ostringstream",
""
] |
You know how django passwords are stored like this:
```
sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
```
and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely? | As always, use the source:
```
# root/django/trunk/django/contrib/auth/models.py
# snip
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return md5_constructor(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return sha_constructor(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
```
As we can see, the password digests are made by concatenating the salt with the password using the selected hashing algorithm. then the algorithm name, the original salt, and password hash are concatenated, separated by "$"s to form the digest.
```
# Also from root/django/trunk/django/contrib/auth/models.py
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return hsh == get_hexdigest(algo, salt, raw_password)
```
To validate passwords django just verifies that the same salt and same password result in the same digest. | [According to the docs](http://docs.djangoproject.com/en/dev/topics/auth/#passwords):
> Hashtype is either sha1 (default), md5 or crypt -- the algorithm used to perform a one-way hash of the password. Salt is a random string used to salt the raw password to create the hash.
According to the code of [`set_password`](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.set_password):
```
def set_password(self, raw_password):
import random
algo = 'sha1'
salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
hsh = get_hexdigest(algo, salt, raw_password)
self.password = '%s$%s$%s' % (algo, salt, hsh)
```
As the documentation describes, the hash is the salt, algorithm, and password, hashed. | What is the format in which Django passwords are stored in the database? | [
"",
"python",
"django",
""
] |
> **Possible Duplicate:**
> [Is Java “pass-by-reference”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference)
I found an unusual Java method today:
```
private void addShortenedName(ArrayList<String> voiceSetList, String vsName)
{
if (null == vsName)
vsName = "";
else
vsName = vsName.trim();
String shortenedVoiceSetName = vsName.substring(0, Math.min(8, vsName.length()));
//SCR10638 - Prevent export of empty rows.
if (shortenedVoiceSetName.length() > 0)
{
if (!voiceSetList.contains("#" + shortenedVoiceSetName))
voiceSetList.add("#" + shortenedVoiceSetName);
}
}
```
According to everything I've read about Java's behavior for passing variables, complex objects or not, this code should do exactly nothing. So um...am I missing something here? Is there some subtlety that was lost on me, or does this code belong on thedailywtf? | As Rytmis said, Java passes references by value. What this means is that you can legitimately call mutating methods on the parameters of a method, but you cannot reassign them and expect the value to propagate.
Example:
```
private void goodChangeDog(Dog dog) {
dog.setColor(Color.BLACK); // works as expected!
}
private void badChangeDog(Dog dog) {
dog = new StBernard(); // compiles, but has no effect outside the method
}
```
**Edit:** What this means in this case is that although `voiceSetList` *might* change as a result of this method (it could have a new element added to it), the changes to `vsName` will not be visible outside of the method. To prevent confusion, I often mark my method parameters `final`, which keeps them from being reassigned (accidentally or not) inside the method. This would keep the second example from compiling at all. | Java passes *references by value*, so you get a copy of the reference, but the referenced object is the same. Hence this method does modify the input list. | Java is NEVER pass-by-reference, right?...right? | [
"",
"java",
"pass-by-reference",
"pass-by-value",
""
] |
My app reads an (html) file from my website, and I would like to track accesses to that file using Google Analytics. As the GA Javascript does not get executed when reading the file, it is not tracked. Is there a way to trigger GA directly from code or alternatively, to execute the Javascript from a .NET app without adding a bunch of dependencies? | Google Analytics works by making a webrequest through javascript back to Google's server. If you want to do this programmatically, you just have to make this web request yourself. I would use Fiddler or FireBug to capture what the request looks like when you load the page in your browser. Then you can use that same URL in your .Net app. | I have recently released a .net library that allows you to natively log a page view with Google Analytics through code. It is released as open source under GNU so all that is required is proper attribution.
You can get the library here: <http://www.diaryofaninja.com/projects/details/ga-dot-net>
example usage of the API:
```
GooglePageView pageView = new GooglePageView("My page title",
"www.mydomain.com",
"/my-page-url.html");
TrackingRequest request = new RequestFactory().BuildRequest(pageView);
GoogleTracking.FireTrackingEvent(request);
```
There is also a built in HTTP Handler that allows you to fire tracking events by simply including a tracking pixel on the page:
```
<img src="/tracker.asmx?domain=mydomain.com&pagetitle=My%20Page%20Title&url=/my-page.aspx" />
```
Alternatively you can use jquery to track links within a page using Google Analytics (zip, jpg, etc) - blogged about it a while ago here:
<http://www.diaryofaninja.com/blog/2009/09/17/random-file-zip-and-pdf-tracking-using-jquery-amp-google-analytics> | How to trigger Google Analytics from code? | [
"",
".net",
"javascript",
"google-analytics",
""
] |
I need to store in a constant class 4 letter of a code. I can do:
```
static final String CODE_LETTERS = "TRWAG";
```
or
```
static final char[] CODE_LETTERS = {'T', 'R', 'W', 'A', 'G'};
```
After, I can obtain one of that characters in two ways:
```
final char codeLetter = CODE_LETTERS.charAt(index);
```
or
```
final char codeLetter = CODE_LETTERS[index];
```
what is the best way?. Please take in mind correction, performance, etc. | Performance is irrelevant in this case. If it's really supposed to be constant, you can't use the `char[]` approach. Consider:
```
public class Test
{
static final char[] CODE_LETTERS = {'T', 'R', 'W', 'A', 'G'};
public static void main(String[] args) throws Exception
{
System.out.println(CODE_LETTERS[0]); // T
CODE_LETTERS[0] = 'x';
System.out.println(CODE_LETTERS[0]); // x
}
}
``` | Neither is incorrect, but since you're going to be dealing with the `char`s individually I'd personally use the `char []`. That said, the impact this will have on performance is going to be negligible if even measurable. | Char Array vs String: which is better for storing a set of letters | [
"",
"java",
"performance",
"coding-style",
"constants",
""
] |
I have a problem with an rss feed.
When i do `<title>This is a title </title>`
The title appears nicely in the feed
But when i ddo
$title = "this is a tilte";
```
<title><![CDATA['$title']]></title>
```
The title doesn't appear at all.
---
It still doesn't work. I generate my rss feed dynamicly and it looks like this:
```
$item_template="
<item>
<title>[[title]]</title>
<link>[[link]]</link>
<description><![CDATA[[[description]]]]></description>
<pubDate>[[date]]</pubDate>
</item>
";
```
and in a loop:
```
$s.=str_replace(
array("[[title]]","[[link]]","[[description]]","[[date]]"),
array(htmlentities($row["title"]),$url,$description,$date),
$item_template);
```
The problem is specifically when the title has a euro sign. Then it shows up in my rss validator like:
```
Â\x80
```
---
**More detailed information:**
Ok I have been struggeling with this for the last few days and I can't find a solution. So I will start a bounty. Here is more information:
* The information that goes in the feed is stored in a latin 1 database (which i administer)
* The problem appears when there is a euro sign in the database. No matter wether its like € or `€`
* The euro sign sometimes appears like weird charachters or like Â\x80
* I try to solve the problem on the feed side not on the reader side.
* The complete code can be found over here: [codedump](http://codedump.mastercode.nl/622/)
* Next: sometimes when the euro sign cannot be parsed the item (either the title or description) is shown empty. So if you look in the source when showing the feed in an browser you'll find `<title></title>`
If there is more information needed please ask. | The problem is your outputting code; change
```
echo '<title><![CDATA[$title]]></title>';
```
to
```
echo '<title><![CDATA[' . $title . ']]></title>';
```
As a side note, please mind the following: Do not answer your own question with a follow-up, but edit the original one. Do not use regexps for no good reason. Do not guess.
Instead, do what you should have done all along: Wrap the title in [`htmlentitites`](http://php.net/htmlentities) and be done, as in:
```
echo '<title>' . htmlentities($title, ENT_NOQUOTES, [encoding]) . '</title>';
```
**Replace `[encoding]` with the character encoding you are using.** Most likely, this is 'UTF-8'. This is necessary because php(<6) uses ISO-8859-1 by default and there is no way to express e.g. the Euro sign in that encoding. For further information, please refer to this [well-written introduction](http://www.joelonsoftware.com/articles/Unicode.html).
I also suggest you [read about XML](http://www.w3.org/TR/2006/REC-xml11-20060816/). Start with the second chapter. | Use `htmlspecialchars()` instead of `htmlentities()`.
RSS/ATOM feeds **are not** HTML, so you cant use HTML entities in them. [XML has only five entities defined by default](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML), so you can’t use `€`. Since you’re using UTF — use literal euro sign, without conversion (no `htmlentities`), but with escaping other sensitive characters (`htmlspecialchars`).
And this would be completely valid RSS/XML. If this doesn’t solve the problem it means, that it lies somewhere else (please provide me with generated raw-source of the RSS for more help). | problem with rss feed and cdata | [
"",
"php",
"rss",
""
] |
I'd like to set a property in my pom to a classpath containing all the project's dependencies. The ant plugin does something like this, so I know it's definitely possible.
I basically want to use ${maven.compile.classpath} wherever I like in my pom and have it 'just work'. I don't mind using plugins or anything else to achieve this.
Many thanks,
Nick | I don't think that there's a way of doing this without writing your own maven plugin. That said, you can get at the classpath using [dependency:build-classpath](http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html). Is that of use? | Since version 2.7 the maven-dependency-plugin can now [set a property to the classpath](https://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html#outputProperty). Here's an example:
```
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputProperty>maven.compile.classpath</outputProperty>
<pathSeparator>;</pathSeparator>
</configuration>
</execution>
</executions>
</plugin>
```
If you want Eclipse support here's my update site:
<http://terraframe.github.io/m2e-maven-dependency-plugin/snapshots/> | Setting the a Property to what maven.compile.classpath Contains WITHOUT Ant | [
"",
"java",
"maven-2",
"properties",
"classpath",
""
] |
When showing my main window, I make a list of objects from linq-to-sql:
```
using (var context = new Data.TVShowDataContext())
{
Shows = new ObservableCollection<Data.Show>(context.Shows);
listShows.ItemsSource = Shows;
}
```
Now, when I doubleclick an item in my list, I want to use the selected object in a new usercontrol:
```
ShowEpList epList = new ShowEpList();
epList.DataContext = (Data.Show)listShows.SelectedItem;
```
Now, this results in an exception:
> System.ObjectDisposedException was unhandled
> Message="Cannot access a disposed object.\r\nObject name: 'DataContext accessed after Dispose.'."
> Source="System.Data.Linq"
> ObjectName="DataContext accessed after Dispose."
I guess this comes as a result of binding a list to the shows season-list, and the season-list needs to be populated or something:
```
<ListBox Name="listSeasons" ItemsSource="{Binding Seasons}"/>
```
Now, what I would like to know, is how this is supposed be done?
Would I need to make a new DataContext-object and retrieve the selected show again, or is it possible to re-conntect my show with a new datacontext to populate the seasons-list?
I guess I'm a little lost.... | Do not use a "using" statement with your datacontext.
Please refer to this post: [Disposing DataContext](https://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context/389853) | When you use a `using()` block, it calls `Dispose()` on whatever you've put into its initializer (in this case, your context). When a LINQ to SQL context is disposed, the entities created with it are as well. I would suggest creating an instance variable on your `Form` for the context, and insert code into your `For`m's `Dispose(bool)` function (it's in the `Designer.cs` file) to dispose of the context. | c#: How to pass linq-objects around | [
"",
"c#",
"wpf",
"linq-to-sql",
"datacontext",
""
] |
What are the options for something that will let users make text bold/italic/underline/etc as they are writing in a textarea and work in all browsers? | Give a look to [FKCEditor](http://www.fckeditor.net/), I always recommend it... | I always liked TinyMCE
<http://tinymce.moxiecode.com/> | javascript WYSIWYG HTML editors? | [
"",
"javascript",
"html",
"cross-browser",
"dhtml",
""
] |
Is it possible to change the default collation based on a column? i want to make 1 column case sensitive but all the others not | `ALTER TABLE ALTER COLUMN` allows to change collation for a single column:
```
alter table Foo alter column Bar ntext collate Latin1_General_CS_AS
```
(collation might be incorrect) | I don't specifically know SQL Server, but the generally accepted DBMS practice (for compatibility) would be to either:
* put insert and update triggers on the table so that they're stored in the case you want.
* use generated columns to store another copy of the column in the case you want.
There may be a faster way to do it in SQL Server but you should be careful of solutions that push workload into the SELECT statements - they never scale well. It's almost always better doing this as part of inserts and updates since that's the only time data changes - doing it that way minimizes the extra workload. | How to make a column case sensitive in sql 2005 or 2008 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-server-2008",
""
] |
when trying to log-in at this [site](http://www.ucuzhizmet.com/) (user:polopolo,pass:samara) the result is a blank page. I know that the problem is with the sending of headers and the *ouput\_buffering* in the php.ini file. I had the same problem on another host but the problem was fixed when I changed *output\_buffering= On*. It doesn't work on the current host and I wonder why? Any suggestions?
-the [phpinfo](http://www.ucuzhizmet.com/phpinfo.php) of the current site.
---
Edit:
Problem solved. I reverse-engineered the code and found some additional spaces after the php closing tag, before the sending of the headers. The code wasn't written by me and I instinctively ignored this option as the whole system worked already on another server. But my colleague did some changes I was unaware of...The lesson learned: teamwork is important and don't let anybody do the thinking for you. Still it is a mystery to me how come after trying everything to display errors and especially the "Cannot modify headers" they didn't display properly. I did everything you advised me to do- display errors, log them and so on...anyway thanks. | Presumably, the page you hit immediately after logging in does a redirect.
Doing a redirect requires outputting an HTTP header with the response. The problem is, if PHP has already begun outputting the *body* of the document, it cannot then output a header because they headers ended when the body started.
Output buffering prevents PHP from outputting any part of the *body* of the document until the output buffer is flushed (or PHP exits). This allows you to output headers at any time.
Now, if turning output buffering on fixed the problem on own site/server, but not on another, that's a clear indication that it isn't actually the same problem - you are encountering a different problem.
You should be logging PHP errors, so check your PHP error log. If (and only if) you are viewing this on a restricted developers-only site (which you aren't), you may turn on display\_errors in your PHP configuration, which will display errors on the page as it is rendered. This is generally considered an unsafe setting on publicly accessible servers, because of the potential for attackers to try and cause an error for which the error message reveals some private information. | I'm no expert and I can't understand what output buffering as to do with anything, maybe there are some errors in the code?
Could you create an .htaccess file with the following content:
```
php_flag display_errors on
php_value error_reporting 30719
```
Place it in the root folder of that site and then try to log in again to see if there are any output errors? | Problem with output_buffering and php.ini | [
"",
"php",
"output-buffering",
""
] |
I am trying to use the Scanner class to read a line using the next(Pattern pattern) method to capture the text before the colon and then after the colon so that s1 = textbeforecolon and s2 = textaftercolon.
The line looks like this:
something:somethingelse | There are two ways of doing this, depending on specifically what you want.
If you want to split the entire input by colons, then you can use the `useDelimiter()` method, like others have pointed out:
```
// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");
// Examines each token one at a time
while (scanner.hasNext())
{
String token = scanner.next();
// Do something with token here...
}
```
If you want to split each line by a colon, then it would be much easier to use `String`'s `split()` method:
```
while (scanner.hasNextLine())
{
String[] parts = scanner.nextLine().split(":");
// The parts array now contains ["something", "somethingelse"]
}
``` | I've never used Pattern with scanner.
I've always just changed the delimeter with a string.
<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)> | Reading text with Java Scanner next(Pattern pattern) | [
"",
"java",
"java.util.scanner",
""
] |
I am doing my assignment in Network architecture 1, where I have to implement a distance vector routing at each node.
At each node, I have a thread which listens for incoming `DatagramPacket`s containing routing information from neighboring nodes only on a specific port. When a datagram arrives, the thread processes that datagram, and if there are updates in its internal routing tables, then it sends its routing information to all of its neighbors.
I am trying to do it in Java.
The problem I am facing is that when a datagram arrives, I need to process it. If during that time any other datagram arrives, it is dropped, as the thread is currently processing information. That means I have a loss of information.
Can any one help me with this?
I am using the usual way of reading from a socket in java.
```
DatagramSocket socket = new DatagramSocket(4445, InetAddress.getByName("127.0.0.1"));
while (true) {
try {
byte[] buf = new byte[2000];
// receive request
DatagramPacket recvRequest = new DatagramPacket(buf, buf.length);
socket.receive(recvRequest);
//Some process of data in datagram
} catch (IOException e) {
e.printStackTrace();
}
}
``` | DatagramSocket socket = new DatagramSocket(4445, InetAddress.getByName("127.0.0.1"));
while (true) {
try {
// note final ..
final byte[] buf = new byte[2000];
```
// receive request
DatagramPacket recvRequest = new DatagramPacket(buf, buf.length);
socket.receive(recvRequest);
//Some process of data in datagram
(new Thread(new Runnable() {
public void run () {
// do stuff with data in buf
...
}
})).start();
} catch (IOException e) {
e.printStackTrace();
}
```
} | You can process the received datagram in a thread, so your thread with the socket listener can continue to receive new datagrams. | Threading for distance vector which does not drop packets | [
"",
"java",
"algorithm",
"multithreading",
"vector",
"distance",
""
] |
So we all know that all classes implicitly extend Object. How about interfaces? Is there an implicit super-interface? I say there is. The following code compiles:
```
java.io.Serializable s1 = null;
java.io.Serializable s2 = null;
s1.equals(s2);
```
The `equals` method is not declared in Serializable, but in Object. Since interfaces can only extend other interfaces, and Object is a class, not an interface, there must be some implicit interface that is being extended. And the `Object` class must then implicitly implement this implicit interface (wow, that was weird to write).
So, the question is, how correct is this? | > Since interfaces can only extend other
> interfaces, and Object is a class, not
> an interface, there must be some
> implicit interface that is being
> extended.
No. Citing the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4.4):
> If an interface has no direct
> superinterfaces, then **the interface
> implicitly declares a public abstract
> member method** m with signature s,
> return type r, and throws clause t
> **corresponding to each public instance
> method** m with signature s, return type
> r, and throws clause t **declared in
> Object**, unless a method with the same
> signature, same return type, and a
> compatible throws clause is explicitly
> declared by the interface. It is a compile-time error if the interface explicitly
> declares such a method m in the case
> where m is declared to be final in
> Object.
The difference between this and your "implicit super interface" is that `Object` has a number of final and protected methods, and you couldn't have those modifiers in an interface. | s1 and s2 here are object references, referring to instances of objects that implement Serializable. There is no such thing as an interface reference in Java.
So Java knows that whatever these objects are, they descend from java.lang.Object. Hence the above code is valid. | implicit super-interface in Java? | [
"",
"java",
"interface",
""
] |
Please let me know what steps I need to follow when my application crashes and closes showing the dialog containing "Don't send" and "Send error report" buttons.
What can I possibly do other than looking at the event viewer to solve this?
Thanks | 1. You could add a `try/catch/finally` construct around your `Main()` entry method's body.
2. For WinForms, you can add a `ThreadException` handler, just before Application.Run(), to catch exceptions thrown in WinForms UI event handlers:
```
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
```
3. All other unhandled exceptions can be caught using:
```
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
```
But it's worth mentioning that this only allows you to log/report the exception - you cannot prevent the application from closing once you exit this final handler.
4. Visual Studio can also be configured to [break on first chance exceptions](https://stackoverflow.com/q/8218249/69809), and external debuggers (like WinDbg with managed SoS extensions) can catch first-chance exceptions too (<http://www.codeproject.com/KB/debug/windbg_part1.aspx>).
Also, use a logging framework like log4net to add useful logging to your app and dump exception information before the application closes. | Ask your users if they can reproduce the error and how. If you can reproduce the error, run in debug in Visual Studio and follow the steps to cause the crash. Visual studio will enter debug mode where it catches the error. Form there you will be able to follow the stack trace and see what code is causing the error. Visual studio makes debugging pretty easy most of the time. | How to identify problem when program crashes without showing error? | [
"",
"c#",
"debugging",
"crash-dumps",
""
] |
I'm trying to implement a mailing list system for my application. I'm currently using `Zend_Mail_Transport_Smtp('localhost')` as my transport, looping through my list of subscribers, and sending a new `Zend_Mail` to each one. However, I am noticing that the length of time that it takes for the script to complete increases as the number of subscribers increase.
I'm sure there must be a more professional approach to doing this, involving the queuing of emails. I suppose the ideal approach would be for the user to fill out the form, click send, and immediately get a response saying that the emails are being sent, rather than waiting for the hundreds of emails to finish sending.
I understand that `Zend_Mail` does not do any sort mail queuing. Could anyone who has experience with this, give me an overview of how this can be done? I don't know anything about cron/crontab/cronjobs, so if it involves that, please explain the process. | In order to reliably send a large number of emails using PHP you have to use a queueing mechanism. As suggested by others, the process of using a queue looks something like this:
* Loop over your set of users, creating an email for each one and possibly customizing the content
* Pass each mail object to the queue which will delay the sending of the email until later
* In some sort of cron script, send out the contents of the queue a few hundred at a time. *Note: you'll want to tweak the number of emails you are sending by watching the logs for errors coming back from the actual sending process. If you try to send too many, I've noticed it reaches a point where the mail transport will no longer accept connections (I'm using qmail)*
There are a few libraries out there you can use to do this, [PEAR Mail Queue](http://pear.php.net/package/Mail_Queue/) (with Mail\_Mime) and SwiftMailer both allow you to create and queue emails. So far, Zend Mail only provides for creation of emails, not queueing (more on that later).
I have experience primarily with [PEAR Mail Queue](http://pear.php.net/package/Mail_Queue/) and there are a few gotchas. If you are trying to queue up a large number of emails (for instance, looping over 20,000 users and trying to get them into the queue in a reasonable time), using Mail Mime's quoted-printable encoding implementation is very slow. You can speed this up by switching to base64 encoding.
As for Zend Mail, you can write a Zend Mail Transport object that puts your Zend Mail objects into the PEAR Mail Queue. I have done this with some success, but it takes a bit of playing to get it right. To do this, extend Zend Mail Transport Abstract, implement the \_sendMail method (which is where you will drop your Zend Mail object into the Mail Queue) and pass the instance of your transport object to the send() method of your Zend Mail object or by Zend Mail::setDefaultTransport().
Bottom line is that there are many ways you can do this, but it will take some research and learning on your behalf. It is a very solvable problem, however. | *NOTE: when I first read your question, I thought it said hundreds of thousand emails at once. When I double checked, I noticed it actually said hundreds to thousands. I'm too lazy to change my post now, so here are some caveats: From my experience, you can probably run fine without a commercial tool to about 40K. At about 10K you'll want to be following the 'minimum' list to prevent major pain when you start reaching larger list sizes. I do recommend implementing it all right away though.*
I've said this before, there are two sides to sending email:
1. The technical side -- basically all
of the RFC's around the smtp
protocol, email formats, DNS
records, etc. This is mildly
complicated but solvable.
2. The magical side -- email delivery
management is voodoo. You will get
frustrated, things will break for no
apparent reason and you will
consider leaving for another job
that doesn't involve email.
I recommend not writing your own bulk sender. I'm sure PHP can do a fine job, but you should probably spend your time elsewhere. The two products I've used in the past and recommend are Strongmail and PowerMTA. Be warned -- they have a high price tag, but I can almost guarantee that you'll spend more building your own solution in the long run.
One area that you'll get nailed with writing your own in PHP is throttling/tar pitting. Mail servers will start adding in sleep(30)'s after you've sent a few messages to slow you down and stop you from spamming.
Typically, these commercial bulk senders run the SMTP protocol for queueing. You would continue to use Zend\_Mail, but hard code it to connect to your server. It'll queue the mail just about as fast as you can send it, then use it's own engine to send the mail to their destinations.
At a 100K list, you will have to employ email best practices. At a minimum, you'll need:
* SPF Records, possibly DKIM as well
* Multiple IPs to segment traffic over -- have 3 IP's, one for quality address you trust, one for medium risk IP addresses and one for high risk IP addresses. This design helps minimize the risk to getting mail to your best customers.
* Proper reverse DNS for sending IP addresses
* Use the feedback loops from AOL, hotmail, yahoo and others for processing spam complaints
* Unsubscribe and bounce management -- make sure you're pruning these addresses
* Having open/click tracking is also important -- if you're customers on the A list aren't opening your emails, you need to degrade them to the B list and so forth. This is important because ISP's will turn inactive accounts into a honeypot. Hotmail is famous for this.
Finally, if you're really serious about sending email, you'll want some other tools like Return Path. | What's the best approach to sending email to hundreds of recipients from a Zend Framework application? | [
"",
"php",
"email",
"zend-framework",
"smtp",
"mailing-list",
""
] |
I am using Intel TBB C++ for multithreading an application on visual studio 2008. When I run the executable I get a dialog saying "MSVCP80D.dll" was not found. There is so much on the net about this that it confuses me.
Please help.
EDIT: Based on answers, finally I was able to fix the "dll missing" problem. I had given a path to TBB lib of vc8 leading to dependency on vc8 dlls, which are used with visual studio 2005, not with 2008. (Using depends (<http://www.dependencywalker.com/> ) it is easy to determine the run-time dependencies of an executable.) I changed by project to depend on vc9 dlls, not vc8 and then it worked fine.
Another thing to note is use of manifest files on windows. Manifest files describe dependencies. The manifest files must be generated while writing an application as it is necessary. | You can find them online at various places. Just scan it for a virus and put it in your program's path and everything should work fine. You may need more than one of the debug dlls, you can use depends32.exe to see what you are missing. | MSVC80D is VS 2005. As part of VS2008 you would have MSVC90D instead. | msvcp80d.dll not found while using TBB | [
"",
"c++",
"visual-studio",
""
] |
I need to write setup scripts for MySQL (usually run using 'source [file]' from mysql console) that depend partly on existing data, and there are differences in environments, meaning that sometimes script does fail. A common case is that a 'SET' statement with a select (to locate an id) fails to find anything; console sets value to NULL. In this case I would like the script to fail; I have heard this would be done by raising an error (with other DBs). However it appears like MySQL didn't have a way to do this.
Are there good ways to force failure under such conditions? As things are now updates will fail when insert tries to use null, but even that does not terminate script itself. Ideally it would just fail and terminate as soon as a problem is encountered. | I think what you're encountering is a limitation of the MySQL console. Given a list of statements, the MySQL console executes each one regardless of any errors generated. Even if you implemented some of the error-raising suggestions that previous comments have mentioned, the MySQL console won't stop executing when such an error is encountered.
I'll assume that you don't have the resources to apply a scripting language to the problem that could execute your SQL for you and handle the errors. I think in this case, you just need a more robust tool than the MySQL console.
[MySQL Administrator](http://dev.mysql.com/downloads/gui-tools/5.0.html) does what you need, if I understand your problem correctly. If you set up your MySQL connection and connect to the database, you have two tools available from the Tools menu. The normal MySQL console is there, but you also have the MySQL Query Browser.
If you open the Query Browser, you get a decent GUI view of your MySQL databases. File -> Open Script to open your SQL script, then use the Execute button.
You get a nice progress bar, and more importantly from the sounds of it, if a query fails, the script execution halts and highlights the failed query. You can choose to skip it and keep going, or even manually modify your data and start up from someplace else farther down the script.
I abandoned the MySQL console almost immediately once I found out about and tried Administrator. | I had the same problem and the GUI isn't an option for me. Here's how I solved it:
```
DELIMITER $$
DROP FUNCTION IF EXISTS sfKillConnection $$
CREATE FUNCTION sfKillConnection() RETURNS INT
BEGIN
SELECT connection_id() into @connectionId;
KILL @connectionId;
RETURN @connectionId;
END $$
DELIMITER ;
```
It's a function instead of a procedure so it can be called in a script like this:
```
select if(@error, sfKillConnection(), 0);
```
You'll probably need to start the mysql client with the `--disable-reconnect` option. | Way to abort execution of MySQL scripts (raising error perhaps)? | [
"",
"sql",
"mysql",
"exception",
"fast-fail",
""
] |
I wrote a small coordinate class to handle both int and float coordinates.
```
template <class T>
class vector2
{
public:
vector2() { memset(this, 0, sizeof(this)); }
T x;
T y;
};
```
Then in main() I do:
```
vector2<int> v;
```
But according to my MSVC debugger, only the x value is set to 0, the y value is untouched. Ive never used sizeof() in a template class before, could that be whats causing the trouble? | No don't use `memset` -- it zeroes out the size of a pointer (4 bytes on my x86 Intel machine) bytes starting at the location pointed by `this`. This is a bad habit: you will also zero out virtual pointers and pointers to virtual bases when using `memset` with a complex class. Instead do:
```
template <class T>
class vector2
{
public:
// use initializer lists
vector2() : x(0), y(0) {}
T x;
T y;
};
``` | As others are saying, `memset()` is not the right way to do this.
There are some subtleties, however, about why not.
First, your attempt to use `memset()` is only clearing `sizeof(void *)` bytes. For your sample case, that apparently is coincidentally the bytes occupied by the `x` member.
The simple fix would be to write `memset(this, 0, sizeof(*this))`, which in this case would set both `x` and `y`.
However, if your `vector2` class has any virtual methods and the usual mechanism is used to represent them by your compiler, then that `memset` will destroy the `vtable` and break the instance by setting the `vtable` pointer to NULL. Which is bad.
Another problem is that if the type `T` requires some constructor action more complex than just settings its bits to 0, then the constructors for the members are not called, but their effect is ruined by overwriting the content of the members with `memset()`.
The only correct action is to write your default constructor as
```
vector2(): x(0), y(0), {}
```
and to just forget about trying to use `memset()` for this at all.
**Edit:** D.Shawley pointed out in a comment that the default constructors for `x` and `y` were actually called before the `memset()` in the original code as presented. While technically true, calling `memset()` overwrites the members, which is at best really, really bad form, and at worst invokes the demons of Undefined Behavior.
As written, the `vector2` class is POD, as long as the type `T` is also plain old data as would be the case if `T` were `int` or `float`.
However, all it would take is for `T` to be some sort of `bignum` value class to cause problems that could be really hard to diagnose. If you were lucky, they would manifest early through access violations from dereferencing the NULL pointers created by `memset()`. But Lady Luck is a fickle mistress, and the more likely outcome is that some memory is leaked, and the application gets "shaky". Or more likely, "shakier".
The OP asked in a comment on another answer "...Isn't there a way to make memset work?"
The answer there is simply, "No."
Having chosen the C++ language, and chosen to take full advantage of templates, you have to pay for those advantages by using the language correctly. It simply isn't correct to bypass the constructor (in the general case). While there are circumstances under which it is legal, safe, and sensible to call `memset()` in a C++ program, this just isn't one of them. | C memset seems to not write to every member | [
"",
"c++",
"templates",
"sizeof",
"memset",
""
] |
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.
I get from the user a URL in UTF-8. So if they've typed in `http://➡.ws/♥` I get `'http://\xe2\x9e\xa1.ws/\xe2\x99\xa5'` in Python. And what I want out is the ASCII version: `'http://xn--hgi.ws/%E2%99%A5'`.
What I do at the moment is split the URL up into parts via a regex, and then manually IDNA-encode the domain, and separately encode the path and query string with different `urllib.quote()` calls.
```
# url is UTF-8 here, eg: url = u'http://➡.ws/㉌'.encode('utf-8')
match = re.match(r'([a-z]{3,5})://(.+\.[a-z0-9]{1,6})'
r'(:\d{1,5})?(/.*?)(\?.*)?$', url, flags=re.I)
if not match:
raise BadURLException(url)
protocol, domain, port, path, query = match.groups()
try:
domain = unicode(domain, 'utf-8')
except UnicodeDecodeError:
return '' # bad UTF-8 chars in domain
domain = domain.encode('idna')
if port is None:
port = ''
path = urllib.quote(path)
if query is None:
query = ''
else:
query = urllib.quote(query, safe='=&?/')
url = protocol + '://' + domain + port + path + query
# url is ASCII here, eg: url = 'http://xn--hgi.ws/%E3%89%8C'
```
Is this correct? Any better suggestions? Is there a simple standard-library function to do this? | ## Code:
```
import urlparse, urllib
def fixurl(url):
# turn string into unicode
if not isinstance(url,unicode):
url = url.decode('utf8')
# parse it
parsed = urlparse.urlsplit(url)
# divide the netloc further
userpass,at,hostport = parsed.netloc.rpartition('@')
user,colon1,pass_ = userpass.partition(':')
host,colon2,port = hostport.partition(':')
# encode each component
scheme = parsed.scheme.encode('utf8')
user = urllib.quote(user.encode('utf8'))
colon1 = colon1.encode('utf8')
pass_ = urllib.quote(pass_.encode('utf8'))
at = at.encode('utf8')
host = host.encode('idna')
colon2 = colon2.encode('utf8')
port = port.encode('utf8')
path = '/'.join( # could be encoded slashes!
urllib.quote(urllib.unquote(pce).encode('utf8'),'')
for pce in parsed.path.split('/')
)
query = urllib.quote(urllib.unquote(parsed.query).encode('utf8'),'=&?/')
fragment = urllib.quote(urllib.unquote(parsed.fragment).encode('utf8'))
# put it back together
netloc = ''.join((user,colon1,pass_,at,host,colon2,port))
return urlparse.urlunsplit((scheme,netloc,path,query,fragment))
print fixurl('http://\xe2\x9e\xa1.ws/\xe2\x99\xa5')
print fixurl('http://\xe2\x9e\xa1.ws/\xe2\x99\xa5/%2F')
print fixurl(u'http://Åsa:abc123@➡.ws:81/admin')
print fixurl(u'http://➡.ws/admin')
```
## Output:
> `http://xn--hgi.ws/%E2%99%A5`
> `http://xn--hgi.ws/%E2%99%A5/%2F`
> `http://%C3%85sa:abc123@xn--hgi.ws:81/admin`
> `http://xn--hgi.ws/admin`
## Read more:
* [urllib.quote()](http://docs.python.org/library/urllib.html#urllib.quote)
* [urlparse.urlparse()](https://docs.python.org/2/library/urlparse.html#urlparse.urlparse)
* [urlparse.urlunparse()](https://docs.python.org/2/library/urlparse.html#urlparse.urlunparse)
* [urlparse.urlsplit()](https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit)
* [urlparse.urlunsplit()](https://docs.python.org/2/library/urlparse.html#urlparse.urlunsplit)
## Edits:
* Fixed the case of already quoted characters in the string.
* Changed `urlparse`/`urlunparse` to `urlsplit`/`urlunsplit`.
* Don't encode user and port information with the hostname. (Thanks Jehiah)
* When "@" is missing, don't treat the host/port as user/pass! (Thanks hupf) | the code given by MizardX isnt 100% correct. This example wont work:
example.com/folder/?page=2
check out django.utils.encoding.iri\_to\_uri() to convert unicode URL to ASCII urls.
<http://docs.djangoproject.com/en/dev/ref/unicode/> | Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python? | [
"",
"python",
"url",
"unicode",
"utf-8",
""
] |
I would like to find a Java library that will allow me to search for colours within an image with a tolerance. Preferably quickly. I know how I would do it if I had to write it myself, and it's not super difficult, but I'm hoping to find a library with features other than that principle one. I'd like to be able to also:
* Find another image within an image, with a tolerance, and figure out how closely matched the image is to whatever the function finds
* Specify the manner in which to search for colors or images in an image (such as a outward spiraling manner or whatever)
* Find and return a string containing what it thinks is the text at a particular location in an image
* (trivial) Find colors and images on the display as opposed to an image (I know I could just make an image out of the display, but this would help)
What I really want is SCAR Divi, the program best known for cheating at Runescape, but in Java form so I can use it with my project and I don't feel dirty. | [ImageMagick](http://www.imagemagick.org/) is a powerful image processing library which has bindings for many languages. [JMagick](http://sourceforge.net/projects/jmagick/) is the Java flavor. | The first part of your question is not very easy clear. At any pixel of an image you have a single color, which you can get with [BufferedImage.getRGB(x,y)](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html#getRGB(int,%20int)). The resulting int contains the RGB values (you need a bit of work to unpack them). You get three 8-bit values in the end: a simplistic (but working) way to compare colors with a tolerance is just to look for the euclidean distance between the two color in the 3D r,g,b space, i.e.
`d = ((r1-r2)^2+(g1-g2)^2(b1-b2)^2)^0.5`; you will consider "similar" two colors whose d is less than a given threshold.
> Find another image within an image,
> with a tolerance, and figure out how
> closely matched the image is to
> whatever the function finds
It's quite difficult to do this efficiently: do you want to tolerate distorsions?
> Specify the manner in which to search
> for colors or images in an image (such
> as a outward spiraling manner or
> whatever)
What do you mean? This is very unclear.
> Find and return a string containing
> what it thinks is the text at a
> particular location in an image
You may look for Java OCR libraries for this functionality, but expect good results only on very clean text. | What Java Library can I use to search for colours, with a tolerance, in an image? | [
"",
"java",
"image-processing",
""
] |
I'm using jQuery 1.3.2.
I'm having trouble getting a correct "height" in Internet Explorer 6. Height values are correct in all other browsers.
I am also using [wresize jQuery plugin](http://noteslog.com/post/how-to-fix-the-resize-event-in-ie/).
Each time the browser loads, I fire a method that resizes divs, iframes based upon browser dimensions. (There's a good reason for this.)
The returned value of $('body').height(), in IE 6, seems to add 10 pixels after each resize of the browser.
Anyone else come across something like this?
```
var iframeH = 0, h = 0, groupH = 0, adjust = 0;
var tableH = $("#" + gridId + "_DXHeaderTable").parent().height();
var pagerH = $(".dxgvPagerBottomPanel").height();
var groupHeight = $(".dxgvGroupPanel").height();
if (pagerH == null)
pagerH = 0;
if (groupHeight != null)
groupH = groupHeight + pagerH;
iframeH = $('body').height();
h = (iframeH - (tableH + pagerH + groupH));
$('#' + gridId + "Panel").css("height", (h + "px"));
$("#" + gridId + "_DXMainTable").parent().css("height", (h + "px"));
```
This code is for setting the height of a DevExpress grid in it's parent container. Ignore the fact that the code could be better. :)
Is there something other than "body" that I could use to get me a correct size? I've tried the window object ($(window).height()), but that doesn't seem to help much.
Any thoughts are appreciated! | The problem you're facing is more likely to be a css rendering difference. Because of floating problems, padding, and margin rendering differences between browsers.
try to get **$("body").innerHeight()** and **$("body").outerHeight()** and compare them in different browsers, you'll get some common results. In worst case you might need run some `if` cases | Sure, here's a couple of ideas:
With IE, and esp. older IE, I like to add a 1-10ms setTimeout statement around my height rendering functions -- it gives the dom and IE a chance to "relax"
Also, make sure you're stuff is visible on page -- for this, you may need to throw things off the screen temporarily using absolute position, and then reveal them onscreen again.
Another thing is that height() is sometimes wonky. Try .css('height') to retrieve heights [it's also faster] and remove the 'px' for what is *sometimes* a truer measurement. | jQuery height() problems with Internet Explorer 6 | [
"",
"javascript",
"jquery",
"internet-explorer",
"height",
"containers",
""
] |
I have two namespaces defined in the default/"root" namespace, **nsA** and **nsB**. **nsA** has a sub-namespace, **nsA::subA**. When I try referencing a function that belongs to **nsB**, from inside of **nsA::subA**, I get an error:
```
undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)'
```
Any ideas? | Need more information to explain that error. The following code is fine:
```
#include <iostream>
namespace nsB {
void foo() { std::cout << "nsB\n";}
}
namespace nsA {
void foo() { std::cout << "nsA\n";}
namespace subA {
void foo() { std::cout << "nsA::subA\n";}
void bar() {
nsB::foo();
}
}
}
int main() {
nsA::subA::bar();
}
```
So, while specifying the global namespace solves your current problem, in general it is possible to refer to symbols in nsB without it. Otherwise, you'd have to write ::std::cout, ::std::string, etc, whenever you were in another namespace scope. And you don't. QED.
Specifying the global namespace is for situations where there's another nsB visible in the current scope - for instance if nsA::subA contained its own namespace or class called nsB, and you want to call ::nsbB:foo rather than nsA::subA::nsB::foo. So you'd get the error you quote if for example you have declared (but not defined) nsA::subA::nsB::theFunctionInNsB(...). Did you maybe #include the header for nsB from inside namespace subA? | Use global scope resolution:
```
::nsB::TheFunctionInNsB()
``` | How do I reference an external C++ namespace from within a nested one? | [
"",
"c++",
"gcc",
"namespaces",
""
] |
I am using the Windows Update API to update a bunch of VM's. With Windows Update comes the inevitable reboots. Can anyone think of a way that I could tell from a remote server if the windows box has indeed finished its reboot? All ideas or thoughts would appreciated.
EDIT:
Because the VM's are in Lab Manager and using a fenced configuration, WMI will not work, and although I thought about using the VM to send a signal when it was back up. There would have been no way to reliably know who to notify as the app waiting for the machine could be on any number of machines so it just didn't seem reasonable. However time is not essential (and even though I know this will bite me sometime when a Service Pack comes down) I have had good success with the PING and then wait 5 minutes so far, so I am going to use that for now. If I run into exceptions I will then try to implement the VM notfiying the world when it comes back up. Thanks to all. | Just wait for it to respond to a ping.
**In light of your comments:**
1 - [Use this script](https://stackoverflow.com/questions/56644/148431#148431)
2 - If you get any errors with that script, [follow these instructions.](https://stackoverflow.com/questions/774319/774390#774390) | Check for this event in the event log:
```
Event Type: Information
Event Source: EventLog
Event Category: None
Event ID: 6005
Date: 7/27/2007
Time: 12:56:24 PM
User: N/A
Computer: IWSDEV
Description:
The Event log service was started.
``` | How to you determine when Windows is done rebooting? | [
"",
"c#",
"reboot",
"windows-update",
""
] |
This is a great primer but doesn't answer what I need:
[Combining two sorted lists in Python](https://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python)
I have two Python lists, each is a list of datetime,value pairs:
```
list_a = [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]]
```
And:
```
list_x = [['1241000884000', 16], ['1241000992000', 16], ['1241001121000', 17], ['1241001545000', 19], ['1241004212000', 20], ['1241006473000', 22]]
```
1. There are actually numerous list\_a lists with different key/values.
2. All list\_a datetimes are in list\_x.
3. I want to make a list, list\_c, corresponding to each list\_a which has each datetime from list\_x and value\_a/value\_x.
Bonus:
In my real program, list\_a is actually a list within a dictionary like so. Taking the answer to the dictionary level would be:
```
dict = {object_a: [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]], object_b: [['1241004212000', 2]]}
```
I can figure that part out though. | Here's some code that does what you asked for. You can turn your list of pairs into a dictionary straightforwardly. Then keys that are shared can be found by intersecting the sets of keys. Finally, constructing the result dictionary is easy given the set of shared keys.
```
dict_a = dict(list_a)
dict_x = dict(list_x)
shared_keys = set(dict_a).intersection(set(dict_x))
result = dict((k, (dict_a[k], dict_x[k])) for k in shared_keys)
``` | "I want to make a list, list\_c, corresponding to each list\_a which has each datetime from list\_x and value\_a/value\_x."
```
def merge_lists( list_a, list_x ):
dict_x= dict(list_x)
for k,v in list_a:
if k in dict_x:
yield k, (v, dict_x[k])
```
Something like that may work also.
```
merged= list( merge_lists( someDict['object_a'], someDict['object_b'] )
```
This may be slightly quicker because it only makes one dictionary for lookups, and leaves the other list alone. | Merge two lists of lists - Python | [
"",
"python",
"django",
"list",
""
] |
Does anyone have any information comparing performance characteristics of different ConnectionPool implementations?
Background: I have an application that runs db updates in background threads to a mysql instance on the same box. Using the Datasource com.mchange.v2.c3p0.ComboPooledDataSource would give us occasional SocketExceptions:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
```
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Broken pipe
STACKTRACE:
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
```
Increasing the mysql connection timeout increased the frequency of these errors.
These errors have disappeared on switching to a different connection pool (com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource); however the performance may be worse and the memory profile is noticeably so (we get fewer, and much larger, GC's than the c3p0 pool). | Whatever connection pool you use, you need to assume that the connection could be randomly closed at any moment and make your application deal with it.
In the case with a long-standing DB connection on a "trusted" network, what often happens is that the OS applies a time limit to how long connections can be open, or periodically runs some "connection cleanup" code. But the cause doesn't matter too much -- it's just part of networking life that you should assume the connection can be "pulled from under your feet", and deal with this scenario accordingly.
So given that, I really can't see the point of a connection pool framework that doesn't allow you to handle this case programmatically.
(Incidentally, this is another of my cases where I'm glad I just write my own connection pool code; no black boxes mysteriously eating memory, and no having to fish around to find the "magic parameter"...) | You may want to have a look at some benchmark numbers up at <http://jolbox.com> - the site hosting BoneCP, a connection pool that is faster than both C3P0 and DBCP. | Performance comparison of JDBC connection pools | [
"",
"java",
"performance",
"jdbc",
"connection-pooling",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.