Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device.
The specific case is where I have a web interface for configuring a modem that comes up on `/dev/ttyUSB[0-9]`.
Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading `/sys/devices` and talking to the modem using some AT commands.
I would like to be able to open the device and do something like:
```
ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
```
The problem is that `pyserial` does this: `self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)` to open the serial port, where portstr is `/dev/ttyUSB0`, but it does it as the `nobody` user, which is unprivileged.
Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. `rw-rw----`).
What is the best way for a user such as `nobody` who should have as few permissions as possible to open a file in dev?
Ideas I will consider:
* Doing things in a subprocess using `sudo`.
* Changing permissions of the files in `/dev/` (instructions on how to do this properly using udev are appreciated!)
* Using another API or piece of software I have not considered. | Configure a *udev* rule to *chgrp* the new device to *nobody*, if it is acceptable that every access via the web interface be permitted the same access to the device. Here's what I put in my *eee-bpw* package in file */etc/udev/rules.d/99-bpw.rules*.
```
# Sierra Wireless AirCard 880 U
BUS=="usb", KERNEL=="ttyUSB2*", ACTION=="add", \
PRODUCT=="1199/6855/0", DEVNAME=="/dev/tts/USB2", \
OWNER="root", GROUP="dialout", \
SYMLINK+="bpw", RUN="/usr/sbin/bpw"
```
Substitute *nobody* for *dialout*. This particular rule assumes the device name to be */dev/ttyUSB2*, but you can extend the rule considerably, see the *udev* documentation. | There's another way of doing this: Unix/Linux allows sending file descriptors via Unix sockets. There's even a Perl module for that: [PassAccessRights.pm](http://search.cpan.org/~sampo/Socket-PassAccessRights-0.03/PassAccessRights.pm). Didn't find similar module for Python but it could be easily implemented. | Privilege Escalation in Web Environment for File Access | [
"",
"python",
"linux",
"permissions",
"serial-port",
"cgi",
""
] |
I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!
I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.
For example:
```
indexes = [2, 4, 5]
main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8]
```
the output would be:
```
[9, 2, 6]
```
(i.e., the elements with indexes 2, 4 and 5 from main\_list).
I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension). | ```
[main_list[x] for x in indexes]
```
This will return a list of the objects, using a list comprehension. | ```
t = []
for i in indexes:
t.append(main_list[i])
return t
``` | Picking out items from a python list which have specific indexes | [
"",
"python",
"list",
"indexing",
"list-comprehension",
""
] |
I have class where the relevant part looks like
```
class C {
void Method<T>(SomeClass<T> obj) {
list.Add(obj);
}
List<?> list = new List<?>();
}
```
How should I define the list so that the class compiles?
I want a list of type `List<SomeClass<?>>`, that is a list of objects of `SomeClass` where each object can have any type parameter. The Java `?` construct allows this; what is the C# equivalent? If no such thing exists, is there a suitable workaround? (A `List<object>` would do but is terribly ugly.) | I don't think you can do this in C#... you would have to add the type parameter to the class:
```
class C<T> {
void Method(SomeClass<T> obj) {
list.Add(obj);
}
List<SomeClass<T>> list = new List<SomeClass<T>>();
}
```
The other option would be to use an interface:
```
class C {
void Method<T>(T obj)
where T : ISomeClass {
list.Add(obj);
}
List<ISomeClass> list = new List<ISomeClass>();
}
``` | To do what you want, you have two options.
You can use List<object>, and handle objects. This will not be typesafe, and will have boxing/unboxing issues for value types, but it will work.
Your other option is to use a generic constraint to limit to a base class or interface, and use a List<Interface>. | Adding generic object to generic list in C# | [
"",
"c#",
"generics",
"list",
""
] |
If I have the following code:
```
class Foo(object):
bar = 1
def bah(self):
print(bar)
f = Foo()
f.bah()
```
It complains
> NameError: global name 'bar' is not defined
How can I access class/static variable `bar` within method `bah`? | Instead of `bar` use `self.bar` or `Foo.bar`. Assigning to `Foo.bar` will create a static variable, and assigning to `self.bar` will create an instance variable. | Define class method:
```
class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
```
Now if `bah()` has to be instance method (i.e. have access to self), you can still directly access the class variable.
```
class Foo(object):
bar = 1
def bah(self):
print self.bar
``` | How can I access "static" class variables within methods? | [
"",
"python",
"oop",
"methods",
"static-variables",
"class-variables",
""
] |
What's the current best practice for handling generic text in a platform independent way?
For example, on Windows there are the "A" and "W" versions of APIs. Down at the C layer we have the "\_tcs" functions (like \_tcscpy) which map to either "wcscpy" or "strcpy". And in the STL I've frequently used something like:
```
typedef std::basic_string<TCHAR> tstring;
```
What issues if any arise from these sorts of patterns on other systems? | There is no support for a generic (variable-width) chararacter like `TCHAR` in standard C++. C++ does have `wchar_t`, but the encoding isn't guaranteed. C++1x will much improve things once we have `char16_t` and `char32_t` as well as UTF-{8,16,32} literals.
I personally am not a big fan of generic characters because they lead to some nasty problems (like conversion) and, what's more, if you are using a type (like `TCHAR`) that might ever have a maximum width of 8, you might as well code with `char`. If you really need that backwards-compatibility, just use UTF-8; it is specifically designed to be a strict superset of ASCII. You may have to use conversion APIs (especially on Windows, which for some bizarre reason is UTF-16), but at least it'll be consistent.
EDIT: To actually answer the original question, other platforms typically have no such construct. You will have to define your TCHAR on that platform, or else use a library that provides one (but as you should no doubt be able to guess, I'm not a big fan of that concept in libraries either). | One thing to be careful of is to make sure for all static libraries that you have, and modules that use these static libraries, that you use the same char format. Because otherwise your code will compile, but not link properly.
I typically create my own `t` types based on the stl types. tstring, tstringstream, and even down to boost types like tpath\_t. | Cross-Platform Generic Text Processing in C/C++ | [
"",
"c++",
"c",
"string",
"cross-platform",
""
] |
I have two tables. Posts and Replies. Think of posts as a blog entry while replies are the comments.
I want to display X number of posts and then the latest three comments for each of the posts.
My replies has a foreign key "post\_id" which matches the "id" of every post.
I am trying to create a main page that has something along the lines of
Post
--Reply
--Reply
--Reply
Post
--Reply
so on and so fourth. I can accomplish this by using a for loop in my template and discarding the unneeded replies but I hate grabbing data from a db I won't use. Any ideas? | This is actually a pretty interesting question.
**HA HA DISREGARD THIS, I SUCK**
On edit: this answer works, but on MySQL it becomes tediously slow when the number of parent rows is as few as 100. **However, see below for a performant fix.**
Obviously, you can run this query once per post: `select * from comments where id = $id limit 3` That creates a lot of overhead, as you end up doing one database query per post, the dreaded *N+1 queries*.
If you want to get all posts at once (or some subset with a where) the following will *surprisingly* work. It assumes that comments have a monotonically increasing id (as a datetime is not guaranteed to be unique), but allows for comment ids to be interleaved among posts.
Since an auto\_increment id column is monotonically increasing, if comment has an id, you're all set.
First, create this view. In the view, I call post `parent` and comment `child`:
```
create view parent_top_3_children as
select a.*,
(select max(id) from child where parent_id = a.id) as maxid,
(select max(id) from child where id < maxid
and parent_id = a.id) as maxidm1,
(select max(id) from child where id < maxidm1
and parent_id = a.id) as maxidm2
from parent a;
```
`maxidm1` is just "max id minus 1"; `maxidm2`, "max id minus 2" -- that is, the second and third greatest child ids *within a particular parent id*.
Then join the view to whatever you need from the comment (I'll call that `text`):
```
select a.*,
b.text as latest_comment,
c.text as second_latest_comment,
d.text as third_latest_comment
from parent_top_3_children a
left outer join child b on (b.id = a.maxid)
left outer join child c on (c.id = a.maxidm1)
left outer join child d on (c.id = a.maxidm2);
```
Naturally, you can add whatever where clause you want to that, to limit the posts: `where a.category = 'foo'` or whatever.
---
Here's what my tables look like:
```
mysql> select * from parent;
+----+------+------+------+
| id | a | b | c |
+----+------+------+------+
| 1 | 1 | 1 | NULL |
| 2 | 2 | 2 | NULL |
| 3 | 3 | 3 | NULL |
+----+------+------+------+
3 rows in set (0.00 sec)
```
And a portion of child. Parent 1 has noo children:
```
mysql> select * from child;
+----+-----------+------+------+------+------+
| id | parent_id | a | b | c | d |
+----+-----------+------+------+------+------+
. . . .
| 18 | 3 | NULL | NULL | NULL | NULL |
| 19 | 2 | NULL | NULL | NULL | NULL |
| 20 | 2 | NULL | NULL | NULL | NULL |
| 21 | 3 | NULL | NULL | NULL | NULL |
| 22 | 2 | NULL | NULL | NULL | NULL |
| 23 | 2 | NULL | NULL | NULL | NULL |
| 24 | 3 | NULL | NULL | NULL | NULL |
| 25 | 2 | NULL | NULL | NULL | NULL |
+----+-----------+------+------+------+------+
24 rows in set (0.00 sec)
```
And the view gives us this:
```
mysql> select * from parent_top_3;
+----+------+------+------+-------+---------+---------+
| id | a | b | c | maxid | maxidm1 | maxidm2 |
+----+------+------+------+-------+---------+---------+
| 1 | 1 | 1 | NULL | NULL | NULL | NULL |
| 2 | 2 | 2 | NULL | 25 | 23 | 22 |
| 3 | 3 | 3 | NULL | 24 | 21 | 18 |
+----+------+------+------+-------+---------+---------+
3 rows in set (0.21 sec)
```
The explain plan for the view is only slightly hairy:
```
mysql> explain select * from parent_top_3;
+----+--------------------+------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------+------+---------------+------+---------+------+------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 3 | |
| 2 | DERIVED | a | ALL | NULL | NULL | NULL | NULL | 3 | |
| 5 | DEPENDENT SUBQUERY | child | ALL | PRIMARY | NULL | NULL | NULL | 24 | Using where |
| 4 | DEPENDENT SUBQUERY | child | ALL | PRIMARY | NULL | NULL | NULL | 24 | Using where |
| 3 | DEPENDENT SUBQUERY | child | ALL | NULL | NULL | NULL | NULL | 24 | Using where |
+----+--------------------+------------+------+---------------+------+---------+------+------+-------------+
```
However, if we add an index for parent\_fks,it gets a better:
```
mysql> create index pid on child(parent_id);
mysql> explain select * from parent_top_3;
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 3 | |
| 2 | DERIVED | a | ALL | NULL | NULL | NULL | NULL | 3 | |
| 5 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | util.a.id | 2 | Using where |
| 4 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | util.a.id | 2 | Using where |
| 3 | DEPENDENT SUBQUERY | child | ref | pid | pid | 5 | util.a.id | 2 | Using where |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
5 rows in set (0.04 sec)
```
---
As noted above, this begins to fall apart when the number of parent rows is few as 100, *even if we index into parent using its primary key*:
```
mysql> select * from parent_top_3 where id < 10;
+----+------+------+------+-------+---------+---------+
| id | a | b | c | maxid | maxidm1 | maxidm2 |
+----+------+------+------+-------+---------+---------+
| 1 | 1 | 1 | NULL | NULL | NULL | NULL |
| 2 | 2 | 2 | NULL | 25 | 23 | 22 |
| 3 | 3 | 3 | NULL | 24 | 21 | 18 |
| 4 | NULL | 1 | NULL | 65 | 64 | 63 |
| 5 | NULL | 2 | NULL | 73 | 72 | 71 |
| 6 | NULL | 3 | NULL | 113 | 112 | 111 |
| 7 | NULL | 1 | NULL | 209 | 208 | 207 |
| 8 | NULL | 2 | NULL | 401 | 400 | 399 |
| 9 | NULL | 3 | NULL | 785 | 784 | 783 |
+----+------+------+------+-------+---------+---------+
9 rows in set (1 min 3.11 sec)
```
(Note that I intentionally test on a slow machine, with data saved on a slow flash disk.)
Here's the explain, looking for exactly one id (and the first one, at that):
```
mysql> explain select * from parent_top_3 where id = 1;
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 1000 | Using where |
| 2 | DERIVED | a | ALL | NULL | NULL | NULL | NULL | 1000 | |
| 5 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | util.a.id | 179 | Using where |
| 4 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | util.a.id | 179 | Using where |
| 3 | DEPENDENT SUBQUERY | child | ref | pid | pid | 5 | util.a.id | 179 | Using where |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
5 rows in set (56.01 sec)
```
Over 56 seconds for one row, even on my slow machine, is two orders of magnitude unacceptable.
So can we save this query? It *works*, it's just too slow.
Here's the explain plan for the modified query. It looks as bad or worse:
```
mysql> explain select * from parent_top_3a where id = 1;
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 100 | Using where |
| 2 | DERIVED | <derived4> | ALL | NULL | NULL | NULL | NULL | 100 | |
| 4 | DERIVED | <derived6> | ALL | NULL | NULL | NULL | NULL | 100 | |
| 6 | DERIVED | a | ALL | NULL | NULL | NULL | NULL | 100 | |
| 7 | DEPENDENT SUBQUERY | child | ref | pid | pid | 5 | util.a.id | 179 | Using where |
| 5 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | a.id | 179 | Using where |
| 3 | DEPENDENT SUBQUERY | child | ref | PRIMARY,pid | pid | 5 | a.id | 179 | Using where |
+----+--------------------+------------+------+---------------+------+---------+-----------+------+-------------+
7 rows in set (0.05 sec)
```
But it completes *three* orders of magnitude faster, in 1/20th of a second!
How do we get to the much speedier parent\_top\_3a? We create *three* views, each one dependent on the previous one:
```
create view parent_top_1 as
select a.*,
(select max(id) from child where parent_id = a.id)
as maxid
from parent a;
create view parent_top_2 as
select a.*,
(select max(id) from child where parent_id = a.id and id < a.maxid)
as maxidm1
from parent_top_1 a;
create view parent_top_3a as
select a.*,
(select max(id) from child where parent_id = a.id and id < a.maxidm1)
as maxidm2
from parent_top_2 a;
```
Not only does this work much more quickly, it's legal on RDBMSes other than MySQL.
Let's increase the number of parent rows to 12800, the number of child rows to 1536 (most blog posts don't get comments, right? ;) )
```
mysql> select * from parent_top_3a where id >= 20 and id < 40;
+----+------+------+------+-------+---------+---------+
| id | a | b | c | maxid | maxidm1 | maxidm2 |
+----+------+------+------+-------+---------+---------+
| 39 | NULL | 2 | NULL | NULL | NULL | NULL |
| 38 | NULL | 1 | NULL | NULL | NULL | NULL |
| 37 | NULL | 3 | NULL | NULL | NULL | NULL |
| 36 | NULL | 2 | NULL | NULL | NULL | NULL |
| 35 | NULL | 1 | NULL | NULL | NULL | NULL |
| 34 | NULL | 3 | NULL | NULL | NULL | NULL |
| 33 | NULL | 2 | NULL | NULL | NULL | NULL |
| 32 | NULL | 1 | NULL | NULL | NULL | NULL |
| 31 | NULL | 3 | NULL | NULL | NULL | NULL |
| 30 | NULL | 2 | NULL | 1537 | 1536 | 1535 |
| 29 | NULL | 1 | NULL | 1529 | 1528 | 1527 |
| 28 | NULL | 3 | NULL | 1513 | 1512 | 1511 |
| 27 | NULL | 2 | NULL | 1505 | 1504 | 1503 |
| 26 | NULL | 1 | NULL | 1481 | 1480 | 1479 |
| 25 | NULL | 3 | NULL | 1457 | 1456 | 1455 |
| 24 | NULL | 2 | NULL | 1425 | 1424 | 1423 |
| 23 | NULL | 1 | NULL | 1377 | 1376 | 1375 |
| 22 | NULL | 3 | NULL | 1329 | 1328 | 1327 |
| 21 | NULL | 2 | NULL | 1281 | 1280 | 1279 |
| 20 | NULL | 1 | NULL | 1225 | 1224 | 1223 |
+----+------+------+------+-------+---------+---------+
20 rows in set (1.01 sec)
```
Note that these timings are for MyIsam tables; I'll leave it to someone else to do timings on Innodb.
---
But using Postgresql, on a similar but not identical data set, we get similar timings on `where` predicates involving `parent`'s columns:
```
postgres=# select (select count(*) from parent) as parent_count, (select count(*)
from child) as child_count;
parent_count | child_count
--------------+-------------
12289 | 1536
postgres=# select * from parent_top_3a where id >= 20 and id < 40;
id | a | b | c | maxid | maxidm1 | maxidm2
----+---+----+---+-------+---------+---------
20 | | 18 | | 1464 | 1462 | 1461
21 | | 88 | | 1463 | 1460 | 1457
22 | | 72 | | 1488 | 1486 | 1485
23 | | 13 | | 1512 | 1510 | 1509
24 | | 49 | | 1560 | 1558 | 1557
25 | | 92 | | 1559 | 1556 | 1553
26 | | 45 | | 1584 | 1582 | 1581
27 | | 37 | | 1608 | 1606 | 1605
28 | | 96 | | 1607 | 1604 | 1601
29 | | 90 | | 1632 | 1630 | 1629
30 | | 53 | | 1631 | 1628 | 1625
31 | | 57 | | | |
32 | | 64 | | | |
33 | | 79 | | | |
34 | | 37 | | | |
35 | | 60 | | | |
36 | | 75 | | | |
37 | | 34 | | | |
38 | | 87 | | | |
39 | | 43 | | | |
(20 rows)
Time: 91.139 ms
``` | Sounds like you just want the `LIMIT` clause for a `SELECT` statement:
```
SELECT comment_text, other_stuff FROM comments WHERE post_id = POSTID ORDER BY comment_time DESC LIMIT 3;
```
You'll have to run this query once per post you want to show comments for. There are a few ways to get around that, if you're willing to sacrifice maintainability and your sanity in the Quest for Ultimate Performance:
1. As above, one query per post to retrieve comments. Simple, but probably not all that fast.
2. Retrieve a list of `post_ids` that you want to show comments for, then retrieve all comments for those posts, and filter them client-side (or you could do it server-side if you had windowing functions, I think, though those aren't in MySQL). Simple on the server side, but the client-side filtering will be ugly, and you're still moving a lot of data from server to client, so this probably won't be all that fast either.
3. As #1, but use an unholy `UNION ALL` of as many queries as you have posts to display, so you're running one abominable query instead of N small ones. Ugly, but it'll be faster than options 1 or 2. You'll still have to do a bit of filtering client-side, but careful writing of the `UNION` will make that much easier than the filtering required for #2, and no wasted data will be sent over the wire. It'll make for an *ugly* query, though.
4. Join the posts and comments table, partially pivoting the comments. This is pretty clean if you only need *one* comment, but if you want three it'll get messy quickly. Great on the client side, but even worse SQL than #3, and probably harder for the server, to boot.
At the end of the day, I'd go with option 1, the simple query above, and not worry about the overhead of doing it once per post. If you only needed one comment, then the join option might be acceptable, but you want three and that rules it out. If windowing functions ever get added to MySQL (they're in release 8.4 of PostgreSQL), option 2 might become palatable or even preferable. Until that day, though, just pick the simple, easy-to-understand query. | LIMIT the return of non-unique values | [
"",
"sql",
"mysql",
"database",
""
] |
**ft2build.h** is located here:
**C:\Program Files\GnuWin32\include**
Initially, I made the same mistake as here:
[Fatal Error C1083: Cannot Open Include file: 'tiffio.h': No such file or directory VC++ 2008](https://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director)
but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:
```
BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
```
I should mention that this is Python 2.6 | Have you installed freetype properly? If you have, there should be a file named `ft2build.h` somewhere under the installation directory, and the directory where that file is found is the one that you should specify with `-I`. The string "GnuWin32" does not appear anywhere in the output of your build command, so it looks like you have not placed that directory in the correct include list. | This error comes about when building matplotlib on Ubuntu 10.10 also. The solution is to do:
```
sudo apt-get install python-dev libfreetype6-dev
``` | Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h' | [
"",
"python",
"build",
"matplotlib",
"freetype",
""
] |
I'm currently trying to filter a text-file which contains words that are separated with a "-". I want to count the words.
```
scanner.useDelimiter(("[.,:;()?!\" \t\n\r]+"));
```
The problem which occurs simply is: words that contain a "-" will get separated and counted for being two words. So just escaping with \- isn't the solution of choice.
How can I change the delimiter-expression, so that words like "foo-bar" will stay, but the "-" alone will be filtered out and ignored?
Thanks ;) | OK, I'm guessing at your question here: you mean that you have a text file with some "real" prose, i.e. sentences that actually make sense, are separated by punctuation and the like, etc., right?
Example:
> This situation is ameliorated - as far as we can tell - by the fact that our most trusted allies, the Vorgons, continue to hold their poetry slam contests; the enemy has little incentive to interfere with that, even with their Mute-O-Matic devices.
So, what you need as delimiter is something that is either any amount of whitespace and/or punctuation (which you already have covered with the regex you showed), or a hyphen that is surrounded by at least one whitespace on each side. The regex character for "or" is "|". There is a shortcut for the whitespace character class (spaces, tabs, and newlines) in many regex implementations: "\s".
```
"[.,:;()?!\"\s]+|\s+-\s+"
``` | This should be a simple enough: `[^\\w-]\\W*|-\\W+`
* But of course if it's prose, and you want to exclude *underscores*:
`[^\\p{Alnum}-]\\P{Alnum}*|-\\P{Alnum}+`
* or if you don't expect numerics:
`[^\\p{Alpha}-]\\P{Alpha}*|-\\P{Alpha}+`
**EDIT:** These are easier forms. Keep in mind the complete solution, that would handle dashes at the beginning and end of lines would follow this pattern. `(?:^|[^\\w-])\\W*|-(?:\\W+|$)` | use of delimiter function from scanner for "abc-def" | [
"",
"java",
"regex",
"java.util.scanner",
"text-formatting",
""
] |
If have a Java class with some fields I want to validate using Hibernate Validator.
Now I want my users to be able to configure at runtime which validations take place.
For example:
```
public class MyPojo {
...
@NotEmpty
String void getMyField() {
...
}
...
}
```
Let's say I want to remove the `NotEmpty` check or replace it with `Email` or `CreditCardNumber`, how can I do it? Is it even possible? I guess it comes down to changing annotations at runtime... | You can't do it normally.
Here's what I've done to get more dynamic validations working via Hibernate Validator.
1. Extend the `ClassValidator` class.
2. Override the `getInvalidVaues(Object myObj)` method. First, call `super.getInvalidValues(myObj)`, then add the hook to your customized validation.
3. Instantiate your custom validator and call `getInvalidValues` to validate. Any hibernate annotated validations will kick off at this point, and your custom dynamic validations (anything not supported by annotations) will kick off as well.
Example:
```
public class MyObjectValidator extends ClassValidator<MyObject>
{
public MyObjectValidator()
{
super(MyObject.class);
}
public InvalidValue[] getInvalidValues(MyObject myObj)
{
List<InvalidValue> invalids = new ArrayList<InvalidValue>();
invalids.addAll(Arrays.asList(super.getInvalidValues(myObj)));
// add custom validations here
invalids.addAll(validateDynamicStuff(myObj));
InvalidValue[] results = new InvalidValue[invalids.size()];
return invalids.toArray(results);
}
private List<InvalidValue> validateDynamicStuff(MyObject myObj)
{
// ... whatever validations you want ...
}
}
```
So your custom validation code can contain logic like "Do this validation, if the user configured it, otherwise do that one", etc. You may or may not be able to leverage the same code that powers the hibernate validations, but either way, what you are doing is more involved that the 'normal' use case for hibernate validator. | Actually it is possible in hibernate validator 4.1. Just read the documentation about [programatic constraint creation](https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/programmaticapi.html). | How can I change annotations/Hibernate validation rules at runtime? | [
"",
"java",
"annotations",
"runtime",
"hibernate-validator",
""
] |
There is an "[Unofficial Plurk API in Python](http://code.google.com/p/plurkapipy/)".
[Plurk](http://www.plurk.com/) is a twitter-like website.
Can I use the API(python) from Objective-C? Or i have to port them? | The way I see it, one option is to try this [this](http://www.saurik.com/id/5).
Alternatively, [ths plurk api](http://code.google.com/p/plurkapipy/source/browse/trunk/plurkapi.py) (which is really more of a python-automated abstraction than an API) isn't very big and is unlikely to take very long to port. Apart from being exceptionally simple code. The author's done all the legwork, defining urls and associated functions and so on. | Apple's iPhone developer license prohibits applications that use interpreted code. So, python is out, unfortunately. | How to use a python api on iPhone? | [
"",
"iphone",
"python",
"objective-c",
""
] |
I have a very high-traffic table with a `char(50)` field which takes part in several indexes. This `char(50)` field allows NULLS, and in that case a NULL value is considered to be the same as a non-NULL, zero-length string for my purposes.
I also disregard leading & trailing whitespace and, while I scrub the data before I insert it, it may also be inserted by means beyond my control.
I have a sproc that is used to copy data from one table to the main table, and it needs to be high-performance. I need to delete duplicate records before inserting the new data and I am using the method discussed [in this thread](https://stackoverflow.com/questions/714590/most-efficient-t-sql-delete-for-many-rows) to perform the deletes.
My delete statement looks like this (simplified):
```
delete masterTable
from masterTable t
join incomingDataTable inc on
(
LTRIM(RTRIM(COALESCE(inc.TextField,''))) =
LTRIM(RTRIM(COALESCE(t.TextField,'')))
)
where LTRIM(RTRIM(COALESCE(t.TextField,''))) <> ''
```
I [have read](http://msdn.microsoft.com/en-us/library/aa964133(SQL.90).aspx) that constructs like LTRIM(RTRIM(...)) are bad. Can my delete statement be improved, and if so, how?
**EDIT:** Just to clarify, `TextField` does take part in indexes on both tables.
**EDIT2:** `TextField` is defined as `char(50)` in both tables. It is not of type `TEXT`. | It is bad because your JOIN will have to scan the whole index, this is because your condition is not *[SARGable](https://web.archive.org/web/20170222053424/https://en.wikipedia.org/wiki/Sargable "Search ARGument ABLE")*
Are you also sure is is a TEXT datatype? Last I checked you could not use LTRIM or RTRIM against a Text datatype column?
in response to the char against varchar comment, run this
```
declare @v varchar(50),@v2 char(50)
select @v ='a',@v2 = 'a'
select datalength(@v),datalength(@v2)
``` | You need to:
1. Create a computed column on `masterTable` using expression `LTRIM(RTRIM(COALESCE(TextField,'')))`
* Build an index on this column and
* Use this column in a join.
The way your table is designed now it's quite impossible to make this query index-friendly.
If you cannot change your table structure but can estimate the number of `LEADING` spaces, you may use an approach described [**here**](http://explainextended.com/2009/03/24/article-aware-title-filtering-internationalization/).
This solution, however, is far not as efficient as creating an index on a computed column. | Is LTRIM(RTRIM(COALESCE(TextField,''))) Bad? | [
"",
"sql",
"sql-server",
"performance",
"t-sql",
""
] |
Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how?
I tried using:
key = Key.from\_path("ModelName", numericalId)
m = ModelName.get(key)
but the key generated wasnt correct. | You are looking for this: <http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_id> | [Getting an Entity Using a Key](http://code.google.com/intl/nl-NL/appengine/docs/python/datastore/creatinggettinganddeletingdata.html#Getting_an_Entity_Using_a_Key) | How to retrieve google appengine entities using their numerical id? | [
"",
"python",
"google-app-engine",
""
] |
I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended.
I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file.
Thanks,
g | Probably the best answer is to use Ant as-is... that is, use the Java version. My second suggestion would be to use [scons](http://www.scons.org/). It won't take much time using scons before you're asking, "Who ever thought of using XML to script a build?" | Some people use [Paver](http://www.blueskyonmars.com/projects/paver/) for build/deployment of Python packages. While I know it works, it does not appeal to me that much. | Python build/release system | [
"",
"python",
"ant",
"build-automation",
""
] |
We've got a .NET 2.0 WinForms app that needs to upload files to an IIS6 Server via WebDav. From time to time we get complaints from a remote office that they get one of the following error messages
* The underlying connection was closed:
an unexpected error occurred on send.
* The underlying connection was closed:
an unexpected error occurred on
receive.
This only seems to occur with large files (~20Mb plus). I've tested it with a 40Mb file from my home computer and tried putting 'Sleep's in the loop to simulate a slow connection so I suspect that it's down to network issues at their end... but
1. The IT at the remote office are no help
2. I'd like to rule out the posibility my code is at fault.
So - can anybody spot any misakes or suggest any workarounds that might 'bulletproof' the code against this problem. Thanks for any help. Chopped down version of code follows:
```
public bool UploadFile(string localFile, string uploadUrl)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
try
{
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;
req.UseDefaultCredentials = Program.WebService.UseDefaultCredentials;
req.Credentials = Program.WebService.Credentials;
req.SendChunked = false;
req.KeepAlive = true;
Stream reqStream = req.GetRequestStream();
FileStream rdr = new FileStream(localFile, FileMode.Open, FileAccess.Read);
byte[] inData = new byte[4096];
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
reqStream.Close();
rdr.Close();
System.Net.HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode!=HttpStatusCode.Created)
{
MessageBox.Show("Couldn't upload file");
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
return true;
}
``` | Try setting [KeepAlive](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx) to false:
```
req.KeepAlive = false;
```
This will allow the connection to be closed and opened again. It will not allow to use a [persistent connection](http://en.wikipedia.org/wiki/HTTP_persistent_connections). I found a lot of references in the Web that suggested this in order to solve a similar to yours error. This is a relevant [link](http://connectionstringexamples.com/article.php?story=underlying-connection-closed).
Anyway, it is not a good idea to use HTTP PUT (or HTTP POST) to upload large files. It will be better to use FTP or a download/upload manager. These will handle retries, connection problems, timeouts automatically for you. The upload will be faster too and you could also resume a stopped uploading. If you decide to stay with HTTP, you should at least try to add a retry mechanism. If an upload is taking too long, then there is a high probability that it will fail due to proxy, server timeout, firewall or what ever reason not to have with your code. | To remove the risk of a bug in your code, try using [`WebClient`](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx):
```
using (WebClient client = new WebClient())
{
client.UseDefaultCredentials = Program.WebService.UseDefaultCredentials;
client.Credentials = Program.WebService.Credentials;
client.UploadFile(uploadUrl, "PUT", localFile);
}
``` | Error using HttpWebRequest to upload files with PUT | [
"",
"c#",
"networking",
""
] |
Can I define a [static method](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods) which I can call directly on the class instance? e.g.,
```
MyClass.the_static_method()
``` | Yep, using the [`staticmethod`](https://docs.python.org/3/library/functions.html#staticmethod "staticmethod") decorator:
```
class MyClass(object):
@staticmethod
def the_static_method(x):
print(x)
MyClass.the_static_method(2) # outputs 2
```
Note that some code might use the old method of defining a static method, using `staticmethod` as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3):
```
class MyClass(object):
def the_static_method(x):
print(x)
the_static_method = staticmethod(the_static_method)
MyClass.the_static_method(2) # outputs 2
```
This is entirely identical to the first example (using `@staticmethod`), just not using the nice decorator syntax.
Finally, use [`staticmethod`](https://docs.python.org/3/library/functions.html#staticmethod "staticmethod") sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.
---
[The following is verbatim from the documentation:](https://docs.python.org/3/library/functions.html#staticmethod "staticmethod"):
> A static method does not receive an implicit first argument. To declare a static method, use this idiom:
>
> ```
> class C:
> @staticmethod
> def f(arg1, arg2, ...): ...
> ```
>
> The @staticmethod form is a function [*decorator*](https://docs.python.org/3/glossary.html#term-decorator "term-decorator") – see the description of function definitions in [*Function definitions*](https://docs.python.org/3/reference/compound_stmts.html#function "Function definitions") for details.
>
> It can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). The instance is ignored except for its class.
>
> Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see [`classmethod()`](https://docs.python.org/3/library/functions.html#classmethod "classmethod").
>
> For more information on static methods, consult the documentation on the standard type hierarchy in [*The standard type hierarchy*](https://docs.python.org/3/reference/datamodel.html#types "types").
>
> New in version 2.2.
>
> Changed in version 2.4: Function decorator syntax added. | I think that [Steven is actually right](https://stackoverflow.com/a/738102/3798217). To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.
(Note that this answer refers to Python 3.x. In Python 2.x you'll get a `TypeError` for calling the method on the class itself.)
For example:
```
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
def rollCall(n): #this is implicitly a class method (see comments below)
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
```
In this code, the "rollCall" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as "rollCall" is called from the class rather than an instance, the code will work fine. If we try to call "rollCall" from an instance, e.g.:
```
rex.rollCall(-1)
```
however, it would cause an exception to be raised because it would send two arguments: itself and -1, and "rollCall" is only defined to accept one argument.
Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.
This is where the decoration comes in:
If we precede the "rollCall" method with
```
@staticmethod
```
then, by explicitly stating that the method is static, we can even call it from an instance. Now,
```
rex.rollCall(-1)
```
would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.
You can verify this by trying the following code with and without the @staticmethod line commented out.
```
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
@staticmethod
def rollCall(n):
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)
``` | Static methods in Python? | [
"",
"python",
"static-methods",
""
] |
I'm having an issue with netbeans and Java. My program needs to be able to cope with large files being uploaded via an arraylist. So I used -Xmx512m to increase the maximum heap size via the netbeans.conf file.
I know that netbeans is catching the change, and I've restarted multiple times to make sure it is. Still, my program continues to crash with a Java heap space memory error when the total memory parameter is only 66650112 bytes; that is, 64M-ish.
How can I force this particular class, procedure, whatever, to allow more memory allocation? | I think you just configured the maximum heap size of netbeans IDE itself and not your program.
Go to your project "**properties**", select "**Run**" category. In the "**VM Options**" text box put your arguments (`-Xmx512m`). | try on **Tools** -> **Servers** -> on the **Platform** tab
there is a VM option below Java Platform. | Java heap space in netbeans.. but I've increased the heap size already! | [
"",
"java",
"netbeans",
"out-of-memory",
""
] |
I have the following data that looks like this for example:
> 34 foo
> 34 bar
> 34 qux
> 62 foo1
> 62 qux
> 78 qux
These are sorted based on the first column.
What I want to do is to process lines that starts with 34, but I also want
the file iteration to quit after it finds no more 34s, without having have to scan
through whole file. How would I do this?
The reason is because the number of lines to be processed is very large (~ 10^7).
And those that start with 34 are only around 1-10% of it.
I am aware that I can grep the lines and output it into another file, but this is too tedious and creates more disk space consumption.
This code illustrates my failed attempt using "continue":
```
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main () {
string line;
ifstream myfile ("mydata.txt");
vector<vector<string> > dataTable;
if (myfile.is_open())
{
while (! myfile.eof() )
{
stringstream ss(line);
int FirstCol;
string SecondCol;
if (FirstCol != 34) {
continue;
}
// This will skip those other than 34
// but will still iterate through all the file
// until the end.
// Some processing to FirstCol and SecondCol
ss >> FirstCol >> SecondCol;
cout << FirstCol << "\t << SecondCol << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
``` | Based on the assumption that the file is sorted by FirstCol, use a state variable that indicates whether or not you have found the first one. Once you have found the first one, as soon as you find a column that is != 34, you can break out of the loop.
For example, suppose your data is now:
```
15 boo
32 not
34 foo
34 bar
34 qux
62 foo1
62 qux
78 qux
```
...this code will do what you want:
```
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main () {
string line;
ifstream myfile ("mydata.txt");
vector<vector<string> > dataTable;
if (myfile.is_open())
{
bool found34 = false;
while ( myfile )
{
stringstream ss(line);
int FirstCol;
string SecondCol;
// This will skip those other than 34
// but will still iterate through all the file
// until the end.
// Some processing to FirstCol and SecondCol
myfile >> FirstCol >> SecondCol;
cout << FirstCol << "\t" << SecondCol << endl;
switch( FirstCol )
{
case 34 :
found34 = true;
cout << "Processing a 34";
continue; // keep looping
default :
if( found34 )
{
// we found all the 34's and now we're on to the next value, so we're done
cout << "We're done.";
break;
}
else
{
// we haven't found the first 34 yet, so keep scanning until we do
cout << "Keep on looking for a 34...";
continue;
}
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
``` | Use `break` instead of `continue`! `continue` returns to the head of the loop, only skipping the current iteration, while `break` leaves the loop for good.
On an unrelated note, your code has a bug that causes it to hang up if the file cannot be read for any reason (e.g. the user deletes it while your program tries to access it, the user removes the USB stick the file is on, etc.). This is because a loop condition such as:
```
while (!file.eof())
```
is **dangerous**! If the file stream goes into an error state, `eof` will never be `true` and the loop will go on and on and on …. You need to test whether the file is in *any* readable state. This is simply done by using the implicit conversion to a boolean value:
```
while (file)
```
This will cause the loop to run only as long as the file isn't finished reading **and** there is no error. | How can I properly parse my file? (Using break/continue) | [
"",
"c++",
"iteration",
"file-processing",
""
] |
I want to be able to store variables that are accessible to all of the other files in my ASP.net project but can be modified programatically. What I am looking for is something akin to being able to pull information from the web.config file for say the database connection strings (ex System.Configuration.ConfigurationManager.ConnectionStrings["cnDatabase"].ToString())
I have variables that have values that are shared amongst all of the other pages and I would like to be able to modify in one location instead of having to update the same value in 4+ aspx.cs pages. | AppSettings in the Web.Config file
or
public/internal constants | If you want something that is global to the application where you can add custom variables, use a Global.asax. Anything you add here will be available through the Global variable inherited in all pages and controls. If all you need is a key/value store, you can use the Application or Session static variables that are inherited in all pages and controls. Application (which is just a static instance of HttpApplicationState) is an object that you can use as a Hashtable to store custom values that will be available on all pages for all users. And, Session (HttpSessionState) is available the same way for use as a Hashtable, but the values you store will be unique per user session.
Note: if you need to access any of these objects outside of a page or control (ie. a custom class used within the context of a page request), you can get a reference to them through the current http context (HttpContext.Current). | How and where are variables that are used throughout the ASP.net Project created/stored? | [
"",
"c#",
"asp.net",
""
] |
I need help in how to create a custom file extension in my C# app. I created a basic notes management app. Right now I'm saving my notes as .rtf (note1.rtf). I want to be able to create a file extension that only my app understands (like, note.not, maybe) | File extensions are an arbitrary choice for your formats, and it's only really dependent on your application registering a certain file extension as a file of a certain type in Windows, upon installation.
Coming up with your own file format usually means you save that format using a format that only your application can parse. It can either be in plain text or binary, and it can even use XML or whatever format, the point is your app should be able to parse it easily. | As a deployment point, you should note that ClickOnce supports file extensions (as long as it isn't in "online only" mode). This makes it a breeze to configure the system to recognise new file extensions.
You can find this in project properties -> Publish -> Options -> File Associations in VS2008. If you don't have VS2008 you can also [do it manually](https://learn.microsoft.com/en-us/visualstudio/deployment/fileassociation-element-clickonce-application), but it isn't fun. | how to create a custom file extension in C#? | [
"",
"c#",
"file-extension",
""
] |
I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?
```
myemail%40gmail.com -> myemail@gmail.com
```
Would urllib.unquote() be the way to go? | I am pretty sure that urllib's [`unquote`](http://docs.python.org/library/urllib.html#urllib.unquote) is the common way of doing this.
```
>>> import urllib
>>> urllib.unquote("myemail%40gmail.com")
'myemail@gmail.com'
```
There's also [`unquote_plus`](http://docs.python.org/library/urllib.html#urllib.unquote_plus):
> Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values. | In Python 3, these functions are [`urllib.parse.unquote`](https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote) and [`urllib.parse.unquote_plus`](https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote).
The latter is used for example for query strings in the HTTP URLs, where the space characters () are traditionally encoded as plus character (`+`), and the `+` is percent-encoded to `%2B`.
In addition to these there is the [`unquote_to_bytes`](https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote_to_bytes) that converts the given encoded string to `bytes`, which can be used when the encoding is not known or the encoded data is binary data. However there is no `unquote_plus_to_bytes`, if you need it, you can do:
```
def unquote_plus_to_bytes(s):
if isinstance(s, bytes):
s = s.replace(b'+', b' ')
else:
s = s.replace('+', ' ')
return unquote_to_bytes(s)
```
---
More information on whether to use `unquote` or `unquote_plus` is available at [URL encoding the space character: + or %20](https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20). | Unescape Python Strings From HTTP | [
"",
"python",
"http",
"header",
"urllib2",
"mod-wsgi",
""
] |
*NOTE: As per [ECMAScript5.1, section 15.1.1.3](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.1.3), window.undefined is read-only.*
* *Modern browsers implement this correctly. for example: Safari 5.1, Firefox 7, Chrome 20, etc.*
* *Undefined is still changeable in: Chrome 14, ...*
When I recently integrated [Facebook Connect](http://en.wikipedia.org/wiki/Facebook_Platform#Facebook_Connect) with [Tersus](http://www.tersus.com), I initially received the error messages `Invalid Enumeration Value` and `Handler already exists` when trying to call Facebook API functions.
It turned out that the cause of the problem was
```
object.x === undefined
```
returning false when there is no property 'x' in 'object'.
I worked around the problem by replacing strict equality with regular equality in two Facebook functions:
```
FB.Sys.isUndefined = function(o) { return o == undefined;};
FB.Sys.containsKey = function(d, key) { return d[key] != undefined;};
```
This made things work for me, but seems to hint at some sort of collision between Facebook's JavaScript code and my own.
What could cause this?
Hint: It is well documented that `undefined == null` while `undefined !== null`. This is not the issue here. The question is how comes we get `undefined !== undefined`. | It turns out that you can set window.undefined to whatever you want, and so get `object.x !== undefined` when object.x is the *real* undefined. In my case I inadvertently set undefined to null.
The easiest way to see this happen is:
```
window.undefined = null;
alert(window.xyzw === undefined); // shows false
```
Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.
```
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
``` | The problem is that undefined compared to null using == gives true.
The common check for undefined is therefore done like this:
```
typeof x == "undefined"
```
this ensures the type of the variable is really undefined. | JavaScript: undefined !== undefined? | [
"",
"javascript",
""
] |
Is anyone using JIT tricks to improve the runtime performance of statically compiled languages such as C++? It seems like hotspot analysis and branch prediction based on observations made during runtime could improve the performance of any code, but maybe there's some fundamental strategic reason why making such observations and implementing changes during runtime are only possible in virtual machines. I distinctly recall overhearing C++ compiler writers mutter "you can do that for programs written in C++ too" while listening to dynamic language enthusiasts talk about collecting statistics and rearranging code, but my web searches for evidence to support this memory have come up dry. | Profile guided optimization is different than runtime optimization. The optimization is still done offline, based on profiling information, but once the binary is shipped there is no ongoing optimization, so if the usage patterns of the profile-guided optimization phase don't accurately reflect real-world usage then the results will be imperfect, and the program also won't adapt to different usage patterns.
You may be interesting in looking for information on [HP's Dynamo](http://www.hpl.hp.com/techreports/1999/HPL-1999-78.html), although that system focused on native binary -> native binary translation, although since C++ is almost exclusively compiled to native code I suppose that's exactly what you are looking for.
You may also want to take a look at [LLVM](http://www.llvm.org), which is a compiler framework and intermediate representation that supports JIT compilation and runtime optimization, although I'm not sure if there are actually any LLVM-based runtimes that can compile C++ and execute + runtime optimize it yet. | I did that kind of optimization quite a lot in the last years. It was for a graphic rendering API that I've implemented. Since the API defined several thousand different drawing modes as general purpose function was way to slow.
I ended up writing my own little Jit-compiler for a domain specific language (very close to asm, but with some high level control structures and local variables thrown in).
The performance improvement I got was between factor 10 and 60 (depended on the complexity of the compiled code), so the extra work paid off big time.
On the PC I would not start to write my own jit-compiler but use either LIBJIT or LLVM for the jit-compilation. It wasn't possible in my case due to the fact that I was working on a non mainstream embedded processor that is not supported by LIBJIT/LLVM, so I had to invent my own. | Runtime optimization of static languages: JIT for C++? | [
"",
"c++",
"optimization",
"jit",
"performance",
""
] |
Among all things I've learned in C++ (which isn't so much), operator overloading seems the most difficult. In general terms, when is it best to write an operator overload as a friend function? When do I have to explicilty use `*this`? Is always bad to use a temporary object? | Neil's answer is correct. In addition, [this link](http://www.parashift.com/c++-faq-lite/operator-overloading.html) provides a lot of good information about when, where, why, and how to use the various types of operator overloading in C++.
In general, I'd try to stick with overloads that are intuitive -- use of the '+' operator should reflect something analogous to addition, etc. If you find yourself doing string comparisons with the '+' operator or something like that, you should probably be using standard functions instead. | There is nothing magical abourt operator overloading - such overloads are simply functions with strange-looking names. So you write operator overloads in the same way you would write a named function. In fact, it's often a good idea to write a named function first - you can always change it to an operator later.
The only thing that you do have to be aware of is that the compiler makes use of a couple of your operators:
* operator=() when storing things in collections
* operator<() when sorting/searching things | What's the best way to implement a operator overload? | [
"",
"c++",
"operator-overloading",
""
] |
Suppose I have two instances of the same class. The class has a pointer to some data, and I want the instances to exchange the pointers as part of some private function's algorithm, but without compromising the data to everybody else by giving a direct access to it through a public function.
My first idea was to add a static variable of type bool called exchange, and two methods: a private one: void requestExchange() and a public one: Data\*\* respond().
requestExchange would set exchange to true, and will be immediately followed with respond() from the instance of choice, which will do the following:
```
if(exchange==true){
exchange=false;
return data;
}
else{return...?!
```
This was when I realized that I have no way of simulating "NO OP" since data may in fact be NULL, so supposedly everything goes as a response. Any ideas as to what can be done?
UPDATE: I thought a bit about it, and since the request-respond combo will only be called in the context where NULL as a result will be meaningful (exchange is most certainly true) I suppose I can simply return NULL and simulate a NO OP this way. To an outsider NULL as a result will be useless... But I'm still interested in suggestions. There must be a more well structured way of doing this. | Objects of the same class can access each others' private data directly. You often see this in copy constructors, for example. | Your description of the problem is not very clear. Why can't you just make respond() a private function?
The idea with a static class member is fraught with peril. What if two pairs of such instances want to communicate simultaneously? What if one sets the exchange flag and then dies before it comes around to calling respond()? What about thread safety?
As for returning a NO-OP or error indicator, you can either use exceptions (that's what they are for, but if your project does not use exceptions it's not a good idea to introduce them suddenly), or go the route of boost::optional. | Getting different instances to communicate | [
"",
"c++",
"object",
""
] |
Does adding -Xmx argument when running a Java program cause the garbage collector to act differently or occur less often? | Yes, most Java garbage collectors only run as needed, as opposed to running on a schedule whether needed or not. So, in general, more memory causes less frequent, longer garbage collections.
The generational garbage collectors have [settings to control the allocation of memory between the young and tenured generations.](http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html#1.1.Sizing%20the%20Generations%7Coutline) By setting these to use a smaller proportion of total memory for the young generation, the absolute size of the young generation can be kept the same as the total heap size is increased. Then, you won't see much of a change in garbage collection frequency or duration—but you will have more room for long-lived objects for applications like caching. | The general answer is that garbage will tend to be collected less often but the GC pauses will tend to be longer.
This is assuming you already have more memory available to the VM than your working set size; otherwise you might be spending a lot of time in garbage collection.
The GC characteristics vary greatly depending on which collector you are using and which version of Java, and whether you specified a higher -Xms in addition to the higher -Xmx. Older versions of Java (before 5) did not resize the young generation space after the VM had initialized. So even if you specified a really large -Xmx value, the size of the young generation would still be really small so you would see frequent young generation collections.
When a young generation collection occurs, there will be some "young" objects that will be promoted to the tenured space anyway, even though they are short-lived objects. This means that the tenured generation will slowly fill up with dead young objects, requiring periodic full GCs. The number of such objects that end up in the tenured generation is proportional to the number of young GCs (assuming constant activity in your program). So the advantage of a larger young generation is that there will be fewer young generation GCs, and therefore fewer objects from the young collection will be promoted to the tenured generation.
There are a number of tuning parameters besides -Xmx (google for java gc), and you will have to experiment with them since the optimal settings will vary for each application. | Does setting the max memory of a Java program affect the GC? | [
"",
"java",
"garbage-collection",
""
] |
How can I cut the string before '(' sign with php
For example:
$a = "abc dec g (gold)";
How can I cut the string become only "abc dec g"??
I tried to used this strstr($a, '(', true) but error display. | You could do this, using [`explode`](http://www.php.net/explode):
```
list($what_you_want,) = explode('(', $str, 2);
```
Or you could also do this, using [`substr`](http://www.php.net/substr) and [`strpos`](http://www.php.net/strpos):
```
$what_you_want = substr($str, 0, strpos($str, '('));
```
The reason you got the error using [`strstr`](http://www.php.net/strstr) is because the last argument is not available unless you have PHP 5.3.0 or later. | ```
$a=substr($a, 0, strpos($a, '('));
``` | Cut string before a symbol with php | [
"",
"php",
""
] |
I have a base class that declares a private non-static reference to the `DataBase Handler` instance (DBH).
DBH is a class we use to simplify database operations of derived classes. It contains the usual methods, like `ExecuteScalar`, `StartTransaction` among others; and it provides additional benefits in the application context, like caching and `zero configuration`.
Instances of derived classes use DBH to read/save its state in the database, and since their operations are not atomic, all derived classes use this transaction. Everything is going on in one place: a virtual method called `InsertUpdate()` declared in the base class.
Next, I have a collection (called Book) of instances of derived classes. I want to take collection updates as transaction.
I want to achieve something similar to this:
```
DatabaseHandler dbh = new DatabaseHandler()
t = dbh.StartTrasaction();
foreach( Type o in Book<Type> )
{
o.prop1 = ..
o.prop2 = ...
o.method1() ...
o.InsertUpdate(t); // uses its own instance of DatabaseHandler and starts its own transaction
}
dbh.EndTransaction(t);
```
Currently the `InsertUpdate` method is parameter-less. I guess I'll have to introduce an overloaded version which accepts a transaction object.
Besides solving my current issue, are there any design issues I need to know about? How can I improve this design or institute a better design? | Make sure you [read this question](https://stackoverflow.com/questions/224689/transactions-in-net#224702)
Personally, I usually go with ["my own"](https://stackoverflow.com/questions/251603/passing-db-connection-object-to-methods/251726#251726) implementation of a TrasactionScope like object that wacks data on to TLS with the added benefit of having a factory that allows for easy profiling and logging.
To me your current design sound fairly complex. By decoupling your raw database access code from your classes it will reduce duplication (and avoid requiring all your data access classes inherit off a base class). Defining an object as opposed to a set of static methods for DB access will ease testing (you can substitute a mock class) | Have you looked at the [System.Transactions](http://msdn.microsoft.com/en-us/library/system.transactions.aspx) namespace? Unless you have already discounted it for some reason you may be able to leverage the built in nested transaction support provided there - e.g:
```
using (var scope = new TransactionScope())
{
// call a method here that uses a nested transaction
someObject.SomeMethodThatAlsoUsesATransactionScope();
scope.Complete();
}
``` | Nested Database transactions in C# | [
"",
"c#",
"database",
""
] |
I don't have access to code here in front of me so I was just wondering if someone could help me out with Session.Evict().
Say I have a Person object with a child collection of Addresses. I populate the Person object from a session and lazy load the Addresses collection. I then call Session.Evict(personObject) to detach the Person object from the session. My question is, if I attempt to access the Addresses collection will it just return null, or will I get an exception because the NHibernate proxy can't find the associated session? | If you cause the lazy load to happen before you evict the entity, then the collection will be accessible even after the eviction. However if you evict the entity and then try to lazy load the child collection you will get an exception. | You will receive a NHibernate.LazyInitializationException. | NHibernate Session.Evict() | [
"",
"c#",
"nhibernate",
""
] |
Is there a way to find JavaScript variable on the page (get it as an object) by its name? Variable name is available as a string constant. | ```
<script>
var a ="test";
alert(a);
alert(window["a"]);
alert(eval("a"));
</script>
``` | All JS objects (which variables are) are available within their scope as named properties of their parent object. Where no explicit parent exists, it is implicitly the `window` object.
i.e.:
```
var x = 'abc';
alert(window['x']); //displays 'abc'
```
and for a complex object:
```
var x = {y:'abc'};
alert(x['y']); //displays 'abc'
```
and this can be chained:
```
var x = {y:'abc'};
alert(window['x']['y']); //displays 'abc'
``` | How to find JavaScript variable by its name | [
"",
"javascript",
""
] |
I need to check for a `string` located inside a packet that I receive as `byte` array. If I use `BitConverter.ToString()`, I get the bytes as `string` with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type `string` and if I call them with the `string` with dashes, It throws an exception.
I need a function that turns hex(as `string` or as `byte`) into the `string` that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is `string`, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because `BitConverter` doesn't convert correctly. | Like so?
```
static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
``` | For Unicode support:
```
public class HexadecimalEncoding
{
public static string ToHexString(string str)
{
var sb = new StringBuilder();
var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
}
public static string FromHexString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
}
}
``` | Converting from hex to string | [
"",
"c#",
"string",
"hex",
"bitconverter",
""
] |
How do I write the `magic` function below?
```
>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
``` | ```
a = 123456
b = str(a)
c = []
for digit in b:
c.append (int(digit))
print c
``` | You mean this?
```
num = 1234
lst = [int(i) for i in str(num)]
``` | Convert a number to a list of integers | [
"",
"python",
"list",
"integer",
""
] |
Will the following code work if resource doesn't implement IDisposable?
```
T resource = new T();
using (resource as IDisposable)
{
...
}
``` | Yes, it will work, check this running test:
```
[TestMethod]
public void TestMethod8()
{
using (new MyClass() as IDisposable)
{
}
}
public class MyClass { }
```
It just runs without any issue. If the corresponding class implements IDisposable it will call it, if not it will still work/run :).
**Update:** As others have said, I also wonder what's the use you want to give to it. My guess is you have something like a factory that can get instances from different classes, which may or may not be disposable :). | Yes. A `using` statement checks whether it's being given `null` and avoids trying to call `Dispose` if so.
From section 8.13 of the C# 3 spec:
> A using statement is translated into
> three parts: acquisition, usage, and
> disposal. Usage of the resource is
> implicitly enclosed in a try statement
> that includes a finally clause. This
> finally clause disposes of the
> resource. If a null resource is
> acquired, then no call to Dispose is
> made, and no exception is thrown. | Will using work on null? | [
"",
"c#",
"idisposable",
""
] |
Is there a better solution (using less code) for the following code snippet. It is something that I find myself doing a lot of in VB6 and was hoping to trim it down.
As I understand it Connection.Execute will not work
```
SQL = "SELECT SomeID FROM TableA"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
SomeID = RecordSet.Fields(0).Value
RecordSet.Close
SQL = "SELECT AnotherID FROM TableB"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
AnotherID = RecordSet.Fields(0).Value
RecordSet.Close
```
This isn't a functional issue just looking to see if there is a tidier way. | The default parameters for both `RecordSet.Open()` and `Connection.Execute()` are:
* adOpenForwardOnly
* adLockReadOnly
You use different settings, but there is no apparent reason not to go with the defaults in your case.
I don't know why you think that `Connection.Execute()` will not work, especially since you seem to have static SQL:
```
Function FetchOneField(Connection, SQL)
With Connection.Execute(SQL)
FetchOneField = .Fields(0).Value
.Close
End With
End Function
SomeID = FetchOneField(Connection, "SELECT SomeID FROM TableA")
AnotherID = FetchOneField(Connection, "SELECT AnotherID FROM TableB")
' or, not expressed as a function (not less lines, but "tidier" nevertheless)'
With Connection.Execute("SELECT SomeID FROM TableA")
SomeID = .Fields(0).Value
.Close
End With
``` | Assuming that you have 1 record per query you could do it this way
```
SQL = "SELECT TableA.SomeID, TableB.AnotherID FROM TableA, TableB"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
SomeID = RecordSet.Fields(0).Value
AnotherID = RecordSet.Fields(1).Value
RecordSet.Close
``` | More elegant solution for pulling value from DB using recordset | [
"",
"sql",
"vb6",
"select",
""
] |
I have 3 Windows Service Question
1. Is WS can work in background ? Is it possible to do some job every 2 minutes ? (if yes, can I get some help ?)
2. How can I install WS in simple way ? (not with Installutil.exe .......)
3. How can I run .exe file from Windows service ?
I've tried this way:
```
System.Diagnostics.Process G = new Process();
G.StartInfo.FileName = @"d:\demo.exe";
G.Start();
```
but it didn't work. | 1. Yes a windows service can and does work in the background. To do the same job every 2 minutes use the system.Timer class and put your code in the onElapsed event. I've recently created this type of service and found there are two types of Timer you can use, make sure you use the correct one or you will not find the onElapsed event.
2. I've not tried installing without the InstallUtil.exe but I do have a .bat file that I use which is run as part of my main application installation.
Your follow-up question on running an .exe from a Windows Service, to run an .exe from a Windows Service I have used:
```
Process p = new Process();
p.StartInfo.WorkingDirectory = @"C:\";
p.StartInfo.FileName = @"C:\demo.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();
p.WaitForExit();
```
Remember that the executable will run at the same level as the service which means it can't display anything on the desktop. If you are expecting to see any window open or the .exe requires any user input then you will be disappointed and the .exe may wait indefinitely. (I found this link [Launch external programs](http://www.thescarms.com/dotnet/Process.aspx) helped and there is also this question on SO - [Launching an Application (.EXE) from C#](https://stackoverflow.com/questions/240171/launching-a-application-exe-from-c)) | * Yes, use [Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) class ([example](http://www.csharphelp.com/archives/archive90.html))
* What's the problem with *installutil.exe*? If you didn't like it, generate an installer with VS.NET, but *installutil.exe* it's always in the background as far I know. ([Complete example 1](http://www.codeproject.com/KB/vb/Windows_Services_Part_2.aspx), [Complete example 2](http://www.developerfusion.com/article/3441/creating-a-windows-service-in-vbnet/3/)) | Windows Service Question | [
"",
"c#",
"windows-services",
"installation",
""
] |
How do you debug lua code embedded in a c++ application?
From what I gather, either I need to buy a special IDE and link in their special lua runtime (ugh). Or I need to build a debug console in to the game engine, using the [lua debug API](http://www.lua.org/manual/5.1/manual.html#3.8) calls.
I am leaning toward writing my own debug console, but it seems like a lot of work. Time that I could better spend polishing the other portions of the game. | There are several tools floating around that can do at least parts of what you want. I have seen references to a VS plugin, there is a SciTE debugger extension in Lua for Windows, and there is the Kepler project's [RemDebug](http://www.keplerproject.org/remdebug/index.html), as well as their [LuaEclipse](http://luaeclipse.luaforge.net/).
RemDebug may be on the track of what you need, as it was built to allow for debugging CGI scripts written in Lua. It does require access to the LuaSocket module to provide a communications channel between the target script and a controller as well as a couple of other modules.
A bigger issue might be the ability to load arbitrary modules from within whatever sandbox the game engine has put around your scripts. If you have some control over the engine, then that won't be as big an issue.
This isn't currently possible for developers of Adobe Lightroom plugins, for example, because Lightroom does not expose `require` inside the plugin's sandbox.
A surprise to me has been how rarely I have felt a need for a debugger when working with Lua. I've built several small applications in it for various projects and have been surprised at how well a combination of complete stack backtraces and the occasional `print` call works to locate the bugs that `require "strict"` didn't prevent in the first place. | How about [Decoda](http://www.unknownworlds.com/decoda)?? there is a video that explains how to use it, and it works pretty darn well for embedded lua source. (i am a happy customer). and it's pretty cheap. | Debugging embedded Lua | [
"",
"c++",
"debugging",
"lua",
""
] |
Below is the program I used for the test.
It prints (as expected):
```
Raise A
Event from A
Raise B
Event from B
```
Now, if we change first two lines of the Main to be:
```
A a = new B();
B b = new B();
```
the Program will print:
```
Raise A
Raise B
Event from B
```
which is also expected, as overriding event hides the private backing field in the base class and therefore events fired by the base class are not visible to clients of the derived class.
Now I am changing the same lines to:
```
B b = new B();
A a = b;
```
and the program starts printing:
```
Raise A
Raise B
Event from A
Event from B
```
What's going on?
```
class A
{
public virtual event EventHandler VirtualEvent;
public void RaiseA()
{
Console.WriteLine("Raise A");
if (VirtualEvent != null)
{
VirtualEvent(this, EventArgs.Empty);
}
}
}
class B : A
{
public override event EventHandler VirtualEvent;
public void RaiseB()
{
Console.WriteLine("Raise B");
if (VirtualEvent != null)
{
VirtualEvent(this, EventArgs.Empty);
}
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
a.VirtualEvent += (s, e) => Console.WriteLine("Event from A");
b.VirtualEvent += (s, e) => Console.WriteLine("Event from B");
a.RaiseA();
b.RaiseB();
}
}
``` | We have a single instance (of B) which has the following fields:
* A.VirtualEvent: null
* B.VirtualEvent: Two event handlers
The call to `a.RaiseA()` *just* prints "Raise A" - but nothing more, because the private field in A is null.
The call to `b.RaiseB()` prints the remaining three lines, because the event has been subscribed to twice (once to print "Event from A" and once to print "Event from B").
Does that help?
EDIT: To make it clearer - think of the virtual event as a pair of virtual methods. It's very much like this:
```
public class A
{
private EventHandler handlerA;
public virtual void AddEventHandler(EventHandler handler)
{
handlerA += handler;
}
public virtual void RemoveEventHandler(EventHandler handler)
{
handlerA -= handler;
}
// RaiseA stuff
}
public class B : A
{
private EventHandler handlerB;
public override void AddEventHandler(EventHandler handler)
{
handlerB += handler;
}
public override void RemoveEventHandler(EventHandler handler)
{
handlerB -= handler;
}
// RaiseB stuff
}
```
Now is it clearer? It's not *quite* like that because as far as I'm aware you can't override just "part" of an event (i.e. one of the methods) but it gives the right general impression. | You hooked up two event handlers to the same event. Since A and B are pointing to the same object, when you call b.RaiseB() both event handlers get fired. So first you're calling RaiseA which is a basecalss method. That prints Raise A. It then doesn't actually fire off the event because it's null. Then, you're raising B but *TWO* handlers are hooked up to it, therefore it first prints Raise B, and when the event fires, both handlers get called. | How virtual events work in C#? | [
"",
"c#",
"events",
"compiler-construction",
""
] |
Adding a script to a view generally involves something like this:
```
<script src="../../Scripts/jquery-1.3.1.min.js" type="text/javascript"></script>
```
Unfortunately, this doesn't work if the app is deployed in a virtual directory under IIS 6. The alternatives discussed [here](https://stackoverflow.com/questions/317315/asp-net-mvc-relative-paths) involve using Url.Content with "~" to resolve the path dynamically, but this completely breaks JS IntelliSense.
Is there a way to get around this and make IntelliSense work without losing the ability to deploy the app in a virtual directory? | Check out the [JScript IntelliSense FAQ](http://blogs.msdn.com/webdevtools/archive/2008/11/18/jscript-intellisense-faq.aspx) on the [Visual Web Developer Team Blog](http://blogs.msdn.com/webdevtools/default.aspx). The comments also reference Srully's `if(false)` trick. | For deployment code you can use the google ajax apis to load JQuery. It is recommended because it help the page load time due to the use of the google CDN.
to get intellisense add this to your page
```
<% if(false){ %>
<script src="../../Scripts/jquery-1.3.1.min.js" type="text/javascript"></script>
<%}%>
```
this will not be emitted because it is within an if(false) but intellisense will recognize it | ASP.NET MVC relative paths without breaking JavaScript IntelliSense? | [
"",
"javascript",
"asp.net-mvc",
"intellisense",
""
] |
Is there any sort of interactive debugger for JavaScript? I'm imagining something like a web page on the left, and a REPL interface on the right.
Or maybe even without having a web page, so I can just play around with the JavaScript language.
Something that doesn't require I refresh the web page with breakpoints in Firebug or VS to examine locals and type code into a Watch window. Maybe I just need to learn Firebug better?
JavaScript doesn't have to be *compiled*, after all.
Kind of like LinqPad but for JavaScript maybe?
Anyone follow me here? | Stand-alone REPL (no browser/DOM, just JavaScript): [JavaScript Shell](https://developer.mozilla.org/en/Rhino_Shell) from the [Rhino](http://www.mozilla.org/rhino/) project. | Node.js has a REPL.
On Mac OS X:
```
brew install node
node
```
.exit to exit the repl, .help for other options
<http://nodejs.org/docs/v0.3.1/api/repl.html> | Debugging JavaScript REPL-style? | [
"",
"javascript",
"debugging",
""
] |
```
DECLARE @ID INT ;
```
This statement parses fine with MS SQL Server, but gives me
*You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @ID INT' at line 1*
Does anyone have any idea about the reason? | DECLARE is used in stored procedures/functions.
If you're looking to set a variable for just regular queries, use SET | try naming the variable without the @
```
DECLARE id INT;
``` | What's wrong with this MySQL statement: DECLARE @ID INT | [
"",
"sql",
"t-sql",
"mysql",
""
] |
I have an array that might be present in my .aspx page, if it is, I want to fire a javascript function.
I tried:
```
if(someArray)
blah(someArray);
```
but I get an error when I havent' defined someArray. | You should probably be pre-defining the array as null and check to see if it resolves, rather than *sometimes* available.
```
Array someArray = null;
// this is where you'll populate or replace someArray
// if you don't, someArray simply remains empty
if (someArray)
{
...
}
``` | ```
if(typeof someArray !== 'undefined') {
blah(someArray);
}
``` | if array exists, then continue | [
"",
"javascript",
"arrays",
""
] |
I've recently been working on some database search functionality and wanted to get some information like the average words per document (e.g. text field in the database). The only thing I have found so far (without processing in language of choice outside the DB) is:
```
SELECT AVG(LENGTH(content) - LENGTH(REPLACE(content, ' ', '')) + 1)
FROM documents
```
This seems to work\* but do you have other suggestions? I'm currently using MySQL 4 (hope to move to version 5 for this app soon), but am also interested in general solutions.
Thanks!
\* I can imagine that this is a pretty rough way to determine this as it does not account for HTML in the content and the like as well. That's OK for this particular project but again are there better ways?
**Update:** To define what I mean by "better": either more accurate, performs more efficiently, or is more "correct" (easy to maintain, good practice, etc). For the content I have available, the query above is fast enough and is accurate for this project, but I may need something similar in the future (so I asked). | The text handling capabilities of MySQL aren't good enough for what you want. A stored function is an option, but will probably be slow. Your best bet to process the data within MySQL is to add a [user defined function](https://dev.mysql.com/doc/extending-mysql/5.7/en/adding-loadable-function.html). If you're going to build a newer version of MySQL anyway, you could also add a [native function](https://dev.mysql.com/doc/extending-mysql/5.7/en/adding-native-function.html).
The "correct" way is to process the data outside the DB since DBs are for storage, not processing, and any heavy processing might put too much of a load on the DBMS. Additionally, calculating the word count outside of MySQL makes it easier to change the definition of what counts as a word. How about storing the word count in the DB and updating it when a document is changed?
Example stored function:
```
DELIMITER $$
CREATE FUNCTION wordcount(str LONGTEXT)
RETURNS INT
DETERMINISTIC
SQL SECURITY INVOKER
NO SQL
BEGIN
DECLARE wordCnt, idx, maxIdx INT DEFAULT 0;
DECLARE currChar, prevChar BOOL DEFAULT 0;
SET maxIdx=char_length(str);
SET idx = 1;
WHILE idx <= maxIdx DO
SET currChar=SUBSTRING(str, idx, 1) RLIKE '[[:alnum:]]';
IF NOT prevChar AND currChar THEN
SET wordCnt=wordCnt+1;
END IF;
SET prevChar=currChar;
SET idx=idx+1;
END WHILE;
RETURN wordCnt;
END
$$
DELIMITER ;
``` | This is quite a bit faster, though just slightly less accurate. I found it 4% light on the count, which is OK for "estimate" scenarios.
```
SELECT
ROUND (
(
CHAR_LENGTH(content) - CHAR_LENGTH(REPLACE (content, " ", ""))
)
/ CHAR_LENGTH(" ")
) AS count
FROM documents
``` | Using SQL to determine word count stats of a text field | [
"",
"mysql",
"sql",
"text-processing",
"word-count",
""
] |
In a Pylons webapp, I need to take a string such as "<3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on.
Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.
The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77] | Use parseIntSet from [here](http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html)
I also like the pyparsing implementation in the comments at the end.
The parseIntSet has been modified here to handle "<3"-type entries and to only spit out the invalid strings if there are any.
```
#! /usr/local/bin/python
import sys
import os
# return a set of selected values when a string in the form:
# 1-4,6
# would return:
# 1,2,3,4,6
# as expected...
def parseIntSet(nputstr=""):
selection = set()
invalid = set()
# tokens are comma seperated values
tokens = [x.strip() for x in nputstr.split(',')]
for i in tokens:
if len(i) > 0:
if i[:1] == "<":
i = "1-%s"%(i[1:])
try:
# typically tokens are plain old integers
selection.add(int(i))
except:
# if not, then it might be a range
try:
token = [int(k.strip()) for k in i.split('-')]
if len(token) > 1:
token.sort()
# we have items seperated by a dash
# try to build a valid range
first = token[0]
last = token[len(token)-1]
for x in range(first, last+1):
selection.add(x)
except:
# not an int and not a range...
invalid.add(i)
# Report invalid tokens before returning valid selection
if len(invalid) > 0:
print "Invalid set: " + str(invalid)
return selection
# end parseIntSet
print 'Generate a list of selected items!'
nputstr = raw_input('Enter a list of items: ')
selection = parseIntSet(nputstr)
print 'Your selection is: '
print str(selection)
```
And here's the output from the sample run:
```
$ python qq.py
Generate a list of selected items!
Enter a list of items: <3, 45, 46, 48-51, 77
Your selection is:
set([1, 2, 3, 45, 46, 77, 48, 49, 50, 51])
``` | I've created a version of @vartec's solution which I feel is more readable:
```
def _parse_range(numbers: str):
for x in numbers.split(','):
x = x.strip()
if x.isdigit():
yield int(x)
elif x[0] == '<':
yield from range(0, int(x[1:]))
elif '-' in x:
xr = x.split('-')
yield from range(int(xr[0].strip()), int(xr[1].strip())+1)
else:
raise ValueError(f"Unknown range specified: {x}")
```
In the process, the function became a generator :) | Interpreting Number Ranges in Python | [
"",
"python",
"numeric-ranges",
""
] |
I get an error when I do the following:
```
if(Session["value"] != null)
{
// code
}
```
The error i get is this:
Object reference not set to an instance of an object.
Why is this? I always check my session this way? I am using the MVC Framework, does this has something to do with it?
EDIT:
The code is in the constructor of a Controller:
```
public class MyController : ControllerBase
{
private int mVar;
public MyController()
{
if (Session["value"] != null)
{
mVar= (int)Session["value"];
}
}
}
``` | The session only really exists during the *processing* of an action - I wouldn't expect it to be valid in the constructor of a controller. For example, the controller might (for all I know) be re-used between requests.
You will need to do this either in the action (method), or (perhaps more appropriately) in an action filter, or the `OnActionExecuting` (etc) method(s):
```
public abstract class ControllerBase : Controller
{
protected override void OnActionExecuting(
ActionExecutingContext filterContext)
{
// code involving this.Session // edited to simplify
base.OnActionExecuting(filterContext); // re-added in edit
}
}
``` | The [] is an indexer, it acts like a method on the class.
In this case, Session is null and you cannot perform the indexing on it.
Do this:
```
if(Session != null && Session["value"] != null)
{
// code
}
``` | C# Cannot check Session exists? | [
"",
"c#",
"asp.net-mvc",
"session",
"exists",
""
] |
When accessing my site from a number of machines $\_SERVER['REMOTE\_ADDR'] always resolves to an empty string. What can be the cause of this?
**Additional info:**
One of the machines is running the site on localhost. Shouldn't a machine on localhost always resolve to 127.0.0.1?
My set up is LAMP. One dev. machine that runs the site localhost and that has the problem is a Mac and runs XAMPP. I think our live staging environment is CentOS (shared host). | I guess this results from a missing reverse delegation for the address. You should avoid reverse resolution unless absolutely necessary.
Not only is it expensive in terms of latency, but can also yield unexpected results as there is no requirement on what to resolve to - or to resolve at aall. | I just ran into this problem, and it turns out that the PHP code was setting it to `''` explicitly before running my code. This was because the IPv6 remote addr didn't match its IPv4 only regex.
Leaving this here in case someone else has the same problem, it was a too simple reason for me to spot it.
The module in question was simplemachinesforum. | PHP $_SERVER['REMOTE_ADDR'] sometimes resolves to empty string | [
"",
"php",
""
] |
I am a bit rusty on generics, trying to do the following, but the compiler complains:
```
protected List<T> PopulateCollection(DataTable dt) where T: BusinessBase
{
List<T> lst = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T(dr);
lst.Add(t);
}
return lst;
}
```
So as you can see, i am trying to dump contents of a Table into an object (via passing a DataRow to the constructor) and then add the object to collection. it complains that T is not a type or namespace it knows about and that I can't use where on a non-generic declaration.
Is this not possible? | There are two big problems:
* You can't specify a constructor constraint which takes a parameter
* Your method isn't currently generic - it should be `PopulateCollection<T>` instead of `PopulateCollection`.
You've already got a constraint that `T : BusinessBase`, so to get round the first problem I suggest you add an abstract (or virtual) method in `BusinessBase`:
```
public abstract void PopulateFrom(DataRow dr);
```
Also add a parameterless constructor constraint to `T`.
Your method can then become:
```
protected List<T> PopulateCollection(DataTable dt)
where T: BusinessBase, new()
{
List<T> lst = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
t.PopulateFrom(dr);
lst.Add(t);
}
return lst;
}
```
If you're using .NET 3.5, you can make this slightly simpler using the extension method in [`DataTableExtensions`](http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.aspx):
```
protected List<T> PopulateCollection<T>(DataTable dt)
where T: BusinessBase, new()
{
return dt.AsEnumerable().Select(dr =>
{
T t = new T();
t.PopulateFrom(dr);
}.ToList();
}
```
Alternatively, you could make it an extension method itself (again, assuming .NET 3.5) and pass in a function to return instances:
```
static List<T> ToList<T>(this DataTable dt, Func<DataRow dr, T> selector)
where T: BusinessBase
{
return dt.AsEnumerable().Select(selector).ToList();
}
```
Your callers would then write:
```
table.ToList(row => new Whatever(row));
```
This assumes you go back to having a constructor taking a `DataRow`. This has the benefit of allowing you to write immutable classes (and ones which don't have a parameterless constructor) it but does mean you can't work generically without also having the "factory" function. | The only [constraint](http://www.atlassian.com/software/crowd/) you can specify which allows for creation of new instances is `new()` - basically, a parameterless constructor. To circumvent this do either:
```
interface ISupportInitializeFromDataRow
{
void InitializeFromDataRow(DataRow dataRow);
}
protected List<T> PopulateCollection<T>(DataTable dt)
where T : BusinessBase, ISupportInitializeFromDataRow, new()
{
List<T> lst = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
t.InitializeFromDataRow(dr);
lst.Add(t);
}
return lst;
}
```
Or
```
protected List<T> PopulateCollection<T>(DataTable dt, Func<DataRow, T> builder)
where T : BusinessBase
{
List<T> lst = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = builder(dr);
lst.Add(t);
}
return lst;
}
``` | C# Generics question | [
"",
"c#",
"generics",
"collections",
""
] |
I have a sql server table of licence keys/serial numbers.
Table structure is something like;
```
[
RecordId int,
LicenceKey string,
Status int (available, locked, used, expired etc.)
AssignedTo int (customerId)
....
]
```
Through my ASP.NET application, when the user decides to buy a licence clicking the accept button, i need to reserve a licence key for the user.
My approach is like,
Select top 1 licenceKey from KeysTable Where Status = available
Update KeysTable Set status = locked
then return the key back to the application.
My concern is, if two asp.net threads access the same record and returns the same licencekey.
What do you think is the best practice of doing such assignments ? Is there a well known aproach or a pattern to this kind of problem ?
Where to use lock() statements if i need any ?
I'm using Sql Server 2005, stored procedures for data access, a DataLayer a BusinessLayer and Asp.Net GUI.
Thanks | There's probably no need to use explicit locks or transactions in this case.
In your stored procedure you can update the table and retrieve the license key in a single, atomic operation by using an [`OUTPUT`](http://msdn.microsoft.com/en-us/library/ms177564.aspx) clause in your [`UPDATE`](http://msdn.microsoft.com/en-us/library/ms177523.aspx) statement.
Something like this:
```
UPDATE TOP (1) KeysTable
SET Status = 'locked'
OUTPUT INSERTED.LicenseKey
-- if you want more than one column...
-- OUTPUT INSERTED.RecordID, INSERTED.LicenseKey
-- if you want all columns...
-- OUTPUT INSERTED.*
WHERE Status = 'available'
``` | To achieve what you're talking about, you'll want to use a serializable transaction. To do this, follow this pattern:
```
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
--Execute select
--Execute update
COMMIT TRANSACTION
```
However, why do you have a table with every possible license key? Why not have a key generation algorithm, then create a new key when a user purchases it? | assigning a serial number to a client from a pool of serial numbers | [
"",
"c#",
"asp.net",
"design-patterns",
"locking",
"license-key",
""
] |
If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file? | Take at look at [CherryPy's Autoreload feature](http://www.cherrypy.org/attachment/wiki/AutoReload/autoreload.py). I think it looks quite simple and always worked well for me. | Here is a very old module that I posted nearly ten years ago. I may no longer work with current Python versions (I have not checked) but it may give some ideas.
<http://mail.python.org/pipermail/python-list/2000-April/031568.html> | How to automatically reload a python file when it is changed | [
"",
"python",
""
] |
Class names can be abbreviated as follows:
```
CustomerService => CS
CustomerPaymentService => CPS
UnpaidBillRetriever => UBR
FindAnyRemainingOpenUserTrasactions => FAROUT
```
This is supported by control-N (idea) or control-shift-T (eclipse). After some initial re-learning I now use this naming strategy heavily. But what is it called ? | It's called Camel-Case. Since you would only take the upper letters. | I would call it an acronym. | What is this notation called? | [
"",
"java",
""
] |
How can I convert special characters to HTML in JavaScript?
Example:
* `&` (ampersand) becomes `&`.
* `"` (double quote) becomes `"` when `ENT_NOQUOTES` is not set.
* `'` (single quote) becomes `'` only when `ENT_QUOTES` is set.
* `<` (less than) becomes `<`.
* `>` (greater than) becomes `>`. | You need a function that does something like
```
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
```
But taking into account your desire for different handling of single/double quotes. | The best way in my opinion is to use the browser's inbuilt HTML escape functionality to handle many of the cases. To do this simply create a element in the DOM tree and set the `innerText` of the element to your string. Then retrieve the `innerHTML` of the element. The browser will return an HTML encoded string.
```
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
```
Test run:
```
alert(HtmlEncode('&;\'><"'));
```
Output:
```
&;'><"
```
This method of escaping HTML is also used by the [Prototype JS library](http://www.prototypejs.org/) though differently from the simplistic sample I have given.
Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here. | Convert special characters to HTML in JavaScript | [
"",
"javascript",
""
] |
In the case of an IM client. I have made 2 separate threads to handle sending packets (by std io) and receiving packets. The question is how to make these 2 threads run simultaneously so that I can keep prompting for input while at the same time be ready to receive packets at any time?
I have already tried setting a timer but the data is always lost receiving. | I think you might have missed something significant with either Threads, Streams or both :-)
You can start a new thread like this:
```
myThread.start();
```
The thread will be started and the run() method will be executed automatically by the jvm.
If the threads run-method is reading from a Stream, and it is the only one reading, it will not "miss" anything in that stream. | Without more details, it is hard to give a complete answer. Nevertheless, here is the code for starting two threads:
```
Thread thread1 = new Thread () {
public void run () {
// ... your code here
}
};
Thread thread2 = new Thread () {
public void run () {
// ... your code here
}
};
thread1.start();
thread2.start();
``` | Running 2 threads simultaneously | [
"",
"java",
"multithreading",
"network-programming",
"simultaneous-calls",
""
] |
Consider i have a C# code, I need some tool that would perform an analysis of my code and report bugs and vulnerabilities. Are there any open source tools, something like klocwork.? | [FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx) can perform static analysis of compiled assemblies, [ReSharper](http://www.jetbrains.com/resharper/) can analyze your program at source code level. Certain editions of Visual Studio have Code Analysis built into them.
As a sidenote: get up to speed on [unit testing](http://en.wikipedia.org/wiki/Unit_test) (think [NUnit](http://www.nunit.org/) et al.) | fxcop would be my first choice | Software to test C# code | [
"",
"c#",
"automated-tests",
"code-analysis",
""
] |
Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e
`<p class="title">$title</p>
<p class="comment">$comment</p>`
and store in a flat file.
Would it be faster and acceptably low in LOC to reimplement the storage in xml or json, in a simple spec of my own or stick with the simple html route?.
I don't want to use relational database for this. | If a flat file is fast enough, then go with that, since it's very simple and accessible. Storing as XML and JSON but still using a flat file probably is very comparable in performance.
You might want to consider (ignore this if you just left it out of your question) sanitizing/filtering the text, so that users can't break your HTML by e.g. entering "</p>" in the comment text. | XML is nice, clean way to store this type of data. In Python, you could use [lxml](http://codespeak.net/lxml/tutorial.html) to create/update the file:
```
from lxml import etree
P_XML = 'xml_file_path.xml'
def save_comment(title_text, comment_text):
comment = etree.Element('comment')
title = etree.SubElement(comment, 'title')
title.text = title_text
comment.text = comment_text
f = open(P_XML, 'a')
f.write(etree.tostring(comment, pretty_print=True))
f.close()
save_comment("FIRST!", "FIRST COMMENT!!!")
save_comment("Awesome", "I love this site!")
```
That's a simple start, but you could do a lot more (i.e. set up an ID for each comment, read in the XML using lxml parser and add to it instead of just appending the file). | fastest way to store comment data python | [
"",
"python",
"xml",
"json",
""
] |
I'm writing a PHP script to grab text box data from a submitted form. These are simple text boxes and I don't want to accept any HTML tags. I think I should at least use strip\_tags() and addslashes(). Anything else? I wouldn't mind restricting the input to alphanumerics, should I use a regular expression to seek out nonstandard characters?
This is a simple form that actually (ugh) gets emailed to the person processing it. (No database, sadly.) And it's simple data, first and last name sort of things.
Edit:
I'd also like to know specifically what I should be looking for. What's the consensus on reasonable input filtering? | Use the [PHP filter functions](http://au.php.net/filter).
You can use them for sanitizing input and validating input (eg email addresses).
There are two approaches to validation (this also applies to security and lots of other things).
Firstly, you can default to allow anything except for that which is explicitly disallowed. Or you can default ti disallowing everything except that which is specifically allowed.
Generally speaking the latter approach is more secure and should be used except in cases where you have a compelling reason not to (eg it's simply too hard to know what's allowed, you're doing an app for users who aren't deemed to be a security threat and so on).
You have to be careful using this however. For people's names characters like ' and - are perfectly valid but naive implementations may restrict them. What you want to generally avoid is:
* SQL injection: **always** use [mysql\_real\_escape\_string()](http://au.php.net/mysql_real_escape_string) on any input;
* XSS (Cross site scripting): generally speaking you should strip out HTML tags from user input. You will of course sometimes have to allow them (eg rich text editor boxes) but even in those cases you will have a list of tags that you allow and you should strip out all others (especially tags); and
* Tpically you should strip out low characters (below ASCII 20? or so); and
* Depending on your internationalization requirements you may want to strip out high characters (above ASCII 127).
A good default value to use is:
```
$var = filter_var($var, FILTER_SANITIZE_STRING);
```
but pick the right filter for the situation. | This is a very common question with alot of not so clear answers. Functions like addslashes() can actually do more harm than good in some setups. Some basic rules to follow when dealing with user input, is don't trust anything and if it's not in the format you are expecting, don't try and fix it just raise an error.
If you only require alphanumeric, then a simple regex will handle that but a little more information would help.
What are you going to be doing with the data? How are you currently (or planning on) handling the input, e.g., user submits a form, you process the form and store data in a DB to later display (like a comment engine).
Edit: If it is as simple as sending a text box via email for a human to process. My biggest concerns would be XSS and smtp header injection (depending on how the email is being sent). Try and go with the simplest solution, If you just need to receive alpha-numeric data for now use a regex and only accept that. Another solution would be to use htmlentities with ENT\_QUOTES. | What should you check for in HTML form text fields? | [
"",
"php",
"html",
"security",
"forms",
""
] |
I need to create a PowerPoint 2007 presentation from a template with [Open XML Format SDK 2.0](http://www.microsoft.com/downloads/details.aspx?familyid=C6E744E5-36E9-45F5-8D8C-331DF206E0D0). The template has to be provided by the customer and is used for a individual layout style (font, background color or image,...). It needs to contain two predefined slides:
* Text slide
* Image slide
The application should now create a copy of the template file, create multiple copies of the text- and image slides and replace the content-placeholders with some content.
I already found some [code snippets from Microsoft](http://www.microsoft.com/downloads/details.aspx?familyid=8d46c01f-e3f6-4069-869d-90b8b096b556) to edit the title of a slide, delete them or replace a image on a slide. But i didn't find out how i can create a copy of a existing slide. Maybe somebody can help me with this. | I have been looking around for a similar answer and have found some resources to share:
[http://msdn.microsoft.com/en-us/library/cc850834(office.14).aspx](http://msdn.microsoft.com/en-us/library/cc850834(office.14).aspx "Insert a new slide into a PowerPoint presentation")
or more samples
[http://msdn.microsoft.com/en-us/library/cc850828(office.14).aspx](http://msdn.microsoft.com/en-us/library/cc850828(office.14).aspx "More samples")
or this website
[http://www.openxmldeveloper.com](http://www.openxmldeveloper.com "Open Xml Developer")
There is also this [free book documenting the OpenXML standard](http://openxmldeveloper.org/attachment/1970.ashx "Open XML Explained") which was somewhat helpful. | This is an example of what I thing you're looking for, but if not, let me know: <http://openxmldeveloper.org/articles/7429.aspx> | Create PowerPoint 2007 presentation from a template | [
"",
"c#",
".net",
"powerpoint",
"openxml",
"presentationml",
""
] |
I've encountered this apparently common problem and have been unable to resolve it.
**If I call my WCF web service with a relatively small number of items in an array parameter (I've tested up to 50), everything is fine.**
**However if I call the web service with 500 items, I get the Bad Request error.**
Interestingly, I've run [Wireshark](http://www.wireshark.org/) on the server and it appears that the request isn't even hitting the server - the 400 error is being generated on the client side.
**The exception is:**
> System.ServiceModel.ProtocolException: The remote server returned an unexpected response: (400) Bad Request. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
**The `system.serviceModel` section of my client config file is:**
```
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://serviceserver/MyService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService"
contract="SmsSendingService.IMyService" name="WSHttpBinding_IMyService" />
</client>
</system.serviceModel>
```
**On the server side, my web.config file has the following `system.serviceModel` section:**
```
<system.serviceModel>
<services>
<service name="MyService.MyService" behaviorConfiguration="MyService.MyServiceBehaviour" >
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyService.MyServiceBinding" contract="MyService.IMyService">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="MyService.MyServiceBinding">
<security mode="None"></security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyService.MyServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
I've [looked at](https://stackoverflow.com/questions/740039/c-wcf-wcf-service-returning-a-404-bad-request-when-sending-an-array-of-items) a [fairly large](https://stackoverflow.com/questions/323551/http-bad-request-error-when-requesting-a-wcf-service-contract) [number](http://rajaramtechtalk.wordpress.com/2008/05/29/systemservicemodelprotocolexception-the-remote-server-returned-an-unexpected-response-400-bad-request/) of [answers](http://www.stonejunction.com/post/2008/12/01/WCF-Call-gives-400-Bad-Request-response.aspx) to [this question](http://www.experts-exchange.com/Programming/Languages/.NET/Web_Services/Q_24002313.html) with [no success](http://joewirtley.blogspot.com/2007/08/maximum-string-content-length-and.html).
Can anyone help me with this? | Try setting maxReceivedMessageSize on the server too, e.g. to 4MB:
```
<binding name="MyService.MyServiceBinding" maxReceivedMessageSize="4194304">
```
The main reason the default (65535 I believe) is so low is to reduce the risk of Denial of Service (DoS) attacks. You need to set it bigger than the maximum request size on the server, and the maximum response size on the client. If you're in an Intranet environment, the risk of DoS attacks is probably low, so it's probably safe to use a value much higher than you expect to need.
By the way a couple of tips for troubleshooting problems connecting to WCF services:
* Enable tracing on the server as described in [this MSDN article](http://msdn.microsoft.com/en-us/library/ms733025.aspx).
* Use an HTTP debugging tool such as [Fiddler](http://www.fiddler2.com/fiddler2/) on the client to inspect the HTTP traffic. | I was also getting this issue also however none of the above worked for me as I was using a custom binding (for BinaryXML) after an long time digging I found the answer here: [Sending large XML from Silverlight to WCF](https://stackoverflow.com/questions/2882465)
As am using a customBinding, the maxReceivedMessageSize has to be set on the httpTransport element under the binding element in the web.config:
```
<httpsTransport maxReceivedMessageSize="4194304" />
``` | Large WCF web service request failing with (400) HTTP Bad Request | [
"",
"c#",
".net",
"wcf",
"web-services",
""
] |
```
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
```
The function doIt will print "dad". Is there a way to make it print "son"? | Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
```
class Son extends Dad {
static {
me = "son";
}
}
```
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class | In short, no, there is no way to override a class variable.
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding.
In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.
For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;
```
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
```
The JLS gives a lot more detail on hiding in section [8.3 - Field Declarations](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3) | Is there a way to override class variables in Java? | [
"",
"java",
"inheritance",
"overriding",
""
] |
I created a console app in c# with a single `Console.ReadLine` statement. Running this app within Visual Studio and stepping into the debugger shows 7 threads in the thread window (6 worker threads, one is .NET SystemEvents and the other is `vshost.RunParkingWindow` and the main thread).
When I run the app outside Visual Studio I see a total of 3 threads in Windows task manager. Why so many when I would expect 1 thread? What are the others being spawned for? | If you're running a .NET application, I believe you always get a thread (mostly sleeping) for the JIT (Just-in-Time compiler) as well as the GC (Garbage Collection) thread, in addition to your main thread. | You do not need to worry: If you don't explicitly use them you won't have any of your code running in another thread than the main thread. The other threads are for:
* Garbage collector
* Finalization
* Threadpool
> Do the 3 threads share one stdin?
Theorethically yes, but the others won't use it unless you use Console.ReadLine inside a destructor or inside ThreadPool.QueueUserWorkItem, so don't worry you will get all data in main thread | Why 3 threads for a basic single threaded c# console app? | [
"",
"c#",
".net",
"multithreading",
"console",
""
] |
I am opening a window as a modal.
window.showModalDialog("<http://www.google.com>","","dialogWidth:500px;dialogHeight:500px")
as I set height, what are other options available?
Like option buttons, menus etc. where I can find tutorials?
**EDIT**
*It works in Mozilla firefox, but people are saying it doesn't!*
My code is
Please somebody Edit my sample code for display purpose
```
<html>
<head>
<script>
function abc() {
window.showModalDialog("3.htm", "", "dialogWidth:500px;dialogHeight:500px");
}
</script>
</head>
<body>
<input type="button" id="check" name="check" onclick="abc()" value="open"/>
</body>
</html>
```
**Second EDIT**
code for page 3.htm
```
<html>
<head>
<script>
function abc(){
close()
}
</script>
</head>
<body>
<input type="button" id="check" name="check" onclick="abc()" value="close"/>
</body>
</html>
```
Check out both code on fire fox! and tell me.
**Third EDIT**
Ok It's not working in corme and opera | Be aware that showModalDialog is IE specific and won't necessarily work with other browsers. If you want cross browser modal dialogs you need to use a div to hide the rest of the page and overlay your dialog on top. It is easier to use an existing javascript library that already takes care of this. | I suggest not to use popups in web apps. Use floating divs instead which looks like a modal dialog but are better than the popups. | Modal dialog options | [
"",
"javascript",
""
] |
I'm working on an ASP.NET application that uses VB. I'm using a SQLReader/SQLCommand/SQLConnection within the VB file to try to pull data values.
I was mystified to find out that the reason why the query wasn't returning any values, and someone here showed me how to troubleshoot the query to verify things were being returned, which they weren't.
I talked to a co-worker, and he asked if it would match because I was feeding a string, and the Text field for the database is an nvarchar. How can I declare the variable in VB so that when fed in as a parameter for the query, it can match?
The types of data it looks to match are just basic things like "2", "2a", "1a", and so on.
If there's no way to just declare the nvarchar, does anyone have a suggestion on how I might workaround that?
Thanks a bunch.
Side note: This is a continuation, of sorts, of this question: [SQL Reader saying no values exist, query seems fine](https://stackoverflow.com/questions/768052/sql-reader-saying-no-values-exist-query-seems-fine)
Edit: Thanks for all the help. I set things up like you guys said, but now I'm getting an error that "No mapping exists from object type System.Data.SqlClient.SqlParameter to a known managed provider native type. "
I have the parameter as a form-wide variable like this:
```
Private travelParameter As New SqlParameter("@trip", SqlDbType.NVarChar)
```
And then inside the main form,
```
travelQuery.CommandText = "SELECT [StartLoc], [EndLoc],[TravelTime], [AvgSpeed], [Distance] FROM [TravelTimes] WHERE [TripNum] = @trip"
travelQuery.Parameters.AddWithValue("@trip", travelParameter)
```
Later on, a function like this will be called.
```
FillWithTime("2", travelReader, time, newCell)
```
Defined as:
```
Private Sub FillWithTime(ByVal TripNum As Char, ByRef travelReader As SqlDataReader, ByRef TimeData() As Object, ByRef Cell As System.Web.UI.WebControls.TableCell)
travelParameter.Value = TripNum
travelReader = travelQuery.ExecuteReader()
If (travelReader.Read()) Then
travelReader.GetValues(TimeData)
'stuff
End If
End Sub
```
Thanks again.
P.S. - Adam and Cerebus, I'd accept both answers if I could. They both really brought the idea together for me, thanks big time. | Your data type in .NET should be a `string`. You just need to make sure that your parameter instance is using `NVarChar` (if it's a `DbParameter`, then then that's `DBType.String`. If it's a `SqlDbParameter`, then that's `SqlDbType.NVarChar`). | The `nvarchar` SqlDbType maps to the .NET string datatype. Personally, I like to create SqlParameters by making them as specific as possible :
```
'This overload of the constructor takes the Parameter name, ...
' its SqlDbType and size.
Dim param as New SqlParameter("@trip", SqlDbType.NVarChar, 2)
param.Value = "1a"
travelQuery.CommandParameters.Add(param)
``` | Declaring an nvarchar in VB/Matching an nvarchar in a SQL query | [
"",
"asp.net",
"sql",
"vb.net",
"nvarchar",
""
] |
Is it possible to hide fields and/or properties from showing up in the debugger watch window? See, we've got a class here with over 50 private fields, most of which are exposed through public properties. This means we're seeing a duplication of a large number of data in the watch window listing.
Is there any means of controlling this? | Try this attribute:
```
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
```
Use it to hide your backing fields by placing the attribute above the field declaration like this:
```
class Foo
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
int bar; // this one will be hidden
int baz; // but this one will be visible like normal
}
```
Keep in mind that the `DebuggerBrowsableState` enumeration has two other members:
> **`Collapsed:`** Collapses the element in the debugger.
> **`RootHidden:`** This shows child elements of a collection but hides the root element itself. | Check out the DebuggerBrowsableAttribute:
<http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx>
In fact, this article has some very useful tips for this area:
<http://msdn.microsoft.com/en-us/magazine/cc163974.aspx>
You might find that using a DebuggerTypeProxy makes more sense. This allows you to provide a "custom view" of the type. | Hiding fields from the debugger | [
"",
"c#",
"debugging",
""
] |
I'm trying to specify the timezone on a string that I am passing to `DateFormat.parse`. We're currently using .net framework 2.0. Current code is
```
DateTimeFormatInfo DATE_FORMAT = CultureInfo.CurrentCulture.DateTimeFormat;
DateTime first = DateTime.Parse("Wed, 31 Oct 2007 8:00:00 -5", DATE_FORMAT);
```
But then when I do `first.ToString("r")`, the result is
```
Wed, 31 Oct 2007 09:00:00 GMT
```
What am I doing wrong? I also tried using `DateTime.SpecifyKind` method to set my DateTime object's Kind to Local, but it seems like you would need to specify the kind as local before you parse the string, if the timezone is part of the string.
My local timezone is EDT, that's what I'm ultimately trying to get this date to.
Edit - our solution:
input :
```
DateTime first = DateTime.SpecifyKind(DateTime.Parse("OCT 31, 2007 8:00 AM", DATE_FORMAT), DateTimeKind.Local);
```
output :
```
first.ToLocalTime().ToString("our format")
```
Still haven't found a way to get time zone abbreviation, like 'EDT'. | Use the [`ToLocalTime()`](http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx) method before calling `ToString()`.
```
first.ToLocalTime().ToString();
``` | You can use the "zz" or "zzz" date formats to give you -5 or -5:00. | how do I specify the timezone on a DateFormat string? | [
"",
"c#",
""
] |
A client has asked me to remove the icon from the form's title bar. As they don't want to display any icon. But this me guessing as when I click on the icon property you have to browse to some icon. | Set **ShowIcon** Property of the form to **False** to see if that's what your client wants. | There are two ways.
First is to create an empty Icon file and then **Select Form -> Right Click -> Goto Properties -> Goto Icon -> Select your file.**
The other approach is to set **FormBorderStyle** of the form to **FormBorderStyle.SizableToolWindow** or **FormBorderStyle.FixedToolWind**
And one more way is to set **ShowIcon** property to be **false**. | C# 2005: Remove icon from the form's title bar | [
"",
"c#",
"forms",
"titlebar",
""
] |
I would like a regular expression to match given a partial or camel cased string. For example, if the search set contains the string "MyPossibleResultString" I want to be able to match it with the likes of the following:
* MyPossibleResultString
* MPRS
* MPRString
* MyPosResStr
* M
I'd also like to include wildcard matching, e.g.:
* MyP\*RString
* \*PosResString
* My\*String
If it's not clear what I mean, the only example I can think of is Eclipse's "Open Type" dialog which is pretty much the exact behaviour I'm looking for. I'm not too up on the use of regexes, so I'm not sure if it matters if I'm looking for a solution in Java. | Ok so I can't really see why you would need the wildcard feature if you can already support the matching described in the first example. This is what I put together. Given a query string query, you use a regular expression to create a regular expression:
```
String re = "\\b(" + query.replaceAll("([A-Z][^A-Z]*)", "$1[^A-Z]*") + ".*?)\\b";
```
For example the query `MyPosResStr` will become the regex:
```
\\b(My[^A-Z]*Pos[^A-Z]*Res[^A-Z]*Str[^A-Z]*.*?)\\b
```
You then use this regex for your matching using the `Matcher.find` method to get something like this:
```
public static String matchCamelCase(String query, String str) {
query = query.replaceAll("\\*", ".*?");
String re = "\\b(" + query.replaceAll("([A-Z][^A-Z]*)", "$1[^A-Z]*") + ".*?)\\b";
System.out.println(re);
Pattern regex = Pattern.compile(re);
Matcher m = regex.matcher(str);
if (m.find()) {
return m.group();
} else return null;
}
```
This will return the first match to your camel case query in the string str.
EDIT: I have added a line to handle wildcards since in my tired stupor I didn't appreciate the need for them | As danbruc said, you have to generate a new regex for each new query. This code should do what you want.
```
public Pattern queryToPattern(String query) {
StringBuilder sb = new StringBuilder();
char[] chars = query.toCharArray();
boolean incamel = false;
for (int i=0; i < chars.length; i++) {
if (chars[i] == '*') {
if (!incamel)
sb.append(".*");
} else if (Character.isUpperCase(chars[i])) {
if (incamel) {
sb.append(".*");
}
sb.append(chars[i]);
incamel = true;
} else {
sb.append(chars[i]);
}
}
sb.append(".*");
return Pattern.compile(sb.toString());
}
```
A query of: MyP\*RString
Creates a pattern of: My.\* P.\* R.\* String.\* | Regex to match from partial or camel case string? | [
"",
"java",
"regex",
""
] |
I want to create a class which will have two properties, e.g. `key` & `value`.
And I want one method which will give me a `value` based on the `key`.
So what is the code? I know `Hashtable` but how to implement it in C#? Can I have a `string` as a key? | Look at the `Dictionary<TKey, TValue>` class: <http://msdn.microsoft.com/en-us/library/xfhwa508.aspx> | Here is the best way implement this (I use Int32 as an example of a type to store):
```
Dictionary<String,Int32> dictionary = new Dictionary<String,Int32>
{
// this just loads up the list with
// some dummy data - notice that the
// key is a string and the value is an int
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
};
```
Now you can grab values from the Dictionary<,> like this:
```
dictionary["one"]; // returns 1
dictionary["two"]; // returns 2
``` | How to create a property class in c#? | [
"",
"c#",
"dictionary",
"hashtable",
""
] |
I have seen many PHP function on how to generate a `<ul><li>` tag but my array input is quite complicated I guess. It is an array returned from a custom function called [xml2assoc](http://www.php.net/manual/en/class.xmlreader.php#88264)
My question is how can I convert the returned xml2assoc array result to a `<ul><li>` formatted HTML code using PHP.
Thanks.
```
$tree = array(
0 => array(
'tag' => 'NavigationMode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Introduction'
),
1 => array(
'tag' => 'NavigationNode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Sub Intro'
)
)
)
)
),
1 => array(
'tag' => 'NavigationMode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Module 1'
)
)
)
);
```
The final output that I need to generate is like this:
```
<ul>
<li>
Introduction
<ul>
<li>Sub Intro</li>
</ul>
</li>
<li>Module 1</li>
</ul>
``` | i didn't test it for variations of the demo data ...
```
<?php
function getTitle($node) {
foreach ($node['value'] as $cnode) {
if ($cnode['tag'] == 'Title') {
return $cnode['value'];
}
}
return 'untitled';
}
function getCNodes($node) {
$cnodes = array();
foreach ($node['value'] as $cnode) {
if ($cnode['tag'] == 'NavigationNode') {
$cnodes[] = $cnode;
}
}
return $cnodes;
}
function runTree($node) {
$title = getTitle($node);
$cnodes = getCNodes($node);
if (count($cnodes) > 0) {
$out = '<li>' . $title . "\n" . '<ul>';
foreach ($cnodes as $cnode) {
$out .= runTree($cnode);
}
$out .= '</ul>' . "\n" . '</li>' . "\n";
return $out;
} else {
return '<li>' . $title . '</li>' . "\n";
}
}
$tree = array(
0 => array(
'tag' => 'NavigationMode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Introduction'
),
1 => array(
'tag' => 'NavigationNode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Sub Intro'
)
)
)
)
),
1 => array(
'tag' => 'NavigationMode',
'value' => array(
0 => array(
'tag' => 'Title',
'value' => 'Module 1'
)
)
)
);
echo '<ul>';
foreach ($tree as $node) {
echo runTree($node);
}
echo '</ul>';
?>
``` | If you have XML as input, why not use XSLT to transform it to `<ul>`?
I guess your input looks something like this (I assume "Navigation*M*ode" is a typo):
```
<tree>
<NavigationNode>
<title>Introduction</title>
<NavigationNode>
<title>Sub Intro</title>
</NavigationNode>
</NavigationNode>
<NavigationNode>
<title>Module 1</title>
</NavigationNode>
</tree>
```
With a small XSLT 1.0 stylesheet:
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:template match="/tree">
<ul>
<xsl:apply-templates select="NavigationNode" />
</ul>
</xsl:template>
<xsl:template match="NavigationNode">
<li>
<xsl:value-of select="title" />
<xsl:if test="NavigationNode">
<ul>
<xsl:apply-templates select="NavigationNode" />
</ul>
</xsl:if>
</li>
</xsl:template>
</xsl:stylesheet>
```
This output is produced:
```
<ul>
<li>
Introduction
<ul>
<li>Sub Intro</li>
</ul>
</li>
<li>Module 1</li>
</ul>
```
[The PHP documentation shows how to use XSLT.](http://www.php.net/manual/en/xsl.examples.php) It's simple. | PHP: How to generate a <ul><li> tree in an xml2assoc array result? | [
"",
"php",
"tree",
""
] |
I guess the question is really about how to define a type as an existing primitive data type. Below clearly doesn't work, but I think you'll get the idea.
```
Type DWORD = typeof(UInt32);
private DWORD func1(int x)
{
return 123;
}
``` | There is no `typedef` in C#. You can't use `#define` macros to replace strings either (they are just conditional). The only rough equivalent is `using DWORD = System.UInt32;` on top of your source file. | What about
```
using DWORD = System.UInt32;
```
Downside to this is that you'll have to do it in each file that you require it in. | In C#, How to declare DWORD as an uint32? | [
"",
"c#",
""
] |
I recently had to program C++ under Windows for an University project, and I'm pretty confused about static and dynamic libraries system, what the compiler needs, what the linker needs, how to build a library ... is there any good document about this out there? I'm pretty confused about the \*nix library system as well (so, dylibs, the ar tool, how to compile them ...), can you point a review document about the current library techniques on the various architectures?
Note: due to my poor knowledge this message could contain wrong concepts, feel free to edit it.
Thank you
**Feel free to add more reference, I will add them to the summary.**
---
**References**
Since most of you posted \*nix or Windows specific references I will summarize here the best ones, I will mark as accepted answer the Wikipedia one, because is a good start point (and has references inside too) to get introduced to this stuff.
[Program Library Howto](http://www.dwheeler.com/program-library/Program-Library-HOWTO/) (Unix)
[Dynamic-Link Libraries (from MSDN)](http://msdn.microsoft.com/en-us/library/ms682589.aspx) (Windows)
[DLL Information (StackOverflow)](https://stackoverflow.com/questions/124549/dll-information) (Windows)
[Programming in C](http://www.cs.cf.ac.uk/Dave/C/) (Unix)
[An Overview of Compiling and Linking](http://edn.embarcadero.com/article/29930) (Windows) | Start with [Wikipedia](http://en.wikipedia.org/wiki/Library_(computing)) - plenty of information there, and lots of links to other useful resources.
P.S. But perhaps it would be better to just ask a specific question about the problem you're currently having. Learning how to solve it may go a long way to teaching you the general concepts. | You can find some background information from this [article here](http://encyclopedia.kids.net.au/page/dy/Dynamically_linked_library). It gives you the basic background. I'm trying to locate something with diagrams. This should be a good place to get started.
The fundamental differences between a static library and a DLL is that with the static library the code is compiled into your final executable whereas a dynamic link library involves linking in a "stub" library (into your application) which contains mappings to functions in a separate file (.dll).
Here's an MSDN entry on [creating a static Win32 Library](http://msdn.microsoft.com/en-us/library/ms235627.aspx) which might also help you.
..another link to MSDN for [creating a Dynamic Link Library](http://msdn.microsoft.com/en-us/library/ms235636.aspx)..
Just found [this site](http://edn.embarcadero.com/article/29930) which covers definitions of basically all the aspect you've quoted. | Static libraries, dynamic libraries, DLLs, entry points, headers ... how to get out of this alive? | [
"",
"c++",
"architecture",
"dynamic",
"static",
""
] |
I have the following classes. For testing purpose, I would like to get all the possible permutations of the class Client. I know that the number can be very large, but this is not my problem for now.
Client: No (int), Name(string), Address(Address object)
Address: Street(string), Country(string), etc.
For a property of type int, I always try the same three values (-1, 0, 1), for string (null, string.Empty, "Hello World", etc.). For the base types, it works well. However, for the class Address, this is different.
In brief, I am trying to write a method generic enough to take any Type (class, etc.) and get all the possible permutations (in other words: public IEnumerable GetPermutations(Type myType)). With the help of .NET Reflection, this method would loop on all the settable properties.
Does anybody have an idea how to do that?
Thanks | Here's a class that may get you started, though I haven't tested it much. Note that this will only work for classes that have a no-args constructor, and won't work for some types of recursive classes (e.g. a class with a property of its own type, such as a tree). You also may want to pre-populate more classes in the static constructor.
```
public static class PermutationGenerator
{
private static class Permutation<T>
{
public static IEnumerable<T> Choices { get; set; }
}
static PermutationGenerator()
{
Permutation<int>.Choices = new List<int> { -1, 0, 1 }.AsReadOnly();
Permutation<string>.Choices = new List<string> { null, "", "Hello World" }.AsReadOnly();
}
public static IEnumerable<T> GetPermutations<T>()
{
if (Permutation<T>.Choices == null) {
var props = typeof(T).GetProperties().Where(p => p.CanWrite);
Permutation<T>.Choices = new List<T>(GeneratePermutations<T>(() => Activator.CreateInstance<T>(), props)).AsReadOnly();
}
return Permutation<T>.Choices;
}
private static IEnumerable GetPermutations(Type t) {
var method = typeof(PermutationGenerator).GetMethod("GetPermutations", new Type[] {}).MakeGenericMethod(t);
return (IEnumerable)(method.Invoke(null,new object[] {}));
}
private delegate T Generator<T>();
private static IEnumerable<T> GeneratePermutations<T>(Generator<T> generator, IEnumerable<PropertyInfo> props)
{
if (!props.Any())
{
yield return generator();
}
else
{
var prop = props.First();
var rest = props.Skip(1);
foreach (var propVal in GetPermutations(prop.PropertyType))
{
Generator<T> gen = () =>
{
var obj = generator();
prop.SetValue(obj, propVal, null);
return (T)obj;
};
foreach (var result in GeneratePermutations(gen, rest))
{
yield return result;
}
}
}
}
}
``` | The [PEX](http://research.microsoft.com/en-us/projects/Pex/) testing framework does something along the lines. It attempts to provide several permutations of method parameters such that potentially useful test cases are covered. | Generate all the possible permutations of a class | [
"",
"c#",
"algorithm",
""
] |
I want a transient window to close itself when the user clicks away from it. This works for Firefox:
```
var w = window.open(...);
dojo.connect(w, "onblur", w, "close");
```
but it doesn't seem to work in Internet Explorer. Some other sites made reference to an IE-specific "onfocusout" event, but I couldn't find a coherent working example of what I need.
What does Stack Overflow say about the best way to get IE browser windows to close when they lose focus?
I'm using Dojo so if there's some shortcut in that library, information would be welcome. Otherwise standard IE calls will be the best answer. | I figured out the alternative in IE.
This:
```
that.previewWindowAction = function () {
var pw =
window.open(this.link, "preview",
"height=600,width=1024,resizable=yes,"
+ "scrollbars=yes,dependent=yes");
dojo.connect(pw, "onblur", pw, "close");
};
```
should be written like this to work in IE:
```
that.previewWindowAction = function () {
var pw =
window.open(this.link, "preview",
"height=600,width=1024,resizable=yes,"
+ "scrollbars=yes,dependent=yes");
if (dojo.isIE) {
dojo.connect
(pw.document,
"onfocusin",
null,
function () {
var active = pw.document.activeElement;
dojo.connect
(pw.document,
"onfocusout",
null,
function () {
if (active != pw.document.activeElement) {
active = pw.document.activeElement;
} else {
window.open("", "preview").close();
}
});
});
}
else {
dojo.connect(pw, "onblur", pw, "close");
}
};
```
The reasons?
* In IE, window objects do not respond to blur events. Therefore we must use the proprietary onfocusout event.
* In IE, onfocusout is sent by most HTML elements, so we must add some logic to determine which onfocusout is the one caused by the window losing focus. In onfocusout, the activeElement attribute of the document is always different from the previous value -- *except* when the window itself loses focus. This is the cue to close the window.
* In IE, documents in a new window send an onfocusout when the window is first created. Therefore, we must only add the onfocusout handler after it has been brought into focus.
* In IE, window.open does not appear to reliably return a window handle when new windows are created. Therefore we must look up the window by name in order to close it. | Try:
```
document.onfocusout = window.close();
``` | Self-closing popups in IE -- how to get proper onBlur behavior? | [
"",
"javascript",
"internet-explorer",
"dojo",
"popup",
"onblur",
""
] |
I've set up ehcache on our Java application, which uses Spring and Hibernate.
However, when I run Junit tests and print the stats, it seems there is nothing in cache:
OUTPUT OF CACHE MANAGER STATS ON EVERY CACHE:
COM.\*\*\*\*.SERVICES.CLARITY.DOMAIN.ACTIONITEM.BYRESOURCEUNIQUENAME:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0
COM.\*\*\*\*.SERVICES.CLARITY.DOMAIN.ACTIONITEM:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0
COM.\*\*\*\*.SERVICES.CLARITY.DOMAIN.RESOURCE:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0
CONTENT OF THE MAPPING FILE (ONLY PARTS, TOO BIG TO PASTE ALL):
```
<class name="ActionItem" table="CAL_ACTION_ITEMS" mutable="false" lazy="false" >
<cache region="com.****.services.clarity.domain.ActionItem" usage="read-only" include="all" />
```
[...]
```
<query name="byResourceUniqueName" cacheable="true" cache-region="com.****.services.clarity.domain.ActionItem.byResourceUniqueName" read-only="true">
FROM ActionItem WHERE id IN (
SELECT DISTINCT actionItemId FROM ActionItemAssignee as aia WHERE assigneeId IN (
SELECT userId FROM Resource WHERE uniqueName = :uniqueName
)
)
ORDER BY dueDate
</query>
```
CONTENT OF EHCACHE.XML:
```
<cache
name="com.****.services.clarity.domain.ActionItem"
maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
timeToLiveSeconds="600" overflowToDisk="false" />
<cache
name="com.****.services.clarity.domain.ActionItem.byResourceUniqueName"
maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
timeToLiveSeconds="60" overflowToDisk="false" />
<defaultCache maxElementsInMemory="200" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
memoryStoreEvictionPolicy="LRU" />
```
HIBERNATE CONFIG:
```
<property name="hibernateProperties">
<value>
hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.OracleDialect
hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider
hibernate.cache.use_query_cache=true
hibernate.show_sql=true
</value>
</property>
</bean>
```
Any ideas on how to populate the cache ?
Thanks. | Normally the items get populated to the cache by Hibernate automatically.
One thing I noticed in your configuration is that you didn't enable the statistics. Add the property
```
hibernate.generate_statistics=true
```
to your session factory's configuration and see, if numbers occur in your output. | yeah,when you use second cache in hibernate , when you will query you must set like this:
```
Query q=....
q.setCacheable(tre);
```
if you Spring you must write like this
```
getHibernateTemplate().setCacheQueries(true);
``` | EHCache doesn't seem to work | [
"",
"java",
"hibernate",
"ehcache",
""
] |
I'm currently maintaining some old code for a company. As it would happen, the current app I'm modifying uses an older version of the in-house library (we'll call this Lib1.dll). They also have a new version of the library called Lib2.dll that improves upon the previous library in many ways.
Unfortunately, Lib2 is not backward compatible with Lib1. What's worse is that they both use the same namespace Product.Common.
How do I use Lib2 and Lib1 in the same project? Right now if I add references to both of them, VS tells me that certain classes are ambiguous (which makes sense, since they using the same namespace).
Basically, I need something like:
```
Imports Lib1:Product.Common.Class
```
I'm using VB.NET 1.1. | I found a blog entry that has a solution in C#, not sure of the solution in VB.NET.
[Extern alias walkthrough](https://learn.microsoft.com/en-us/archive/blogs/ansonh/extern-alias-walkthrough)
and
[C# 2.0: Using different versions of the same dll in one application](https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-2-0-using-different-versions-of-the-same-dll-in-one-application)
---
### Edit:
It would seem you are out of luck. There does not appear to be a solution with .NET 1.1. | You could add another project to "host" one of your Lib projects. Basically just add a layer to nest the namespace a level deeper so it no longer causes a conflict. | Using two .NET libraries with the same namespace | [
"",
"c#",
".net",
"vb.net",
"dll",
""
] |
I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so <http://docs.python.org/library/stdtypes.html> is of no help. Could someone please point me to the relevant source code? | The comment on the implementation has the following to say:
> fast search/count implementation,
> based on a mix between boyer-moore
> and horspool, with a few more bells
> and whistles on the top.
>
> for some more background, see: <http://effbot.org/zone/stringlib.htm>
—<https://github.com/python/cpython/blob/master/Objects/stringlib/fastsearch.h#L5> | You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h. | How is string.find implemented in CPython? | [
"",
"python",
""
] |
having trouble coming up with search parameters for this issue, so I can't find an answer on my own.
```
Column X |
Message (info 1) |
Message (info 2) (info 1) |
```
Above is the contents of one column I need to handle. The result of the query should be the part INSIDE the parentheses only. Problem is, there's one program that saves two sets of information in parentheses, in which case the LATTER (**info 1**) is the one we want in the first column, in addition to which we must add a second column for **info 2**.
So I'm imagining I need to combine an if clause with a variable I can depend on to count how many left parentheses there are, for example. *If left\_parentheses = 2, Then .... Else If left\_parentheses = 1, Then ....*
But I don't know how to do that in SQL, and I also don't know how to separate between **info 1 / 2** in the example.
The result from the example would look like this:
```
Column 1 | Column 2
Info 1 |
Info 1 | Info 2
```
As usual, I'll try to look for the answer while waiting for tips here. Thanks! | Here's my go at it in SQL 2005 syntax using a Common Table Expression. I make no claims as to it's correctness or it's efficiency and I've made some assumptions about how you wanted it to work.
```
WITH BracketIndeces AS
(
SELECT
ColumnX AS ColVal,
CHARINDEX('(', ColumnX) as first_open_bracket,
CHARINDEX('(', ColumnX, CHARINDEX('(', ColumnX)+1) as second_open_bracket,
CHARINDEX(')', ColumnX) as first_close_bracket,
CHARINDEX(')', ColumnX, CHARINDEX(')', ColumnX)+1) as second_close_bracket
FROM SomeTable
)
SELECT
CASE
WHEN second_close_bracket = 0 THEN
SUBSTRING(ColVal, first_open_bracket+1, first_close_bracket - first_open_bracket-1)
ELSE
SUBSTRING(ColVal, second_open_bracket+1, second_close_bracket - second_open_bracket-1)
END AS Column1,
CASE
WHEN second_close_bracket = 0 THEN
NULL
ELSE
SUBSTRING(ColVal, first_open_bracket+1, first_close_bracket - first_open_bracket-1)
END AS Column2
FROM BracketIndeces
WHERE first_open_bracket <> 0
AND first_close_bracket <> 0
AND first_open_bracket < first_close_bracket
AND (
(second_open_bracket = 0 AND second_close_bracket = 0)
OR
(second_open_bracket < second_close_bracket
AND second_open_bracket > first_close_bracket
)
)
```
The where clause at the bottom is just to filter out any columns that either contain no brackets or contain brackets in a weird order and it uses NULL in Column2 when only one set of brackets are there. | Look at the builtin functions `charindex`, `patindex`, and `substring`.
`charindex` finds the positon of a specified character, `patindex` of a pattern, `substring` returns a portion of a string by position.
My advice would be to write a view over the table column X is in, that uses the above functions to provide two calculate columns. Then you could `insert into result table select info1, info2 from columnX'stable;`.
At least the calculated column `info2` will involve a case statement to handle the case when there is only one parenthesized "info" in the source, something along these lines:
```
case when [some test using patindex too check for two parenthesized infos]
then [some combination of patidex and substring to extract the second info]
else null;
```
In particular, patindex returns zero when a pattern is not found so:
```
patindex('%(%)%(%)%', columnX)
```
would return zero for your first example but not your second example.
You'll also need to consider how you want to handle erroneous data, specifically 1) rows with no parentheses, 2) with unequal numbers of open and close parentheses, 3) with additional text between two parenthesized "infos", 4) with additional text after the closing parenthesis.
I'd encourage you to add examples of all these possibilities, as well as correctly formatted columnXes, to your test data, and then test that the view does what you want in all cases. | SQL function question | [
"",
"sql",
"t-sql",
"logic",
""
] |
I have a table, contacts, that has a dozen columns or so. I want to identify each row in which at least one column contains a regular expression. I'm wondering if it's possible to do something like this:
```
select * from contacts where * like '%re%';
```
instead of this:
```
select * from contacts where last_name like '%re%' or first_name like '%re%' or ... ;
```
Is this possible? | I don't think that's possible. Perhaps you could put a trigger on the table to update a single denormalized column? | ```
select * from contacts where concat(last_name, ' ', first_name) like '%re%'
``` | Can I search multiple table columns in SQLite using a wildcard? | [
"",
"sql",
"sqlite",
""
] |
I want to apply pagination for some class of my application, in which i am using spring, struts2 & hibernate. Here i am calling action class from welcome.jsp file. It has following code :
```
<s:form action="marketing/allCountry.action">
<s:submit value="Click"></s:submit>
</s:form>
```
Now my `allCountry.action` class of java has following code :
```
public String executeAction() throws Exception {
try {
countryList = new ArrayList<Country>();
countryList = this.countrySecurityProcessor.findByAll(0, null, null, null, null, false, false, null, null, null, null, 0);
System.out.println("countryList = "+countryList);
return ActionSupport.SUCCESS;
} catch (Exception ex) {
return ActionSupport.ERROR;
}
}
```
It fetches the data properly, that i confirmed by printing countryList object. But now i am redirecting from `SUCCESS` to `country.jsp`. The code of `country.jsp` is :
```
<display:table list="countryList" requestURI="CountryAllAction" pagesize="3">
<display:column property="id" title="ID" />
<display:column property="name" />
</display:table>
```
Now at the time executing my application i am getting run time error like :
> javax.servlet.ServletException: javax.servlet.ServletException:
> Exception: [.LookupUtil] Error looking up property "id" in object type
> "java.lang.String". Cause: Unknown property 'id'
What is the solution to this type of error? | You need to have a getter for your countryList in your action.
```
List<Country> countryList = new ArrayList<Country>();
public String executeAction() throws Exception {
try {
countryList = this.countrySecurityProcessor.findByAll(0, null, null, null, null, false, false, null, null, null, null, 0);
System.out.println("countryList = "+countryList);
return ActionSupport.SUCCESS;
} catch (Exception ex) {
return ActionSupport.ERROR;
}
}
public List<Country> getCountryList() {
return countryList;
}
``` | I'm not familiar with Struts2 but it seems that DisplayTag can't find your countryList in any scope.
I don't see you putting countryList in from or request. If I'm not right may be you need to specify form name like
`<display:table list="${yourStrutsFormName.countryList}" ...` | Pagination through Struts2 using DisplayTag Library Framework | [
"",
"java",
"struts2",
""
] |
We have a transact sql statement that queries 4 tables with millions of rows in each.
It takes several minutes, even though it has been optimized with indexes and statistics according to TuningAdvisor.
The structure of the query is like:
```
SELECT E.EmployeeName
, SUM(M.Amount) AS TotalAmount
, SUM(B.Amount) AS BudgetAmount
, SUM(T.Hours) AS TotalHours
, SUM(TB.Hours) AS BudgetHours
, SUM(CASE WHEN T.Type = 'Waste' THEN T.Hours ELSE 0 END) AS WastedHours
FROM Employees E
LEFT JOIN MoneyTransactions M
ON E.EmployeeID = M.EmployeeID
LEFT JOIN BudgetTransactions B
ON E.EmployeeID = B.EmployeeID
LEFT JOIN TimeTransactions T
ON E.EmployeeID = T.EmployeeID
LEFT JOIN TimeBudgetTransactions TB
ON E.EmployeeID = TB.EmployeeID
GROUP BY E.EmployeeName
```
Since each transaction table contains millions of rows, I consider splitting it up into one query per transaction table, using table variables like `@real`, `@budget`, and `@hours`, and then joining these in a final `SELECT`. But in tests it seems to not speed up.
How would you deal with that in order to speed it up? | I'm not sure the query you posted will yield the results you're expecting.
It will cross join all the dimension tables (MoneyTransactions etc.) and multiply all the results.
Try this:
```
SELECT E.EmployeeName,
(
SELECT SUM(amount)
FROM MoneyTransactions m
WHERE M.EmployeeID = E.EmployeeID
) AS TotalAmount,
(
SELECT SUM(amount)
FROM BudgetTransactions m
WHERE M.EmployeeID = E.EmployeeID
) AS BudgetAmount,
(
SELECT SUM(hours)
FROM TimeTransactions m
WHERE M.EmployeeID = E.EmployeeID
) AS TotalHours,
(
SELECT SUM(hours)
FROM TimeBudgetTransactions m
WHERE M.EmployeeID = E.EmployeeID
) AS BudgetHours
FROM Employees E
``` | I don't know if you have all the indexes on your tables that will speed up things, but having big tables could have this impact on a query time.
I would recommend partitioning the tables if possible. It is more work, but everything you do to speed up the query now it won't be enough after few millions new records. | Sql query with joins between four tables with millions of rows | [
"",
"sql",
"sql-server",
"join",
"large-data-volumes",
""
] |
I'm trying to move some elements on the page, and during the time the animation occurs, I want to have "overflow:hidden" applied to an elemnt, and "overflow" back to "auto" once the animation is completed.
I know jQuery has an utility function that determines whether some element is being animated but I can't find it anywhere in the docs | ```
if( $(elem).is(':animated') ) {...}
```
**More info**: <https://api.jquery.com/animated-selector/>
---
Or:
```
$(elem)
.css('overflow' ,'hidden')
.animate({/*options*/}, function(){
// Callback function
$(this).css('overflow', 'auto');
};
``` | Alternatively, to test if something is not animated, you can simply add a "!":
```
if (!$(element).is(':animated')) {...}
``` | How do I find out with jQuery if an element is being animated? | [
"",
"javascript",
"jquery",
"animation",
""
] |
Before we start, strip\_tags() doesn't work.
now,
I've got some data that needs to be parsed, the problem is, I need to get rid of all the HTML that has been formated very strangely.
the tags look like this:
(notice the spaces)
```
< p > blah blah blah < / p > < a href= " link.html " > blah blah blah < /a >
```
All the regexs I've been trying aren't working, and I don't know enough about regex formating to make them work. I don't care about preserving anything inside of the tags, and would prefer to get rid of the text inside a link if I could.
Anyone have any idea?
(I really need to just sit down and learn regular expressions one day) | Does
```
preg_replace('/<[^>]*>/', '', $content)
```
work? | `strip_tags()` will work if you use `html_entity_decode()` on a variable before `strip_tags()`
```
<?php
$text = '< p > blah blah blah < / p > < a href= " link.html " > blah blah blah< /a >';
echo strip_tags(html_entity_decode($text));
?>
``` | php regex to remove HTML | [
"",
"php",
"html",
"regex",
""
] |
I want to make a Servlet filter that will read the contents of the Response after it's been processed and completed and return that information in XML or PDF or whatever. But I'm not sure how to get any information out of the HttpServletResponse object. How can I get at this information? | Add this to the filter java file.
```
static class MyHttpServletResponseWrapper
extends HttpServletResponseWrapper {
private StringWriter sw = new StringWriter(BUFFER_SIZE);
public MyHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public PrintWriter getWriter() throws IOException {
return new PrintWriter(sw);
}
public ServletOutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
public String toString() {
return sw.toString();
}
}
```
Use the follow code:
```
HttpServletResponse httpResponse = (HttpServletResponse) response;
MyHttpServletResponseWrapper wrapper =
new MyHttpServletResponseWrapper(httpResponse);
chain.doFilter(request, wrapper);
String content = wrapper.toString();
```
The content variable now has the output stream. You can also do it for binary content. | Spring now has feature for it . All you need to do is use [ContentCachingResponseWrapper], which has method public byte[] getContentAsByteArray() .
I Suggest to make WrapperFactory which will allow to make it configurable, whether to use default ResponseWrapper or ContentCachingResponseWrapper. | How can I read an HttpServletReponses output stream? | [
"",
"java",
"http",
"servlets",
""
] |
I created a service that is hosted on a server that has .Net 3.5 installed and I need to call this service from a client that only has .Net 2.0 installed.
Is there a way I can do this? | If your WCF service exposes an endpoint using basicHttpBinding, then it should be possible for the .NET 2.0 client to consume it. As Marc said, "no problem". | Yes you can do it. There are some caveats, however:
You have to use protocols that match. The standard .NET 2.0 libraries don't support many secure web service features; in fact, you're pretty much stuck with using only basicHttpBinding on the WCF service if you want to be consumed by a default install of .NET 2.0. That is a severe limitation in many enterprise scenarios. However, it may be all you need.
If you need more security but are still using .NET 2.0, there are alternatives. Again, your WCF service must accommodate your .NET 2.0 client, but your .NET 2.0 client will also need to take advantage of an external library. Specifically, you'll need the [Web Service Enhancements](http://www.microsoft.com/downloads/details.aspx?FamilyID=018a09fd-3a74-43c5-8ec1-8d789091255d&displaylang=en) put out by Microsoft. Keep in mind, however, that these libraries implement a *beta* version of some SOAP protocols, while WCF (the successor to WSE in many ways) implements the standards by default. Since there were some breaking changes in the protocols (particularly WS-Addressing), you'll have to offer a [customBinding](http://msdn.microsoft.com/en-us/library/ms731377.aspx) endpoint on your WCF service to accommodate.
Unfortunately, I can't tell you which you'll use, as it'll depend on which protocol you want to accommodate on the service, but most of your problems will be solved by changing the messageVersion of the [textMessageEncoding](http://msdn.microsoft.com/en-us/library/ms731787.aspx) for the custom binding. This is not the best scenario, but it could buy you something if you're trying to integrate a client.
Bottom line, there's a lot of work to get a .NET 2.0 client to talk to a WCF service for anything other than basicHttpBinding. In many cases, basicHttpBinding may be enough. For many enterprise scenarios, it will not. I can't speak as to which will help you or not, but it *is* possible to get it to work -- I've done it successfully.
But it's a big pain. Look for an alternative if you can. | Call .Net 3.5 WCF service from .Net 2.0 Standard ASMX Web Service Client | [
"",
"c#",
"wcf",
".net-3.5",
".net-2.0",
"asmx",
""
] |
After reading all the questions and answers on StackOverflow concerning overriding `GetHashCode()` I wrote the following extension method for easy and convenient overriding of `GetHashCode()`:
```
public static class ObjectExtensions
{
private const int _seedPrimeNumber = 691;
private const int _fieldPrimeNumber = 397;
public static int GetHashCodeFromFields(this object obj, params object[] fields) {
unchecked { //unchecked to prevent throwing overflow exception
int hashCode = _seedPrimeNumber;
for (int i = 0; i < fields.Length; i++)
if (fields[i] != null)
hashCode *= _fieldPrimeNumber + fields[i].GetHashCode();
return hashCode;
}
}
}
```
(I basically only refactored the code that someone posted there, because I really like that it can be used generally)
which I use like this:
```
public override int GetHashCode() {
return this.GetHashCodeFromFields(field1, field2, field3);
}
```
Do you see any problems with this code? | That looks like a solid way to do it.
My only suggestion is that if you're really concerned about performance with it, you may want to add generic versions for several common cases (ie. probably 1-4 args). That way, for those objects (which are most likely to be small, key-style composite objects), you won't have the overhead of building the array to pass to the method, the loop, any boxing of generic values, etc. The call syntax will be exactly the same, but you'll run slightly more optimized code for that case. Of course, I'd run some perf tests over this before you decide whether it's worth the maintenance trade-off.
Something like this:
```
public static int GetHashCodeFromFields<T1,T2,T3,T4>(this object obj, T1 obj1, T2 obj2, T3 obj3, T4 obj4) {
int hashCode = _seedPrimeNumber;
if(obj1 != null)
hashCode *= _fieldPrimeNumber + obj1.GetHashCode();
if(obj2 != null)
hashCode *= _fieldPrimeNumber + obj2.GetHashCode();
if(obj3 != null)
hashCode *= _fieldPrimeNumber + obj3.GetHashCode();
if(obj4 != null)
hashCode *= _fieldPrimeNumber + obj4.GetHashCode();
return hashCode;
}
``` | I wrote some stuff a little while back that you might solve your problem... (And actually, it could probably be improved to include the seed that you have...)
Anyway, the project is called Essence ( <http://essence.codeplex.com/> ), and it uses the System.Linq.Expression libraries to generate (based on attributes) standard representations of Equals/GetHashCode/CompareTo/ToString, as well as being able to create IEqualityComparer and IComparer classes based on an argument list. (I also have some further ideas, but would like to get some community feedback before continuing too much further.)
(What this means is that it's almost as fast as being handwritten - the main one where it isn't is the CompareTo(); cause the Linq.Expressions doesn't have the concept of a variable in the 3.5 release - so you have to call CompareTo() on the underlying object twice when you don't get a match. Using the DLR extensions to Linq.Expressions solves this. I suppose I could have used the emit il, but I wasn't that inspired at the time.)
It's quite a simple idea, but I haven't seen it done before.
Now the thing is, I kind of lost interest in polishing it (which would have included writing an article for codeproject, documenting some of the code, or the like), but I might be persuaded to do so if you feel it would be something of interest.
(The codeplex site doesn't have a downloadable package; just go to the source and grab that - oh, it's written in f# (although all the test code is in c#) as that was the thing I was interested in learning.)
Anyway, here is are c# example from the test in the project:
```
// --------------------------------------------------------------------
// USING THE ESSENCE LIBRARY:
// --------------------------------------------------------------------
[EssenceClass(UseIn = EssenceFunctions.All)]
public class TestEssence : IEquatable<TestEssence>, IComparable<TestEssence>
{
[Essence(Order=0] public int MyInt { get; set; }
[Essence(Order=1] public string MyString { get; set; }
[Essence(Order=2] public DateTime MyDateTime { get; set; }
public override int GetHashCode() { return Essence<TestEssence>.GetHashCodeStatic(this); }
...
}
// --------------------------------------------------------------------
// EQUIVALENT HAND WRITTEN CODE:
// --------------------------------------------------------------------
public class TestManual
{
public int MyInt;
public string MyString;
public DateTime MyDateTime;
public override int GetHashCode()
{
var x = MyInt.GetHashCode();
x *= Essence<TestEssence>.HashCodeMultiplier;
x ^= (MyString == null) ? 0 : MyString.GetHashCode();
x *= Essence<TestEssence>.HashCodeMultiplier;
x ^= MyDateTime.GetHashCode();
return x;
}
...
}
```
Anyway, the project, if anyone thinks is worthwhile, needs polishing, but the ideas are there... | GetHashCode Extension Method | [
"",
"c#",
"hash",
"hashcode",
"gethashcode",
""
] |
I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:
```
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
```
This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.
Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script? | You can use as many event methods as you want, jquery joins them in a queue. Order of method call is same as definition order - last added is last called.
A useful thing may be also that, you can load html code with script using ajax and when code is loaded into DOM $().ready() also will be called, so you can load ads dynamically. | Yes, adding multiple $(documents).ready()s is not a problem. All will be executed on the ready event.
Note however that your code sample is wrong. $(document).ready() takes a function, not an expression. So you should feed it a function like this:
```
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
```
That function will be executed when the document is ready. | second $(document).ready event jQuery | [
"",
"javascript",
"jquery",
"html",
"blocking",
"ads",
""
] |
My team uses a shared instance of Oracle for development using C#, NHibernate and ASP.NET, and we occasionally step on each others toes when making data or schema changes holding up everyone.
On another project I'm using Java and HSQL in 100% in-memory mode and just have Hibernate launch a script to import enough data to test with. It also creates and drops the schema. I considered using the same approach in .NET-land. With everything temporary and independent it would be impossible to step on each others toes, and we could still integrate our schema and data on the shared Oracle box.
I looked for HSQL on .NET and [SharpHSQL](http://sharphsql.codeplex.com/) seems to be a dead project (last release 2005).
Is there an active project equivalent to HSQL for .NET, or anything close enough to be used this way?
How have you got on using this approach in a team environment? Any issues?
How do you manage and version control data for populating the database? Is there a cross-platform solution for importing data? | See the HSQLDB.org web site. There is now a .NET implementation.
Edit: The implementation is for HSQLDB 1.8.0.x and is in the SVN repository. Needs to be compiled for use. | With something like [Sqlite](http://www.sqlite.org/), you could take the same approach in your .NET applications as with your Java applications - creating the schema and populating test data via NHibernate schema export / NHibernate population code is a good way to manage this scenario (NHibernate works fine with Sqlite). If you chose to, you could potentially standardise on Sqlite with your Java applications too. | Using HSQL for .NET development and related questions of process | [
"",
"c#",
"process",
"hsqldb",
"embedded-database",
"test-data",
""
] |
If `BaseFruit` has a constructor that accepts an `int weight`, can I instantiate a piece of fruit in a generic method like this?
```
public void AddFruit<T>()where T: BaseFruit{
BaseFruit fruit = new T(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
```
An example is added behind comments. It seems I can only do this if I give `BaseFruit` a parameterless constructor and then fill in everything through member variables. In my real code (not about fruit) this is rather impractical.
**-Update-**
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:
* Factory Pattern
* Reflection
* Activator
I tend to think reflection is the least clean one, but I can't decide between the other two. | Additionally a simpler example:
```
return (T)Activator.CreateInstance(typeof(T), new object[] { weight });
```
Note that using the new() constraint on T is only to make the compiler check for a public parameterless constructor at compile time, the actual code used to create the type is the Activator class.
You will need to ensure yourself regarding the specific constructor existing, and this kind of requirement may be a code smell (or rather something you should just try to avoid in the current version on c#). | You can't use any parameterised constructor. You can use a parameterless constructor if you have a "`where T : new()`" constraint.
It's a pain, but such is life :(
This is one of the things I'd like to address with ["static interfaces"](http://codeblog.jonskeet.uk/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx). You'd then be able to constrain T to include static methods, operators and constructors, and then call them. | Create instance of generic type whose constructor requires a parameter? | [
"",
"c#",
".net",
"generics",
""
] |
I'm really not sure how to approach this, but I am subscribing to events fired within a custom class and ideally I wish to queue them and handle them first in first out as they come in. I am aware of `Queue<T>` and I think I should use this? but my question is in the event handler when my message is received, would I simply `Enqueue()` to the queue there, and if so, then how can the queue be crunched through as new items are added?
I was considering calling a method in the constructor which performs something like (*hold on to your hats*):
```
while (true)
{
foreach (var item in myQueue)
{
// process
myQueue.Dequeue();
}
}
```
Surely there must be a more elegant way to do this? This should effectively hit myQueue and iterate as it contains elements and do what I want though. What would performance be like? I can spawn this on a separate thread to avoid any thread blocking, I just really have a had time accepting `while (true)`! | If you're running this from multiple threads, you'll need to introduce some form of locking to prevent problems with synchronization of your queue. You probably should also make sure that your queue is locked when enqueuing elements, as well as dequeuing elements.
If the thread processing your queue is going to do nothing but this, you're basic code is probably fine, with the exception of handling the case where the Queue is currently empty. You probably should add something like:
```
while (myQueue.Count == 0)
Thread.Sleep(sleepTime);
```
This would give you a way to "wait" until your events fill your queue.
Also, when you dequeue from your queue, you won't be able to use a foreach. You'll want to do something like:
```
while (myQueue.Count == 0)
Thread.Sleep(sleepTime);
while (myQueue.Count > 0)
{
lock(myLock)
myObject = myQueue.Dequeue();
// do your work...
}
```
This will prevent collection modification problems if somebody adds to your queue, and keep you from needing to lock the entire time your processing your elements.
---
Edit: I do agree with some comments, that this is not always the most effective strategy.
If the queue is going to be largely empty, and only have elements on occasion, I'd make a custom class that wraps it.
You could have an event triggered when the queue's made empty/non-empty. As soon as the queue receives items, the event could trigger a thread to process it and empty it out. As soon as it reached 0 items, it could have an event to stop the processing.
This would be much more effective than waiting constantly if the queue's state is empty most of the time. If, on the other hand, the queue is full nearly constantly, and the processing thread will rarely keep up, I'd use the approach above for simplicity. | This is a classic producer/consumer problem. A quick web search reveals <http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80,loband).aspx>, which covers this exactly.
You don't want to do a while(true) loop since your thread will be burning 100% of the CPU, even when there is no work for it do, potentially starving other threads in the system. | Loop through list in a thread continually as it receives new elements | [
"",
"c#",
".net",
"events",
"queue",
""
] |
I looking to create a custom calender with Zend Framework, I am hoping that it will be able to list all the days of the month for the coming years and then have a different bg color on the date if there is an event on this. I am however struggling to create this firstly because it needs to go into the layout view, rather than an action, so where does the logic go? I am also unclear as to how the logic with mkdate() would work.
Can someone point me in the right direct please?
Thanks | Here is a simple Calendar class that uses Zend\_Date and Zend\_Locale that you can use as a starting point:
[www.arietis-software.com/index.php/2009/05/26/a-php-calendar-class-based-on-zend\_date/](http://www.arietis-software.com/index.php/2009/05/26/a-php-calendar-class-based-on-zend_date/) | I've created and embedded a calendar in a similar why to which you are describing. My approach was to implement the calendar as a [view helper](http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.custom).
The helper, was called `My_View_Helper_Calendar` and has to contain a public method called `calendar` which I have returning an instance of the helper, like so:
```
public function calendar()
{
// Calls to private methods here
return $this;
}
```
As indicated, I set up some private methods within the view helper to do the calendar building, and had another public method called `toHtml` which renders the calendar as HTML.
That way, calling the helper from the context of a view file is as easy as:
```
<?= $this->calendar()->toHtml(); ?>
```
Hope this helps you get on the right track. | Calendar in Zend Framework | [
"",
"php",
"mysql",
"zend-framework",
""
] |
I have part of XmlDocument Example.xml as given below:
```
<rapaine dotoc="palin" domap="rattmin">
<derif meet="local" />
<derif meet="intro" />
.
.
.
</rapaine>
```
Here i am creating a Nodelist and fetching the element raplin to get its attributes.
Now i want to make sure that whether the attributes 'dotoc' and 'domap' are the attributes of rapaine with respective values which are always fixed.Then only i can access the childNodes 'deriff' with its attribute 'meet'. here the value only changes.
i have written a part of code there are no compile errors but on debugging i found that its not going inside the for loop to check its attributes and child nodes.
```
XmlNodeList listOfSpineRootNodes = opfXmlDoc.GetElementsByTagName("rapine");
for (int x = 0; x < listOfSpineRootNodes.Count; x++)
{
XmlAttributeCollection spineAttributes = listOfSpineRootNodes[x].Attributes;
string id = spineAttributes[0].Value;
if (spineAttributes != null)
{
XmlNode attrToc = spineAttributes.GetNamedItem("dotoc");
XmlNode attrPageMap = spineAttributes.GetNamedItem("domap");
if (attrToc.Value == "palin" && attrPageMap.Value == "rattmine")
{
if (listOfSpineRootNodes != null)
{
foreach (XmlNode spineNodeRoot in listOfSpineRootNodes)
{
XmlNodeList listOfSpineItemNodes = spineNodeRoot.ChildNodes;
if (listOfSpineItemNodes != null)
{
foreach (XmlNode spineItemNode in listOfSpineItemNodes)
{
if (spineItemNode.NodeType == XmlNodeType.Element
&& spineItemNode.Name == "derif")
{
XmlAttributeCollection spineItemAttributes = spineItemNode.Attributes;
if (spineItemAttributes != null)
{
XmlNode attrIdRef = spineItemAttributes.GetNamedItem("meet");
if (attrIdRef != null)
{
spineListOfSmilFiles.Add(attrIdRef.Value);
}
}
}
}
}
}
}
}
}
```
Can you please tell me where i am going wrong..
Thanks.... | You can do this with the following code using XPath. Since XPath is a language designed specifically to query XML documents, you should consider learning it. Most newbies like to start learning at [W3schools](http://www.w3schools.com/xpath/).
Here is the code:
```
XmlNodeList meetList = opfXmlDoc.SelectNodes("/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet")
if (meetList.Count > 0)
{
foreach (XmlNode meet in meetList)
{
spineListOfSmilFiles.Add(meet.Value);
}
}
```
For your reference, the XPath expression:
```
/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet
```
can be explained as:
a) Find all `rapaine` root level elements that have an attribute `dotoc` with a value of "palin" and also have an attribute `domap` with a value "rattmin".
b) Within those `rapaine` elements, find all `derif` children.
c) Within those `derif` elements, retrieve all `meet` attributes.
Note how much more concise the code becomes. | Can't you just fix this with a simple XPath expression?
All the nested loops with condition is simply asking for trouble. | To fetch the attributes from the NodeList of XmlDocument? | [
"",
"c#",
"xml",
"xmldocument",
""
] |
I have ultraTree (infragistics tree) which is created at design time and it has custom class as "Tag". I have List as member variable. I have two combo box. Based on the combo selection I'll check the List's each items "Tag". If list contains, just i pick that, otherwise i create a new UltraTree and add it to List and i assign to the Tree that is created at design time.
My problem is, what i adding to the collection gets reference and all the item in the collection are overwritten by the last item. UltraTree don't have any clone method.
I don't found any way to clone using this control.
What can be my solution :(
My sample code is
```
// My custom class
SelectedDeviceState treeState = new SelectedDeviceState(
firstDevice, secondDevice);
UltraTree tree = new UltraTree();
// This will clone the root node
// (it will be executed only once -> Root)
foreach (UltraTreeNode nod in tvwNavigation.Nodes)
{
UltraTreeNode tnode = nod.Clone() as UltraTreeNode;
tree.Nodes.Add(tnode);
}
//Adding the custom class as TAG
tree.Tag = treeState;
// Assigned and added
tvwNavigation = tree;
_treeCollection.Add(tree);
``` | You could perform a manual clone by writing a method that creates a new isntance of your type then assigns values to it from the original object.
In terms of a tree structure you would need to write a recursive clone, something like.
```
private ItemType CloneDeep(ItemType node)
{
ItemType clone = new ItemType();
clone.Property1 = node.Property1;
clone.Property2 = node.Property2;
foreach ( ItemType child in node.Nodes)
{
clone.Nodes.add(CloneDeep(child));
}
return clone;
}
```
Maybe look at [extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx). | He wants to know how to get a copy of an object, rather than a copy of a reference to an object. | Need UltraTree Clone Method - Problem with reference | [
"",
"c#",
"infragistics",
"ultratree",
""
] |
I took over a PHP project and I'm trying to get it running on my dev box. I'm a developer and not a sysadmin, so I'm having trouble getting it working.
The previous developer used .h files to include PHP. My current configuration is taking that .h file and including it without executing it. What do I need to look for in my apache config (or is it my php.ini)?
EDIT:
Something clicked when I read one of the comments below. The code is using ASP style tags "`<?`". I've turned the option on in php.ini and according to phpinfo(), it's enabled, but apache is still just including the code as text.
I just checked it and running the code with the full opening PHP tag "`<?php`" fixes the problem. Having said that, I'd still like it to work the other way.
I'm running the code on a Macbook with the latest versions available. PHP 5.2.6, postgresql 8.3 and apache 2.
The code works on the staging server, but I can't figure out what the difference it.
EDIT
Durrr...I didn't have short\_open\_tags enabled in php.ini. | Could the problem be that the .h file you are including just starts into php code without the opening "`<?php`" tag?
From [include](http://www.php.net/manual/en/function.include.php) documentation:
> When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within [valid PHP start and end tags](http://www.php.net/manual/en/language.basic-syntax.phpmode.php). | PHP is an interpreted language, so you can't 'include' a file without executing it. Remember that '.h' is just a file extension, so although the previous coder may have put PHP in a '.h' file, it's still just PHP.
More details on the problems you're running into would be helpful. | Including different types of files in PHP | [
"",
"php",
"include",
"apache2",
""
] |
I'm building a webapp using spring MVC and am curious as to whether there is any clean way to make SEO urls.
For example, instead of <http://mysite.com/articles/articleId> and the such, have:
<http://mysite.com/articles/my-article-subject> | This might be of interest to you:
<http://tuckey.org/urlrewrite/>
If you are familiar with mod\_rewrite on Apache servers, this is a similar concept. | If you're using the new Spring-MVC annotations, you can use the @RequestMapping and @PathVariable annotations:
```
@RequestMapping("/articles/{subject}")
public ModelAndView findArticleBySubject(@PathVariable("subject") String subject)
{
// strip out the '-' character from the subject
// then the usual logic returning a ModelAndView or similar
}
```
I think it is still necessary to strip out the - character. | Java and SEO URLS | [
"",
"java",
"seo",
"spring-mvc",
""
] |
If I were designing a oil refinery, I wouldn't expect that materials from different vendors would not comply with published standards in subtle yet important ways. Pipework, valves and other components from one supplier would come with flanges and wall thicknesses to ANSI standards, as would the same parts from any other supplier. Interoperability and system safety is therefore assured.
Why then are the common databases so choosy about which parts of the standards they adhere to, and why have no 100% standards-compliant systems come to the fore? Are the standards 'broken', lacking in scope or too difficult to design for?
Taking this to conclusion; what is the point of ANSI (or ISO) defining standards for SQL?
Edit: [List of implementation differences between common databases](http://troels.arvin.dk/db/rdbms/) | In the software industry you have some standards that are really standards, i.e., products that don't comply with them just don't work. File specifications fall into that category. But then you also have "standards" that are more like guidelines: they may defined as standards with point-by-point definitions, but routinely implemented only partially or with significant differences. Web development is full of such "standards", like HTML, CSS and "ECMAScript" where different vendors (i.e. web browsers) implement the standards differently.
The variation causes headaches, but the standardization still provides benefits. Imagine if there were no HTML standard at all and each browser used its own markup language. Likewise, imagine if there were no SQL standard and each database vendor used its own completely proprietary querying language. There would be much more vendor lock-in, and developers would have a much harder time working with more than one product.
So, no, ANSI SQL doesn't serve the same purpose as ANSI standards do in other industries. But it does serve a useful purpose nonetheless. | Probably because standards conformance is of a low priority to database system purchasers. They are more interested in:
* compatibility with what they've already got
* performance
* price
* OS support
to name but a few factors.
The same is true of programming languages - very few (if any) compilers support every single feature of the current ANSI C and C++ standards.
As to why bother with standard, well most vendors do eventually bring standard support on board. For example, most vendors support more or less all of SQL89. This allows the vendor to tick a (relatively unimportant) check-box on their spec sheet and also allow people like me who are interested in writing portable code to do so, albeit having to forgo lots of bells and whistles. | Why does no database fully support ANSI or ISO SQL standards? | [
"",
"sql",
"database",
"database-design",
"standards",
"ansi-sql",
""
] |
Accidentally I pressed some keys while writing C# code in VS2008 and space characters replaced by . and enter key replaced by some square boxes, now how do I reset the editor
 | You're probably viewing whitespace, duplicate topic here:
[How do I get rid of the dots!](https://stackoverflow.com/questions/784039/how-do-i-get-rid-of-the-dots) | Press Ctrl+R, Ctrl+W to toggle this setting (without releasing the Ctrl Key). | How to avoid dots in VS2008 | [
"",
"c#",
"visual-studio-2008",
""
] |
I am assuming Java has some built-in way to do this.
**Given a date, how can I determine the date one day prior to that date?**
For example, suppose I am given 3/1/2009. The previous date is 2/28/2009. If I had been given 3/1/2008, the previous date would have been 2/29/2008. | Use the Calendar interface.
```
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DAY_OF_YEAR,-1);
Date oneDayBefore= cal.getTime();
```
Doing "addition" in this way guarantees you get a valid date. This is valid for 1st of the year as well, e.g. if `myDate` is January 1st, 2012, `oneDayBefore` will be December 31st, 2011. | You can also use [Joda-Time](http://joda-time.sourceforge.net), a very good Java library to manipulate dates:
```
DateTime result = dt.minusDays(1);
``` | How to determine the date one day prior to a given date in Java? | [
"",
"java",
"date",
"leap-year",
""
] |
I saw this code:
```
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
```
It seems to be using `!!` as an operator, which I don't recognize. What does it do? | It converts `Object` to `boolean`. If it was falsy (e.g., `0`, `null`, `undefined`, etc.), it would be `false`, otherwise, `true`.
```
!object // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation
```
So `!!` is not an operator; it's just the `!` operator twice.
**It is generally simpler to do:**
```
Boolean(object) // Boolean
```
Real World Example "Test IE version":
```
const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // Returns true or false
```
If you ⇒
```
console.log(navigator.userAgent.match(/MSIE 8.0/));
// Returns either an Array or null
```
But if you ⇒
```
console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// Returns either true or false
``` | It's a horribly obscure way to do a type conversion.
`!` means *NOT*. So `!true` is `false`, and `!false` is `true`. `!0` is `true`, and `!1` is `false`.
So you're converting a value to a `Boolean`, inverting it, and then inverting it again.
```
// Maximum Obscurity:
val.enabled = !!userId;
// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;
// And finally, much easier to understand:
val.enabled = (userId != 0);
// Or just
val.enabled = Boolean(userId);
```
**Note:** the middle two expressions aren't *exactly* equivalent to the first expression when it comes to some edge cases (when `userId` is `[]`, for example) due to the way the `!=` operator works and what values are considered *truthy*. | What is the !! (not not) operator in JavaScript? | [
"",
"javascript",
"operators",
""
] |
A collegue of mine at work gave a presentation on static factory methods (right out of Effective Java), and then gave an example of its use for obtaining static / singleton exceptions.
This set off a red flag for me. Aren't exceptions stateful? Aren't they populated by the JVM for stack trace info? What savings do you really get with this, since exceptions should only occur for, well, exceptional situations?
My knowledge on Exceptions is rather limited, so I come to you with this: will singleton exceptions work, and is there any reason to use them? | Singleton exceptions are supposed to be a performance optimization. The thinking is that you eliminate the cost of populating the stack trace when creating an exception which is usually the most expensive part of exceptions.
If the exception were sufficiently unique and descriptive and the stacktrace was not going to be used, then a singleton could potentially be effective. You could design the app such that a specific exception type with a specific message always means that an exception orgininated from a specific location. Then the stack trace would be irrelevant.
The [April 22, 2003 Tech Tips article](http://java.sun.com/developer/JDCTechTips/2003/tt0422.html#2) describes a scenario where you reuse an exception. In this case, they are trying to game the garbage collector by reducing the number of objects created. If you skipped the `populateStackTrace()` call, you would not have to worry about threading.
Generally, if the performance impact of an exception is causing problems, that is a sign that exceptions are being used for application logic and an error-code should be used instead.
In newer JVM's (1.4+, I believe), this "optimization" can be done automatically by the JVM when running in "-server" mode. This hotspot optimization can be controlled by the option `-XX:+OmitStackTraceInFastThrow`.
*Personally, I would recommend against using the singleton exception [anti-]pattern.* | Although I heartily disagree with the approach, Singleton Exceptions *can* work in a single-threaded environment.
Folks who suggest Singleton Exception patterns tend to be used to the old c-style invoke/error/check-error paradigm, and want to translate that in one of those new-fangled "Object Orientated" languages.
It's possible, but I call it code smell. | Do singleton exceptions work? | [
"",
"java",
"exception",
"static",
"singleton",
""
] |
After connecting to the database, can I get the name of all the columns that were returned in my `SqlDataReader`? | ```
var reader = cmd.ExecuteReader();
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}
```
or
```
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
``` | There is a `GetName` function on the `SqlDataReader` which accepts the column index and returns the name of the column.
Conversely, there is a `GetOrdinal` which takes in a column name and returns the column index. | Can you get the column names from a SqlDataReader? | [
"",
"c#",
"ado.net",
"sqldatareader",
""
] |
Since DateTime.AddDays() takes a `double` parameter, I'm concerned that when you add a days, there might be some rounding errors. For example let's say I have the following loop:
```
DateTime Now = DateTime.Today;
for (int i = 0; i < 365; ++i)
{
Now = Now.AddDays(1);
// do something
}
```
I'm concerned that Now might start drifting away from midnight. I'm always tempted to do something like this which may be a little slower, but relieves my paranoia:
```
for (int i = 0; i < 365; ++i)
{
Now = Now.AddDays(1.01).Date;
// do something
}
``` | As `DateTime` stores the date internaly as 64 bit integer where one tick represents 100 nanoseconds, there is no risk of an error. One day has 864,000,000,000 ticks and `Double` has a precision of at least 15 digits. So every error is vanished when rounding to ticks because `Double` has a higher resolution than one tick if `1.0` equals one day.
This would not be true for `AddYears()`, because `Double` has not enough precision to represent one tick if `1.0` equals one year. But if you look at the `DateTime` class, you see that the design respects that fact - `AddMonths()` and `AddYears()` have both integer and not floating point arguments.
To check this just execute the following code.
```
DateTime now = DateTime.Now;
// Displays 864000000000
Console.WriteLine(now.AddDays(1.0).Ticks - now.Ticks);
``` | In general, I think you are correct to worry about rounding with doubles since not all real numbers are absolutely expressible with a double -- for instance, if you were to add 1/3 of a day three times, you might not end up with exactly one day's advance. However, in this case, 1 is a number that is absolutely expressible and as you are simply multiplying it by another number that is also absolutely expressible in a double (the number of ticks in a day), you should be ok. The second sample is probably overkill.
Example:
```
DateTime now = DateTime.Today;
for (int i = 0; i < 7; ++i )
{
for (int j = 0; j < 7; ++j )
{
now = now.AddDays( 1 / 7.0 );
}
}
Console.WriteLine( DateTime.Today);
Console.WriteLine( now );
```
Results in (on 4/20/2009)
```
4/20/2009 12:00:00 AM
4/26/2009 11:59:59 PM
``` | How Accurate is DateTime.AddDays? | [
"",
"c#",
"datetime",
"rounding",
""
] |
I have a script in T-SQL that goes like this:
```
create table TableName (...)
SET IDENTITY INSERT TableName ON
```
And on second line I get error:
Cannot find the object "TableName" because it does not exist or you do not have permissions.
I execute it from Management Studio 2005. When I put "GO" between these two lines, it's working. But what I would like to acomplish is not to use "GO" because I would like to place this code in my application when it will be finished.
So my question is how to make this work without using "GO" so that I can run it programmatically from my C# application. | Without using GO, programmatically, you would need to make 2 separate database calls. | Run the two scripts one after the other - using two calls from your application.
You should only run the second once the first has successfully run anyway, so you could run the first script and on success run the second script. The table has to have been created before you can use it, which is why you need the GO in management studio. | Using table just after creating it: object does not exist | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"ssms",
""
] |
I have installed Openoffice.org3 on our server and it's running in headless
mode. We use it with jodconverter to convert word and excell files.
It used to work fine, but one day it just stopped working and I really
don't understand why.
When I run /usr/local/bin/java -jar
jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar
on an .xls file to convert it to a .csv file it just gives me:
Exception in thread "main" com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException: conversion failed: could not save output document; OOo errorCode: 3088
If I run jodconverter on a word file, it just gives me an empty
output file, or an other error code. That depends.
Our server have both openoffice 2.4 and 3.0 installed and neither
of the work now. (They both have the same problem) so it's not
directly a problem with the openoffice install.
I even tried to create a new user on the server, and run openoffice as him
but that don't work either.
So does anyone have any idear about what might be wrong, or how I
do get openoffice.org to produce some kind of log file/console outptu,
so I can se whats going on.
I use
/opt/openoffice.org3/program/soffice.bin -headless -nofirststartwizard -accept="socket,host=localhost,port=8100;urp;" & | Well, I ended up deleting both of my old openoffice installs and
installing a new version, and now it's working again. I still don't understand
why it stopped working but sometimes you just have to accept that a
reinstall is a solution. | Sometimes, the soffice is running, but all conversion attempts fail.
My workaround is to run:
`Runtime.getRuntime("killtask /IM soffice.bin /F")`
To shutdown the OS process. And after this,
`Runtime.getRuntime("c:\\path\\start-openoffice-uno.bat")`.
For what it's worth I'm using OO 3.3. | Openoffice3/jodconverter stopped working | [
"",
"java",
"openoffice.org",
"jodconverter",
""
] |
I am building a little HTA for personal use, and would like to be able to drag and drop a file to the interface. Once the file is dropped, I would either automatically run it (assuming it fits some parameters I set, like file extension), or at least fill in the input box on the HTA interface.
I've searched extensively, but can't find a solution. Thoughts? | An HTA obviously cannot be target of a shell drop operation – at least on my system, dropping something on an HTA is impossible.
This would imply you cannot *directly* do what you intend.
A .vbs can however be a drop target. Full paths of the dropped files are available via the `WScript.Arguments.Unnamed` collection.
HTA has access to it's command line arguments via [the commandLine Property](http://msdn.microsoft.com/en-us/library/ms536479(VS.85).aspx). This would mean you could build a small helper VBScript that translates the dropped files into a command line and calls the HTA for you.
Note that you cannot drop endless amounts of files on a .vbs, and command lines are not unlimited either. There will be a length limit in the area of a few kB (I have not tried to find where exactly the limit is, just be prepared to face a limit.) | Tomalak, is incorrect in his statement...there is way to do what you want except that you have to add the DropHandler in the registry for HTA files it's really easy to do and once done you will be able to do exactly what your trying to do. I couldn't find much documentation on it, but here is a link to an HTA that was written a long time ago by a guy named Michel Gallant, that shows you how to it: [https://www.jensign.com/www/wsh/imager/](http://www.jensign.com/JavaScience/www/wsh/imager/index.html)
When the HTA is launched it looks to see if you have the DropHandler already configured. If you don't it gives you the option for it to configure it for you. Once configure all you have to do is close and reopen the HTA and wallah, there you go Drag and Drop support in HTA files. | Javascript - getting path of file dropped into HTA | [
"",
"javascript",
"vbscript",
"drag-and-drop",
"hta",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.