Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
This is more of a design than implementation question and it's going to be long so bear with me. It's best explained with an example:
Let's say I have a business entity called **Product** with a bunch of properties (**name**, **price**, **vendor**, etc...).
It's represented by an interface (**Product**) and implementation (**ProductImpl**, mapped in Hibernate) as well as basic CRUD service interface (**ProductService**) and implementation (**ProductServiceImpl**).
**Product** and **ProductService** are exposed as API, their implementations are not.
I want to add a **List findProducts(QueryCriteria criteria)** method to **ProductService** that would return a list of products satisfying given criteria.
The requirements are:
1. Query by direct **Product** properties (e.g. `product.price gt 50.0`)
2. Query by association (e.g. `product.vendor.name = "Oracle"`)
3. Sort results (e.g. `order by product.vendor.name desc, product.price asc"`)
4. Apply additional filters. Unlike the above 3 items which are all specified by API client, additional filters may be applied by the service based on client's identity (e.g. client invoking this method may be limited to only seeing products manufactured by given vendor). Such filters take precedence over any criteria specified by the client (e.g. if the filter is set to `product.vendor.name = "Microsoft"`, query in (2) above should produce empty result set.
The question, therefore, is what should **QueryCriteria** interface used by such a method look like? I can think of 3 solutions and I don't like either one of them:
* Allow clients to specify HQL (starting with "where" clause) directly.
This is the most straightforward solution, but also the most problematic security-wise. Even assuming that filters (#4 above) are simple enough to be implemented via Hibernate's session filters, HQL still needs to be parsed to - at the very least - ensure that query parameters are specified as parameters and not inlined.
* Use thinly wrapped Hibernate's **DetachedCriteria** in place of **QueryCriteria**.
"Thinly wrapped" because client can not be allowed to create **DetachedCriteria** directly for there would be no way to control what mapped entity it was created for.
Also, this would not as flexible as HQL for some queries are not easily (or at all) expressible via Criteria API. As with HQL approach, filters (#4 above) will be limited to Hibernate session filters.
* Write my own **QueryCriteria** interface / implementation which will form either DetachedCriteria or HQL behind the scenes.
While probably the most flexible solution, this will have to duplicate a lot of code from Criteria API which seems less than ideal.
Any comments on the validity of the above approaches or - fingers crossed - simple elegant solutions that didn't occur to me would be highly appreciated.
P.S. In my specific case, all API clients are internal and "semi-trusted" - that is I'm not as much concerned with someone trying to deliberately break something as with poor programming resulting in Cartesian product of 5 tables :-) However, it'd be nice to come up with a solution that would withstand API exposure to public. | The actual solution I've implemented uses a hybrid approach.
Methods that use well-defined queries (e.g. methods that are used internally by other services, predefined reports, etc.) have signature similar to HibernateTemplate's findBy methods:
```
public List<Entity> findEntities(String queryName, QueryParameters parameters);
```
where `QueryParameters` is a convenience class for specifying named parameters explicitly or taking them from a bean. Sample usage is:
```
List<Product> products = findProducts("latestUpdates",
new QueryParameters()
.add("vendor", "Oracle")
.add("price", "50.0")
);
```
or
```
List<Product> products = findProducts("latestUpdates",
new QueryParameters(product, "vendor", "price"));
```
Access to such methods is limited to "trusted" code; queries used obviously must obviously be defined in Hibernate mappings. Filters are built into query or defined as session filters. The benefits are cleaner code (no Criteria-like stuff spread across half a page) and clearly defined HQL (easier to optimize and deal with cache if necessary).
---
Methods that are exposed to UI or otherwise need to be more dynamic use [Search](http://code.google.com/p/hibernate-generic-dao/wiki/Search) interface from [Hibernate-Generic-DAO](http://code.google.com/p/hibernate-generic-dao/) project. It's somewhat similar to Hibernate's DetachedCriteria but has several advantages:
1. It can be created without being tied to particular entity. It's a big deal for me because entity interface (part of API visible to users) and implementation (POJO mapped in Hibernate) are two different classes and implementation is not available to user at compile time.
2. It's a well thought out open interface; quite unlike DetachedCriteria from which it's nearly impossible to extract anything (yes, I know DC wasn't designed for that; but still)
3. Built-in pagination / results with total count / bunch of other little niceties.
4. No explicit ties to Hibernate (though I personally don't really care about this; I'm not going to suddenly drop Hibernate and go with EclipseLink tomorrow); there are both Hibernate and generic JPA implementations available.
Filters can be added to Search on service side; that's when entity class is specified as well. The only thing's missing is quick-fail on client side if invalid property name is specified and that can be resolved by writing my own ISearch / IMutableSearch implementation but I didn't get to that yet. | **Option One:**
If it's possible to expand your API, I suggest making your API "richer" -- adding more methods such as a few below to make your service sound more natural. It can be tricky to make your API larger without it seeming bloated, but if you follow a similar naming scheme it will seem natural to use.
```
productService.findProductsByName("Widget")
productService.findProductsByName(STARTS_WITH,"Widg")
productService.findProductsByVendorName("Oracle")
productService.findProductsByPrice(OVER,50)
```
Combining the results (applying multiple restrictions) could be left as something for the clients to do after they received the result set by using CollectionUtils and Predicates. You could even build a few common Predicates for the consumers of your API just to be nice. CollectionUtils.select() is fun.
**Option Two:** If it is not possible to expand the API, your third bullet is the one I would go with.
> * Write my own QueryCriteria interface / implementation which will form either DetachedCriteria or HQL behind the scenes...
You could try to apply a DSL style approach to the naming using something akin to the Builder pattern to make things more readable and natural sounding. This gets a little clumsy in Java with all the dots and parens, but maybe something like:
```
Product.Restriction restriction = new Product.Restriction().name("Widget").vendor("Oracle").price(OVER,50) );
productService.findProducts(restriction);
```
**Option Three:** Combine the two approaches, providing a restriction-style criteria along with a richer API. These solutions would be clean in that they hides the Hibernate implementation details from the consumer of your API. (Not that anyone would ever think of switching away from Hibernate.) | Exposing Hibernate criteria via service API | [
"",
"java",
"hibernate",
""
] |
**Update:** When I use the `subprocess.call` instead of `subprocess.Popen`, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from `subprocess.call` to a string or something like that? Thanks!
I'm trying to use `Devenv` to build projects, and it runs just fine when i type it in command prompt like `devenv A.sln /build "Debug|Win32"` - but when I use a python to run it using `Popen(cmd,shell=true)` where `cmd` is the same line as above, it shows nothing. If I remove the `|`, change it to `"Debug"` only, it works....
Does anybody know why this happens? I've tried putting a `\` before `|`, but still nothing happened..
This is the code I am using:
```
from subprocess import Popen, PIPE
cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" '
sys.stdout.flush()
p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE)
lines = []
for line in p.stdout.readlines():
lines.append(line)
out = string.join(lines)
print out
if out.strip():
print out.strip('\n')
sys.stdout.flush()
```
...which doesn't work, however, if I swap `Debug|Win32` with `Debug`, it works perfectly..
Thanks for every comment here | When `shell = False` is used, it will treat the string as a single command, so you need to pass the command/arugments as a list.. Something like:
```
from subprocess import Popen, PIPE
cmd = [
r"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv", # in raw r"blah" string, you don't need to escape backslashes
"solution.sln",
"/build",
"Debug|Win32"
]
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
out = p.stdout.read() # reads full output into string, including line breaks
print out
``` | There is a difference between `devenv.exe` and `devenv.com`, both of which are executable and live in the same directory (sigh). The command lines used in the question and some answers don't say which they want so I'm not sure which will get used.
If you want to call from the command line then you need to ensure you use `devenv.com`, otherwise you're likely to get a GUI popping up. I think this might be the cause of some (but not all) of the confusion. | When I write a python script to run Devenv with configure "Debug|Win32" it does nothing | [
"",
"python",
"subprocess",
""
] |
For example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>title</title>
</head>
<body>
<a href="aaa.asp?id=1"> I want to get this text </a>
<div>
<h1>this is my want!!</h1>
<b>this is my want!!!</b>
</div>
</body>
</html>
```
and the result is:
```
I want to get this text
this is my want!!
this is my want!!!
``` | [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack):
```
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
string s = doc.DocumentNode.SelectSingleNode("//body").InnerText;
``` | Use this function...
```
public string Strip(string text)
{
return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
}
``` | How to clean HTML tags using C# | [
"",
"c#",
"html",
""
] |
We use Enterprise Library 3.0 to access Oracle DB (microsoft oracle client).
What happens when I do not dispose a DbCommand instance after a stored procedure or function is called? Does .NET automatically garbage collect them?
Note that we do make sure that the transaction/connection gets closed and disposed properly. | This is a duplicate, but I don't have time to find the original.
If it implements IDisposable, and if you created it, then you need to call Dispose on it. That's why the developer of the class made it implement IDisposable.
The garbage collector does not call Dispose on all IDisposable-implementing objects. | Reflector doesn't indicate that `OracleCommand` specifically overrides Dispose (from `System.ComponentModel.Component`'s implementation, anyway), so chances are it won't hurt your application much if you don't call it.
The important thing, though, is that `OracleCommand` specifically implements `IDbCommand`, which specifically implements `IDisposable`. If you ever replaced your `OracleCommand` with another `IDbCommand`, then you would most likely want to use `Dispose()`. And while `SqlCommand` doesn't explicitly override `Dispose()`, Odbc and OleDb certainly do.
In short, since it's `IDisposable`, you should dispose it, just to be on the safe side. | Is is necessary to dispose DbCommand after use? | [
"",
"c#",
".net",
"oracle",
""
] |
I would like to create a stored procedure with parameters that indicate which fields should be selected.
E.g. I would like to pass two parameters "selectField1" and "selectField2" each as bools.
Then I want something like
```
SELECT
if (selectField1 = true) Field1 ELSE do not select Field1
if (selectField2 = true) Field2 ELSE do not select Field2
FROM Table
```
Thanks
Karl | Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing.
```
IF (selectField1 = true AND selectField2 = true)
BEGIN
SELECT Field1, Field2
FROM Table
END
ELSE IF (selectField1 = true)
BEGIN
SELECT Field1
FROM Table
END
ELSE IF (selectField2 = true)
BEGIN
SELECT Field2
FROM Table
END
```
Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.
```
DECLARE @sql varchar(MAX)
SET @sql = 'SELECT '
IF (selectField1 = true)
BEGIN
SET @sql = @sql + 'Field1, '
END
IF (selectField2 = true)
BEGIN
SET @sql = @sql + 'Field2, '
END
...
-- DROP ', '
@sql = SUBSTRING(@sql, 1, LEN(@sql)-2)
SET @sql = @sql + ' FROM Table'
EXEC(@sql)
``` | In `SQL`, you do it this way:
```
SELECT CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM Table
```
Relational model does not imply dynamic field count.
Instead, if you are not interested in a field value, you just select a `NULL` instead and parse it on the client. | SQL conditional SELECT | [
"",
"sql",
"select",
"conditional-statements",
""
] |
Does anyone know how to construct a format string in .NET so that the resulting string contains a colon?
In detail, I have a value, say 200, that I need to format as a ratio, i.e. "1:200". So I'm constructing a format string like this "1:{0:N0}" which works fine. The problem is I want zero to display as "0", not "1:0", so my format string should be something like "{0:1:N0;;N0}", but of course this doesn't work.
Any ideas? Thanks! | ```
using System;
namespace ConsoleApplication67
{
class Program
{
static void Main()
{
WriteRatio(4);
WriteRatio(0);
WriteRatio(-200);
Console.ReadLine();
}
private static void WriteRatio(int i)
{
Console.WriteLine(string.Format(@"{0:1\:0;-1\:0;\0}", i));
}
}
}
```
gives
```
1:4
0
-1:200
```
The `;` separator in format strings means 'do positive numbers like this; negative numbers like this; and zero like this'. The `\` escapes the colon. The third `\` is not *strictly* necessary as a literal zero is the same as the standard numeric format output for zero :) | You can use AakashM's solution. If you want something slightly more readable, you can create your own provider:
```
internal class RatioFormatProvider : IFormatProvider, ICustomFormatter
{
public static readonly RatioFormatProvider Instance = new RatioFormatProvider();
private RatioFormatProvider()
{
}
#region IFormatProvider Members
public object GetFormat(Type formatType)
{
if(formatType == typeof(ICustomFormatter))
{
return this;
}
return null;
}
#endregion
#region ICustomFormatter Members
public string Format(string format, object arg, IFormatProvider formatProvider)
{
string result = arg.ToString();
switch(format.ToUpperInvariant())
{
case "RATIO":
return (result == "0") ? result : "1:" + result;
default:
return result;
}
}
#endregion
}
```
With this provider, you can create very readable format strings:
```
int ratio1 = 0;
int ratio2 = 200;
string result = String.Format(RatioFormatProvider.Instance, "The first value is: {0:ratio} and the second is {1:ratio}", ratio1, ratio2);
```
If you control the class being formatted (rather than a primitive one like Int32), you can make this look nicer. See [this article](http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx) for more details. | Emitting a colon via format string in .NET | [
"",
"c#",
".net",
"string",
""
] |
I have a function which accepts a string parameter such as: "var1=val1 var2=val2 var3='a list of vals'";
I need to parse this string and pick out the var/val combination's. That is easy enough until introducing something like var3='a list of vals'. Obviously I can't explode the string into an array using a white space delimiter which has me kind of stuck. I want to create an array from this string with the var/val pairs properly assigned, how can I do this in a case where I have something like var3? | if the format of the string *is* set in stone, you could do something like:
```
$string = "var1=val1 var2=val2 var3='this is a test'";
$vars = array();
$i = 0;
while ($i < strlen($string)) {
$eqIndex = strpos($string, "=", $i);
$varName = substr($string, $i, $eqIndex - $i);
$i = $eqIndex + 1;
if ($string[$i] == "'")
{
$varEndIndex = strpos($string, "'", ++$i);
}
else
{
$varEndIndex = strpos($string, " ", $i);
if ($varEndIndex === FALSE) $varEndIndex = strlen($string);
}
$varValue = substr($string, $i, $varEndIndex - $i);
$vars[$varName] = $varValue;
$i = $varEndIndex + 1;
}
print_r($vars);
```
EDIT:
More robust function that handles escaped chars in the quoted values:
```
function getVarNameEnd($string, $offset) {
$len = strlen($string);
$i = $offset;
while ($i < $len) {
if ($string[$i] == "=")
return $i;
$i++;
}
return $len;
}
function getValueEnd($string, $offset) {
$len = strlen($string);
$i = $offset;
if ($string[$i] == "'") {
$quotedValue = true;
$i++;
}
while ($i < $len) {
if ($string[$i] == "\\" && $quotedValue)
$i++;
else if ($string[$i] == "'" && $quotedValue)
return $i + 1;
else if ($string[$i] == " " && !$quotedValue)
return $i;
$i++;
}
return $len;
}
function getVars($string) {
$i = 0;
$len = strlen($string);
$vars = array();
while ($i < $len) {
$varEndIndex = getVarNameEnd($string, $i);
$name = substr($string, $i, $varEndIndex - $i);
$i = $varEndIndex + 1;
$valEndIndex = getValueEnd($string, $i);
$value = substr($string, $i, $valEndIndex - $i);
$i = $valEndIndex + 1;
$vars[$name] = $value;
}
return $vars;
}
$v = getVars("var1=var1 var2='this is a test' var3='this has an escaped \' in it' var4=lastval");
print_r($v);
``` | This is traditionally why query strings use & as the delimiter and not spaces.
If you can do that, then just use [parse\_str](http://www.php.net/manual/en/function.parse-str.php) to get the data out.
If not, you'll need to do regex:
```
preg_match_all('/(\S*)=('.*?'|\S*)/g', $your_string, $matches);
print_r($matches);
``` | Parsing a string within a string? | [
"",
"php",
"parsing",
"variables",
"string",
""
] |
This seems like it should be something I already know. We need to run a bunch of sql updates in a transaction, and rollback if one of them fails. We also want to print a status message since we'll be running a large number of these. This would be simple if I were doing it in a general purpose programming language. But I am trying to find a solution a team member can use that is just SQL. She has done this in MS SQL Server in the past with the pattern below. Is there an equivalently simple pattern for Oracle?
```
DECLARE @ErrorVar INT;
BEGIN TRANSACTION;
UPDATE MyTable1 SET MyColumn1 = 'JSMITH' where MyColumn1 = 'JOHN';
SET @ErrorVar = @@ERROR;
UPDATE MyTable2 SET MyColumn2 = 'JSMITH' where MyColumn2 = 'JOHN';
SET @ErrorVar = @ErrorVar + @@ERROR;
UPDATE MyTable SET LoginID = 'JSMITH' where LoginID = 'JOHN';
SET @ErrorVar = @ErrorVar + @@ERROR;
IF @ErrorVar <> 0
BEGIN
ROLLBACK TRANSACTION;
PRINT 'We had a problem with JSMITH and rolled back *****';
END;
ELSE
BEGIN
COMMIT TRANSACTION;
PRINT 'JSMITH Updated ok';
END;
GO
``` | In SQLPlus, use the WHENEVER command to control behavior when an error occurs.
WHENEVER SQLERROR EXIT FAILURE ROLLBACK is fairly standard in our scripts.
Type HELP WHENEVER at the SQLPlus prompt for more info. | Because my answer to akf's comment is too long for a comment, I post it as a separate answer.
Here is why it doesn't achieve anything extra/useful.
Suppose we have the three tables mentioned by Peter:
```
SQL> create table mytable1 (mycolumn1) as select cast('JOHN' as varchar2(6)) from dual
2 /
Tabel is aangemaakt.
SQL> create table mytable2 (mycolumn2) as select cast('JOHN' as varchar2(6)) from dual
2 /
Tabel is aangemaakt.
SQL> create table mytable (loginid) as select cast('JOHN' as varchar2(6)) from dual
2 /
Tabel is aangemaakt.
```
And add a check constraint to make the third update statement fail:
```
SQL> alter table mytable add constraint no_jsmith_ck1 check (loginid <> 'JSMITH')
2 /
Tabel is gewijzigd.
```
The PL/SQL block can be as simple as this, and it fails:
```
SQL> begin
2 update mytable1
3 set mycolumn1 = 'JSMITH'
4 where mycolumn1 = 'JOHN'
5 ;
6 update mytable2
7 set mycolumn2 = 'JSMITH'
8 where mycolumn2 = 'JOHN'
9 ;
10 update mytable
11 set loginid = 'JSMITH'
12 where loginid = 'JOHN'
13 ;
14 commit
15 ;
16 end;
17 /
begin
*
FOUT in regel 1:
.ORA-02290: check constraint (RWK.NO_JSMITH_CK1) violated
ORA-06512: at line 10
```
And to show that everything was rollbacked, without issuing a rollback:
```
SQL> select * from mytable1
2 /
MYCOLU
------
JOHN
1 rij is geselecteerd.
SQL> select * from mytable2
2 /
MYCOLU
------
JOHN
1 rij is geselecteerd.
SQL> select * from mytable
2 /
LOGINI
------
JOHN
1 rij is geselecteerd.
```
So no exception handler is necessary here. Your proposed exception handler does this:
```
SQL> begin
2 update mytable1
3 set mycolumn1 = 'JSMITH'
4 where mycolumn1 = 'JOHN'
5 ;
6 update mytable2
7 set mycolumn2 = 'JSMITH'
8 where mycolumn2 = 'JOHN'
9 ;
10 update mytable
11 set loginid = 'JSMITH'
12 where loginid = 'JOHN'
13 ;
14 commit
15 ;
16 EXCEPTION
17 WHEN OTHERS THEN
18 ROLLBACK; --// Oracle will do this for you, but it doesnt hurt to be clear
19 DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_backtrace);
20 raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
21 END;
22 /
ORA-06512: at line 10
begin
*
FOUT in regel 1:
.ORA-20001: An error was encountered - -2290 -ERROR- ORA-02290: check constraint (RWK.NO_JSMITH_CK1) violated
ORA-06512: at line 20
```
Although it's not wrong, I see nothing of added value here.
```
SQL> select * from mytable1
2 /
MYCOLU
------
JOHN
1 rij is geselecteerd.
SQL> select * from mytable2
2 /
MYCOLU
------
JOHN
1 rij is geselecteerd.
SQL> select * from mytable
2 /
LOGINI
------
JOHN
1 rij is geselecteerd.
```
And why advice to add code that does nothing?
Regards,
Rob. | How to progromatically know to rollback a transaction (can do it in SQLServer, but need oracle solution) | [
"",
"sql",
"sql-server",
"oracle",
"transactions",
""
] |
I need to use system-specific functions, e.g. `ftello()` (defined in `stdio.h` as per POSIX standard).
I also need to use standard C++ features, e.g. `std::sprintf()` (defined in `cstdio`, as per ISO C++ standard).
AFAIK, including only `<cstdio>` doesn't guarantee defining non-standard-C++ stuff, so I guess I have to include both.
I've read a long time ago that (for example) with gcc there may be problems with the include file order.
So, what is the correct order for including both `<cstdio>` and `<stdio.h>`?
I'm looking for a solution which is as cross-platform as possible (at least for gcc, suncc, intel C++/linux and mingw). | OK, after some more reasearch I finally came to a conclusion that including the C++ header first, C header later is the correct thing to do.
For example, consider the following C++0x header (from gcc):
/usr/include/c++/4.3/tr1\_impl/cstdint:
```
// ...
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include_next <stdint.h>
// ...
```
What it does is that it defines two C99 macros, and only then includes the C99 stdint.h header. The reason is that in C99, some of the features of stdint.h are optional, and only available if those macros are defined. However, in C++0x, all stdint.h features are mandatory.
Now, if I included the C99 stdint.h first, cstdint later, I wouldn't get the mandatory C++0x features because of the header guards in stdint.h.
One could argue that this is the compiler vendor's fault, but that would be incorrect. stdint.h is a system-bundled header (from glibc in this case), which is a C99 header and doesn't know anything about C++0x (it can be an old system, after all) or gcc. The compiler can't really fix all the system headers (in this case to always enable those features in C++ mode), yet it has to provide C++0x support on these systems, so the vendor uses this workaround instead. | I don't know of any true rule, however generally speaking I include the lower level system libraries before the higher level libraries.
So in this case stdio.h is a C header and (in my imagination) is closer to the machine, and `<cstdio>` is higher level, C++ Standard Library which I imagine to be more abstracted.
I tend to include `stdio.h` before `cstdio` myself, but I don't know of an exact reasoning to support that rationale. | Correct order for including both <cstdio> and <stdio.h>? | [
"",
"c++",
"gcc",
"include",
"stdio",
""
] |
I have two tables, one for routes and one for airports.
Routes contains just over 9000 rows and I have indexed every column.
Airports only 2000 rows and I have also indexed every column.
When I run this query it can take up to 35 seconds to return 300 rows:
```
SELECT routes.* , a1.name as origin_name, a2.name as destination_name FROM routes
LEFT JOIN airports a1 ON a1.IATA = routes.origin
LEFT JOIN airports a2 ON a2.IATA = routes.destination
WHERE routes_build.carrier = "Carrier Name"
```
Running it with "DESCRIBE" I get the followinf info, but I'm not 100% sure on what it's telling me.
```
id | Select Type | Table | Type | possible_keys | Key | Key_len | ref | rows | Extra
--------------------------------------------------------------------------------------------------------------------------------------
1 | SIMPLE | routes_build | ref | carrier,carrier_2 | carrier | 678 | const | 26 | Using where
--------------------------------------------------------------------------------------------------------------------------------------
1 | SIMPLE | a1 | ALL | NULL | NULL | NULL | NULL | 5389 |
--------------------------------------------------------------------------------------------------------------------------------------
1 | SIMPLE | a2 | ALL | NULL | NULL | NULL | NULL | 5389 |
--------------------------------------------------------------------------------------------------------------------------------------
```
The only alternative I can think of is to run two separate queries and join them up with PHP although, I can't believe something like this being something that could kill a mysql server. So as usual, I suspect I'm doing something stupid. SQL is my number 1 weakness. | Personally, I would start by removing the left joins and replacing them with inner joins as each route must have a start and end point. | ```
SELECT routes.*, a1.name as origin_name, a2.name as destination_name
FROM routes_build
LEFT JOIN
airports a1
ON a1.IATA = routes_build.origin
LEFT JOIN
airports a2
ON a2.IATA = routes_build.destination
WHERE routes_build.carrier = "Carrier Name"
```
From your `EXPLAIN PLAN` I can see that you don't have an index on `airports.IATA`.
You should create it for the query to work fast.
Name also suggests that it should be a `UNIQUE` index, since `IATA` codes are unique.
**Update:**
Please post your table definition. Issue this query to show it:
```
SHOW CREATE TABLE airports
```
Also I should note that your `FULLTEXT` index on `IATA` is useless unless you have set `ft_max_word_len` is `MySQL` configuration to `3` or less.
By default, it's `4`.
`IATA` codes are `3` characters long, and `MySQL` doesn't search for such short words using `FULLTEXT` with default settings. | How can I optimize this query...? | [
"",
"sql",
"mysql",
"query-optimization",
""
] |
I have a wpf application (C#) that needs to copy a file to a server that is not part of a domain. FTP cannot be used. I looked into using LogonUser() within advapi32.dll but could impersonate the local user to the machine successfully. Are there any other options? | I was able to impersonate the local user by setting logonProvider to 0 and logonType to 9 using advapi32.dll. | one option is there to upload file through WCF Service..in that case it is not required that it should be in same domain.
Here article's title is large file upload / download but it is meant only for small files upto
[10 MB - 40 MB].
[WCF File Upload Download](http://www.codeproject.com/KB/WCF/WCFDownloadUploadService.aspx)
[Second Option](http://kjellsj.blogspot.com/2007/02/wcf-streaming-upload-files-over-http.html) | Copying file to a server that is not part of a domain | [
"",
"c#",
".net",
""
] |
Upon starting my webapp within Tomcat 6.0.18, I bootstrap Spring with only what is necessary to *initialize* the system -- namely, for now, database migrations. I do not want any part of the system to load until the migrations have successfully completed. This prevents the other beans from having to wait on the migrations to complete before operating, or even instantiating.
I have a startup-appcontext.xml configured with a dbMigrationDAO, a startupManager which is a [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html), and lastly, a FullSystemLauch bean. I pass a list of configuration locations to the FullSystemLaunch bean via setter injection. The FullSystemLaunch bean implements [ServletContextAware](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/ServletContextAware.html), gets a reference to the current [WebApplicationContext](http://static.springframework.org/spring/docs/2.5.6/api/org/springframework/web/context/WebApplicationContext.html) and thus I can have a [ConfigurableListableBeanFactory](http://static.springframework.org/spring/docs/2.5.6/api/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.html). Unfortunately, this bean factory isConfigurationFrozen() returns true, so by calling beanFactory.setConfigLocations(configLocations) has no effect.
Can I accomplish this or is Spring preventing me from doing so because it's a bit out of the ordinary? It seems reasonable if understood, but also a bit dangerous. And yes, I'm willing to blow away the current context b/c the currently loaded Singletons are not needed once initialization is complete.
Thank you for the help. | You could use the existing context as parent context for the other contexts, although I doubt that you could replace the existing WebApplicationContext.
If you use EAR - WAR packaging, you get this out-of-the-box (sort of) by loading an application context from the EAR and then adding one in the WAR.
Not sure whether this is applicable in your situation. | My opinion would be to allow Spring to initialise your beans is it sees fit - in the order of their declared dependencies.
If you need database migrations there are a couple of patterns to have them run first:
* if you're using Hibernate/JPA make your sessionFactory/persistenceManager *depend-on* the migration beans;
* if you're using plain JDBC create a wrapper DataSource and in its *init-method* invoke the migrations ( [code sample](https://stackoverflow.com/questions/959547/short-way-of-making-many-beans-depend-on-one-bean/980913#980913))
The advantage is clear: simplicity. | Can I dynamically load additional Spring configuration files into an existing WebApplicationContext? | [
"",
"java",
"spring",
"tomcat",
"migration",
"servletconfig",
""
] |
I am using the following regex to get the `src` value of the first `img` tag in an HTML document.
```
string match = "src=(?:\"|\')?(?<imgSrc>[^>]*[^/].(?:jpg|png))(?:\"|\')?"
```
Now it captures total `src` attribute that I dont need. I just need the url inside the `src` attribute. How to do it? | **Parse your HTML with something else.** [HTML is not regular](http://welbog.homeip.net/glue/53/XML-is-not-regular) and thus regular expressions aren't at all suited to parsing it.
Use an HTML parser, or an XML parser if the HTML is strict. It's a lot easier to get the src attribute's value using XPath:
```
//img/@src
```
XML parsing is built into the [`System.Xml` namespace](http://msdn.microsoft.com/en-us/library/system.xml(VS.71).aspx). It's incredibly powerful. [HTML parsing](http://www.developer.com/net/csharp/article.php/2230091) is a bit more difficult if the HTML isn't strict, but there are lots of libraries around that will do it for you. | see [When not to use Regex in C# (or Java, C++ etc)](https://stackoverflow.com/questions/968919/when-not-to-use-regex-in-c-or-java-c-etc) and [Looking for C# HTML parser](https://stackoverflow.com/questions/100358/looking-for-c-html-parser)
PS, how can I put a link to a StackOverflow question in a comment? | Regex to get src value from an img tag | [
"",
"c#",
"html",
"regex",
""
] |
Can someone please explain to me the difference between the AppSettings and ApplicationSettings sections in the App.Config file. Why are there two different sections that apparently do the same thing?? | I believe that the `<appsettings/>` collection in your app.config/web.config allows you to store settings in key-value pairs, and is accessed through the System.Configuration API, as follows:
`string setting = System.Configuration.ConfigurationManager.AppSettings["settingName"];`
Settings can only be stored and retrieved as string values.
They can also be accessed through System.Configuration.ConfigurationSettings, but this way has been deprecated.
The `<ApplicationSettings/>` collection in your config file stores your settings in a strongly typed manner, and also allows you to access these settings in a strongly typed way. VS automatically generates wrapper classes for you, in the **settings.settings** file in the **Properties** folder of your project. To add a settings file to your project, right click on your project, and click **Properties**, then open the **Settings** tab. Then click the link to add a new settings file. VS will automatically generate one for you. It's that easy.
You usually access your settings as follows:
`MyProjectName.Properties.Settings.Default.SettingName`
Notice the difference in how the two collections are accessed.
The second (non-deprecated) way of storing settings is the better way to do it, and provides lots of flexibility and power. It takes some learning though - but it is worth the effort. | <http://kevinskorner.net/blog/post/2008/03/27/applicationSettings-vs-appSettings.aspx>
> Application settings give us more
> control and most important,
> intelliscence. | What is the difference between the ApplicationSettings section and the AppSettings section? | [
"",
"c#",
"settings",
""
] |
I would like to create a custom document library where I use the standard UI but implement a different persistence layer. Basically fetch and display documents from a different source system. This way I can use my existing object model but leverage the great office integration within SharePoint.
I found a decent article [here](http://code.msdn.microsoft.com/spextcontent) but they are cheating, they have coded a completely new UI for the external persistence.
I have looked at the SPList and SPDocumentLibrary objects but I can't override the necessary methods.
I have looked at the event framework and it is closer but it lacks important events such as 'GetFile' or 'PopulateList'.
Any thoughts? | This isn't a perfect (or probably even a "good") fit for what you're trying to do, but I mention it primarily for awareness and to possibly give you some additional ideas (and warnings).
SharePoint's storage architecture leverages two different back-end stores: one for metadata (always SharePoint's SQL databases), and another for BLOB storage (also SQL by default). In its current form, though, SharePoint allows you to "wire-in" your own BLOB storage provider via a type that implements the ISPExternalBinaryProvider interface. Wiring in a type that implements this interface allows you to continue storing metadata in SQL while storing documents and other BLOB item types in a different store of your choice.
This probably sounds somewhat promising, but there are a couple of serious considerations:
1. Wiring-in your own ISPExternalBinaryProvider has a farm-wide impact. It's all or nothing, so once the provider is wired in, all sites and libaries will use the new provider.
2. You'll need to dive into unmanaged code, as the ISPExternalBinaryProvider is doing to require you to work with some IDL.
You can read more here: <http://msdn.microsoft.com/en-us/library/bb802976.aspx>
My take is that the external BLOB storage (EBS) system is something of a "prototype" at this point -- not ready for prime-time. If nothing else, though, it gives you something to think about. SharePoint Server 2010 will hopefully do more with it and make it more attractive and easy to implement.
For what it's worth! | If you really wanna roll your own external persistance, try taking a look at this brand new, extensive article from june on TechNet:
<http://technet.microsoft.com/en-us/magazine/2009.06.insidesharepoint.aspx>
Now, hand me the bounty. ;) | Create a document library with external persistence | [
"",
"c#",
"visual-studio-2008",
"sharepoint",
"persistence",
"sharepointdocumentlibrary",
""
] |
Does anyone know a PHP RegEx to allow only relative paths, not absolute?
For example, I have an AJAX function that submits this value to my PHP script "some-directory/another-directory/some-file.php".
My PHP script then includes that file.... include($some-php-document);
I don't want a hacker to be able to use my AJAX function to submit something like: "<http://www.malicious-website.com/malicious-script.php>"
In my PHP Document I would like to do something like:
```
<php>
$some-php-document = $_POST["some_value_submitted_via_ajax"];
//if $some-php-document is a URL (not a relative path to a file),
//then $some_php_document = null
//how can I use a php regex to accomplish the above?
</php>
```
How can I do this?
Or, let me know if there are more secure solutions. | I would use the [parse\_url()](http://www.php.net/manual/en/function.parse-url.php) function rather than a regexp, something like:
```
<?php
$some_php_document = $_POST["some_value_submitted_via_ajax"];
$parsed_doc = parse_url($some_php_document);
//if $some-php-document is a URL (not a relative path to a file),
//then $some_php_document = null
if (isset($parsed_doc['scheme']) || isset($parsed_doc['host'])) {
$some_php_document = null;
}
?>
```
The file path will be in $parsed\_doc['path']. It should be checked before being used, so an attacker can't say, request /etc/passwd or some similarly sensitive file. | Don't allow the upload of file names to specify an include. Instead do this:
```
$valid_files = array(
'file1' => 'file1.inc',
'file2' => 'john.inc',
'fred' => 'bob.inc',
);
$requested_include = trim(strtolower($_POST["some_value_submitted_via_ajax"])));
if (!array_key_exists($requested_include, $valid_files)) {
$requested_include = "file1";
}
include WEB_ROOT_PATH . 'templates/whatever/' . $valid_files[$requested_include];
```
Validate all input, no need for a RegEx - it's hard to get right and you're better off with a tighter security solution as above. | Beginner RegEx Question - PHP RegEx to allow only relative paths (not URL's) | [
"",
"php",
"ajax",
"regex",
"security",
""
] |
Is there any addon by which I can disable all catch blocks temporarily. I'm maintaining an application and I need to find out where exactly it is throwing exception. Someone has done error handling is done is all layers to make my job tough :( | I don't know a way to disable catch blocks but what you are trying to achieve can be done easily a VS option in exceptions dialog:
```
Debug -> Exceptions -> CLR Exceptions -> Check the "Thrown" checkbox.
```
This way, VS will break immediately when an exception is being thrown before running any catch block. | You don't need to disable all catch blocks to identify where an exception is first thrown from - in the debugger. If you open the Exceptions dialog in VS, you can configure the debugger to catch an exception either when it's unhandled (the default), or when it is first thrown. This is the simplest and least intrusive way to do it.
The Exceptions dialog is accessible from the Debug menu. | VS 2008 Addon to temporarily disable/remove all catch block | [
"",
"c#",
".net",
"visual-studio",
"debugging",
"exception",
""
] |
I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?
Here's the exact error:
```
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
b = urllib.urlopen('http://www.google.com')
File "C:\Python26\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "C:\Python26\lib\urllib.py", line 203, in open
return getattr(self, name)(url)
File "C:\Python26\lib\urllib.py", line 342, in open_http
h.endheaders()
File "C:\Python26\lib\httplib.py", line 868, in endheaders
self._send_output()
File "C:\Python26\lib\httplib.py", line 740, in _send_output
self.send(msg)
File "C:\Python26\lib\httplib.py", line 699, in send
self.connect()
File "C:\Python26\lib\httplib.py", line 683, in connect
self.timeout)
File "C:\Python26\lib\socket.py", line 498, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno 11001] getaddrinfo failed
```
More info: I also get this error with urllib2.urlopen | You probably need to fill in proxy information.
```
import urllib2
proxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'})
proxy_auth_handler = urllib2.HTTPBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.stackoverflow.com')
``` | Check you are using the correct proxy.
You can get the proxy information by using urllib.getproxies (note: getproxies does *not* work with dynamic proxy configuration, like when using PAC).
**Update** As per information about empty proxy list, I would suggest using an urlopener, with the proxy name and information.
Some good information about how use proxies urlopeners:
1. [Urllib manual](http://docs.python.org/library/urllib.html#url-opener-objects)
2. [Michael Foord's introduction to urllib](http://www.voidspace.org.uk/python/articles/urllib2.shtml#proxies) | urllib.urlopen isn't working. Is there a workaround? | [
"",
"python",
"url",
""
] |
What is the difference, if there is one, between a destructor and a Finalize method in a class?
I recently discovered that Visual Studio 2008 considers a destructor synonymous with a Finalize method, meaning that Visual Studio won't let you simultaneously define both methods in a class.
For example, the following code fragment:
```
class TestFinalize
{
~TestFinalize()
{
Finalize();
}
public bool Finalize()
{
return true;
}
}
```
Gives the following error on the call to Finalize in the destructor:
> The call is ambiguous between the following methods or properties:
> 'TestFinalize.~TestFinalize()' and 'TestFinalize.Finalize()'
And if the call to Finalize is commented out, it gives the following error:
> Type 'ManagementConcepts.Service.TestFinalize' already defines a member called
> 'Finalize' with the same parameter types | A destructor in C# overrides `System.Object.Finalize` method. You **have to** use destructor syntax to do so. Manually overriding `Finalize` will give you an error message.
Basically what you are trying to do with your `Finalize` method declaration is [**hiding**](http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx) the method of the base class. It will cause the compiler to issue a warning which can be silenced using the `new` modifier (if it was going to work). The important thing to note here is that you **can't** both `override` and declare a `new` member with identical name at the same time so having both a destructor and a `Finalize` method will result in an error (but you **can**, although not recommended, declare a `public new void Finalize()` method if you're not declaring a destructor). | Wikipedia has some good discussion on the difference between a finalizer and a [destructor](http://en.wikipedia.org/wiki/Destructor_%28computer_science%29) in the [finalizer](http://en.wikipedia.org/wiki/Finalizer) article.
C# really doesn't have a "true" destructor. The syntax resembles a C++ destructor, but it really is a finalizer. You wrote it correctly in the first part of your example:
```
~ClassName() { }
```
The above is syntactic sugar for a `Finalize` function. It ensures that the finalizers in the base are guaranteed to run, but is otherwise identical to overriding the `Finalize` function. This means that when you write the destructor syntax, you're really writing the finalizer.
[According to Microsoft](http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx), the finalizer refers to the function that the garbage collector calls when it collects (`Finalize`), while the destructor is your bit of code that executes as a result (the syntactic sugar that becomes `Finalize`). They are so close to being the same thing that Microsoft should have never made the distinction.
Microsoft's use of the C++'s "destructor" term is misleading, because in C++ it is executed on the same thread as soon as the object is deleted or popped off the stack, while in C# it is executed on a separate thread at another time. | In C# what is the difference between a destructor and a Finalize method in a class? | [
"",
"c#",
"destructor",
"finalize",
""
] |
There are many ways of converting a String to an Integer object. Which is the most efficient among the below:
```
Integer.valueOf()
Integer.parseInt()
org.apache.commons.beanutils.converters.IntegerConverter
```
My usecase needs to create wrapper Integer objects...meaning no primitive int...and the converted data is used for read-only. | Don't even waste time thinking about it. Just pick one that seems to fit with the rest of the code (do other conversions use the .parse\_\_() or .valueOf() method? use that to be consistent).
Trying to decide which is "best" detracts your focus from solving the business problem or implementing the feature.
Don't bog yourself down with trivial details. :-)
On a side note, if your "use case" is specifying java object data types for your code - your BA needs to step back out of your domain. BA's need to define "the business problem", and how the user would like to interact with the application when addressing the problem.
Developers determine how best to build that feature into the application with code - including the proper data types / objects to handle the data. | If efficiency is your concern, then creating an Integer object is much more expensive than parsing it. If you have to create an Integer object, I wouldn't worry too much about how it is parsed.
Note: Java 6u14 allows you to increase the size of your Integer pool with a command line option -Djava.lang.Integer.IntegerCache.high=1024 for example.
Note 2: If you are reading raw data e.g. bytes from a file or network, the conversion of these bytes to a String is relatively expensive as well. If you are going to write a custom parser I suggest bypassing the step of conversing to a string and parse the raw source data.
Note 3: If you are creating an Integer so you can put it in a collection, you can avoid this by using GNU Trove (trove4j) which allows you to store primitives in collections, allowing you to drop the Integer creation as well.
Ideally, for best performance you want to avoid creating any objects at all. | Most efficient way of converting String to Integer in java | [
"",
"java",
"optimization",
"performance",
""
] |
I need to check whether a given date is in the preceding month for a monthly query. I can get
```
CURRENT DATE - 1 MONTH
```
to compare the selected date with, but I can't assume the current date will be the first day of each month exactly. Is there a built in way to get the first day of the month without extracting the year and month and gluing it back together? | ## Available in all Db2 versions
First day of this year:
```
date('0001-01-01') + year(current date) years - 1 year
```
---
First day of this month:
```
date('0001-01-01') + year(current date) years - 1 year + month(current date) months - 1 month
```
---
First day of last month:
```
date('0001-01-01') + year(current date) years - 1 year + month(current date) months - 2 months
```
---
## Available in Db2 11.1 and newer
If you don't need to maintain SQL compatibility with Db2 LUW v10.5 and older, you can also use these convenient Db2 LUW v11.1 scalar functions: `THIS_WEEK()` `THIS_MONTH()` `THIS_QUARTER()` and `THIS_YEAR()`.
First day of this month:
```
THIS_MONTH(CURRENT DATE)
```
---
First day of last month:
```
THIS_MONTH(CURRENT DATE) - 1 MONTH
```
---
Last day of last month:
```
THIS_MONTH(CURRENT DATE) - 1 DAY
```
## A note about `ROUND_TIMESTAMP()`
`ROUND_TIMESTAMP()` is available in Db2 9.7 and newer, but given that it by design rounds some input values down and others up, `ROUND_TIMESTAMP()` is not an ideal way to reliably return the first day of the current month or previous month.
As pointed out in the original question, `CURRENT DATE - 1 MONTH` will only return the first day of the previous month (the desired result) when run on the first day of the month, but `ROUND_TIMESTAMP(CURRENT DATE - 1 MONTH, 'W')` only extends that behavior for three more days, until the fifth, when it will start returning the eighth day of the previous month. Similarly, `ROUND_TIMESTAMP(CURRENT DATE - 1 MONTH, 'MM')` will only return the first day of the previous month up to and including the 15th, after which it will round upward and return the first day of the current month. | First Day of the Current Month:
```
CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS
```
First of the Current Year is
```
CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS - (MONTH(CURRENT_DATE)-1) MONTHS
```
Last Day of the Last Month:
```
CURRENT_DATE - DAY(CURRENT_DATE) DAYS
```
First Day of the Last Month:
```
CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS - 1 MONTH
``` | Select first day of preceding month in (DB2) SQL | [
"",
"sql",
"database",
"date",
"db2",
""
] |
I saw this C# using statement in a code example:
```
using StringFormat=System.Drawing.StringFormat;
```
What's that all about? | That's aliasing a typename to a shorter name. The same syntax can also be used for aliasing namespaces. See [using directive](http://msdn.microsoft.com/en-us/library/sf0df423.aspx).
(Updated in response to Richard) | It's an **alias**, from now on, the user can use **StringFormat** to refer to **System.Drawing.StringFormat**. It's useful if you don't want to use the whole namespace (in case of name clash issues for example).
source: [using Directive article from MSDN](http://msdn.microsoft.com/en-us/library/sf0df423.aspx) | What's this C# "using" directive? | [
"",
"c#",
"using",
"using-directives",
""
] |
im new to regular expressions in php.
I have some data in which some of the values are stored as zero(0).What i want to do is to replace them with '-'. I dont know which value will get zero as my database table gets updated daily thats why i have to place that replace thing on all the data.
```
$r_val=preg_replace('/(0)/','-',$r_val);
```
The code im using is replacing all the zeroes that it finds for eg. it is even replacing zero from 104.67,giving the output 1-4.56 which is wrong. i want that data where value is exact zero that must be replaced by '-' not every zero that it encounter.
Can anyone please help!!
Example of the values that $r\_val is having :-
10.31,
391.05,
113393,
15.31,
1000 etc. | This depends alot on how your data is formatted inside `$r_val`, but a good place to start would be to try:
```
$r_val = preg_replace('/(?<!\.)\b0\b(?!\.)/', '-', $r_val);
```
Where `\b` is a 0-length character representing the start or end of a 'word'.
Strange as it may sound, but the [Perl regex documentation](http://perldoc.perl.org/perlre.html) is actually really good for explaining the regex part of the `preg_*` functions, since Perl is where the functionality is actually implemented. | Again, it would be more than helpful if you could supply an example of what the `$r_val` string really looks like.
Note that `\b` matches at word boundaries, which would also turn a string like "`0.75`" into "`-.75`". Not a desirable result, I guess. | replace exact match in php | [
"",
"php",
"mysql",
"regex",
""
] |
How do you retrieve the last element of an array in C#? | The array has a `Length` property that will give you the length of the array. Since the array indices are zero-based, the last item will be at `Length - 1`.
```
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
```
When declaring an array in C#, the number you give is the length of the array:
```
string[] items = new string[5]; // five items, index ranging from 0 to 4.
``` | LINQ provides [Last()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.last.aspx):
```
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
```
This is handy when you don't want to make a variable unnecessarily.
```
string lastName = "Abraham Lincoln".Split().Last();
``` | Finding the last index of an array | [
"",
"c#",
"arrays",
""
] |
I'm attempting to deserialize a custom class via the XmlSerializer and having a few problems, in the fact that I don't know the type that I'm going to be deserializing (it's pluggable) and I'm having difficulty determining it.
I found [this post](https://stackoverflow.com/questions/590658/c-serializing-and-restoring-an-unknown-class) which looks similar but can't quite get it to work with my approach because I need to deserialize an interface which is XmlSerializable.
What I've currently got is of the form. Note that I expect and need to be able to handle both class A and class B to be implemented via a plugin. So if I can avoid using the IXmlSerializable (which I don't think I can) then that would be great.
The ReadXml for A is what I'm stuck on. However if there are other changes that I can make to improve the system then I'm happy to do so.
```
public class A : IXmlSerializable
{
public IB MyB { get; set;}
public void ReadXml(System.Xml.XmlReader reader)
{
// deserialize other member attributes
SeekElement(reader, "MyB");
string typeName = reader.GetAttribute("Type");
// Somehow need to the type based on the typename. From potentially
//an external assembly. Is it possible to use the extra types passed
//into an XMlSerializer Constructor???
Type bType = ???
// Somehow then need to deserialize B's Members
// Deserialize X
// Deserialize Y
}
public void WriteXml(System.Xml.XmlWriter writer)
{
// serialize other members as attributes
writer.WriteStartElement("MyB");
writer.WriteAttributeString("Type", this.MyB.GetType().ToString());
this.MyB.WriteXml(writer);
writer.WriteEndElement();
}
private void SeekElement(XmlReader reader, string elementName)
{
ReaderToNextNode(reader);
while (reader.Name != elementName)
{
ReaderToNextNode(reader);
}
}
private void ReaderToNextNode(XmlReader reader)
{
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
{
reader.Read();
}
}
}
public interface IB : IXmlSerializable
{
}
public class B : IB
{
public void ReadXml(XmlReader reader)
{
this.X = Convert.ToDouble(reader.GetAttribute("x"));
this.Y = Convert.ToDouble(reader.GetAttribute("y"));
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("x", this.X.ToString());
writer.WriteAttributeString("y", this.Y.ToString());
}
}
```
NOTE : Updated as I realised B was supposed to use interface IB. Sorry for slightly wrong question. | To create an instance from a string, use one of the overloads of Activator.CreateInstance. To just get a type with that name, use Type.GetType. | I don't think you need to implement `IXmlSerializable`...
Since you don't know the actual types before runtime, you can dynamically add attribute overrides to the XmlSerializer. You just need to know the list of types that inherit from A. For instance, if you use A as a property of another class :
```
public class SomeClass
{
public A SomeProperty { get; set; }
}
```
You can dynamically apply `XmlElementAttribute`s for each derived type to that property :
```
XmlAttributes attr = new XmlAttributes();
var candidateTypes = from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
where typeof(A).IsAssignableFrom(t) && !t.IsAbstract
select t;
foreach(Type t in candidateTypes)
{
attr.XmlElements.Add(new XmlElementAttribute(t.Name, t));
}
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(SomeClass), "SomeProperty", attr);
XmlSerializer xs = new XmlSerializer(typeof(SomeClass), overrides);
...
```
This is just a very basic example, but it shows how to apply XML serialization attributes at runtime when you can't do it statically. | Custom Xml Serialization of Unknown Type | [
"",
"c#",
"xml-serialization",
""
] |
2007 formula written with A1 style, how is it possible to convert the A1 style formula to R1C1 in c# so that later on i can use it for range.FormulaArray=...
in documentation it says that FormulaArray should be given in R1C1 style...
for example this one
```
"=ROUND((IF(Sheet4!A1:HM232=1,0,"+
"IF(Sheet4!A1:HM232=0,1,Sheet4!A1:HM232))),0)"
```
i want to perform not operation on a matrix, at the end i will have the 0s and 1s replaced in a matrix... in excel -2007 i would select the range and press the Ctrl+Shift+Enter! | Use the [Application.ConvertFormula](http://msdn.microsoft.com/en-us/library/bb223281.aspx) function. | I think, there are different ways to write formula.
You cannot change the A1 style formula to R1C1 style using range.Formula.
You will have to use range.FormulaR1C1, if you wish to assign formula in R1C1 notation.
What are you trying to do exactly? | c# excel converting A1 formula to R1C1 | [
"",
"c#",
"excel-2007",
""
] |
Im on an optimization crusade for one of my sites, trying to cut down as many mysql queries as I can.
Im implementing partial caching, which writes .txt files for various modules of the site, and updates them on demand. I've came across one, that cannot remain static for all the users, so the .txt file thats written on the HD, will need to be altered on the fly via php.
Which is done via
```
flush();
ob_start();
include('file.txt');
$contents = ob_get_clean();
```
Then I modify the html in the $contents variable, and echo it out for different users.
Alternatively, I can leave it as it is, which runs a mysql query, which queries a small table that has category names (about 13 of them).
Which one is less expensive? Running a query every single time.... or doing it via the method I posted above, to inject html code on the fly, into a static .txt file? | Reading the file (save in very weird setups) will be minutely faster than querying the DB (no network interaction, &c), but the difference will hardly be measurable -- just try and see if you can measure it! | Optimize your queries first! Then use memcache or similar caching system, for data that is accessed frequently and then you can add file caching. We use all three combined and it runs very smooth. Small optimized queries aren't so bad. If your DB is in local server - network is not an issue. And don't forger to use MySQL query cache (i guess you do use MySQL). | Which one is less costly in terms of resources? | [
"",
"php",
"mysql",
"optimization",
""
] |
I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will `$_FILES['myflie']['size'] <=0` work? | You can use [`is_uploaded_file()`](http://php.net/manual/en/function.is-uploaded-file.php):
```
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
```
From the docs:
> Returns TRUE if the file named by
> filename was uploaded via HTTP POST.
> This is useful to help ensure that a
> malicious user hasn't tried to trick
> the script into working on files upon
> which it should not be working--for
> instance, /etc/passwd.
>
> This sort of check is especially
> important if there is any chance that
> anything done with uploaded files
> could reveal their contents to the
> user, or even to other users on the
> same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
```
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
``` | This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
```
<input name="files[]" type="file" multiple="multiple" />
```
PHP part:
```
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
``` | How to check whether the user uploaded a file in PHP? | [
"",
"php",
""
] |
My problem is a bit more complex than using the following simple JavaScript code:
```
window.onbeforeunload = function (e) {
return 'Are You Sure?';
};
```
On an e-commerce web page I would like to remind the user that he has items in the shopping cart so that he can change his mind before
1. closing the browser tab/window
2. navigating to another domain
The JavaScript method above does not solve my problem because it is evoked even when the user navigates within the domain.
Short:
1. User tries to close window -> Show dialog
2. User changes [www.mydomain.com/shoppingcart](http://www.mydomain.com/shoppingcart) url to [www.google.com](http://www.google.com) in the browser's address bar -> Show dialog
3. User navigates to [www.mydomain.com/checkout](http://www.mydomain.com/checkout) with the checkout button or presses the back button in the browser -> Do NOT show the dialog | Sorry there's no technical solution to your "problem."
It's not an accident when a user decides to leave your site, i.e. by typing a new URL, so stopping them to say "Hey, you haven't checked out yet" is kind of pointless. | It's not possible to tell if a user is pressing the back-button or closing the tab and you don't have access to their intended location.
It is possible to stop the dialog from showing if an internal link is clicked though:
```
(function(){
function isExternal( href ) {
return RegExp('https?:\\/\\/(?!' + window.location.hostname + ')').test(href);
}
var returnValue = 'Are you sure?';
document.documentElement.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.href && !isExternal(target.href)) {
returnValue = undefined;
}
};
window.onbeforeunload = function(){
return returnValue;
};
})();
``` | Prevent user from accidentally navigating away | [
"",
"javascript",
"dom-events",
""
] |
I'm trying to write a method like this:
```
public static T Test<T>()
{
if (typeof(T)==typeof(string))
return "1241";
// do something else
}
```
but I can't seem to figure out how to pull it off. I want to return values depending on the type of T that the method was invoked with. I need to return strings, int's, custom classes, List etc.
The actual usecase is some custom serialization code where it is essential that the deserializing code knows the type of the object it should produce.
Clarification:
the example above gives the following error:
Cannot convert string to type T
The ideal solution would work on value types and reference types, and would not include a dummy parameter for overload resolution.
I'm starting to doubt if that ideal solution exists though.
Thanks, Lucas | The intermediate cast to `object` isn't ideal, but something like this should do the trick:
```
public static T Test<T>()
{
if (typeof(T) == typeof(string))
return (T)(object)"1241";
// do something else
}
``` | You have to cast the return value to T, e.g. something like this for reference types:
```
public static T Test<T>() where T : class
{
if (typeof(T)==typeof(string))
return "1241" as T;
return default(T);
}
``` | I know the typeof(T) but the compiler doesn't. How to fix? | [
"",
"c#",
"generics",
""
] |
I'm currently implementing a JavaScript library that keeps track of the history of changes to the hash part in the address bar. The idea is that you can keep a state in the hash part, and then use the back button to go back to the previous state.
In most of the recent browsers, this is automatic and you only have to poll the `location.hash` property for changes (In IE8 you don't even have to do that; you simply attach a function to the `onhashchange` event.)
**What I'm wondering is**, what different methods are there to keep track of the history? I've implemented functionality that has been tested to work in Internet Explorer 6/7/8, Firefox and Chrome, but what about other browsers? Here's the ways I currently keep the history:
***Edit***: See my answer below instead for a walk-through of the various browsers. | First of all, thanks to you guys who answered! =)
I've now done a lot more research and I believe I'm satisfied with my implementation. Here are the results of my research.
First of all, [my finished `Hash` library](http://github.com/blixt/js-hash). It's a stand-alone library with no dependencies. It has two functions: `Hash.init(callback, iframe)` and `Hash.go(newHash)`. The callback function is called whenever the hash changes with the new hash as its first argument, and as its second argument a flag indicating whether the callback is called due to initial state (`true`) or an actual change to the hash (`false`).
> [Hash.js](http://github.com/blixt/js-hash/raw/master/Hash.js) (MIT license)
I also made a jQuery plugin for making it easier to use. Adds a global `hashchange` event as well. See example in source code for how to use it.
> [jquery.hash.js](http://github.com/blixt/js-hash/raw/master/jquery/jquery.hash.js) (MIT license)
To see them in use, go to my JavaScript "realm" page:
> [Blixt's JavaScript realm](http://blixt.org/js)
### Internet Explorer 8
Smooooth cruisin'! Just smack on one o' them `onhashchange` events to the `window` object (using `attachEvent`) and get the `location.hash` value in the event handler.
It doesn't matter if the user clicks a link with a hash, or if you set the hash programmatically; history is kept perfectly.
### Chrome, Firefox, Safari 3+, Opera 8+
Smooth cruisin'! Just poll for changes to the `location.hash` property using `setInterval` and a function.
History works perfectly. For Opera, I set `history.navigationMode` to `'compatible'`. To be honest, I'm not sure what it does, I did it on recommendation from a comment in the YUI code.
***Note***: Opera needs some additional testing, but it has worked fine for me so far.
***Surprise quirk bonus! (Can it be?!)*** It turns out that Firefox (only confirmed in 3.5+) decodes the `location.hash` property, so this can trigger a `hashchange` event twice (first for the encoded version then for the unencoded version.) There is a new version of my Hash.js library that takes this into account by using the `location.href` property instead (changes provided by Aaron Ogle.)
### Internet Explorer 6, 7
Now it gets nastier. The navigation history in older Internet Explorer versions ignore hash changes. To work around this, the commonly accepted solution is to create an `iframe` and set its content to the new hash. This creates a new entry in the navigation history. When the user goes back, this changes the content of the `iframe` to its previous content. By detecting the change of content, you can get it and set it as the active hash.
Checking for changes to the `location.hash` property is still needed to manual changes to the current address. Beware of the quirks I've mentioned below, though.
While this solution seems to be the best one out there, it's still not perfect in Internet Explorer 6, which is a bit quirky about the back/forward buttons. Internet Explorer 7 works fine, though.
***Surprise quirk bonus #1!*** In Internet Explorer 6, whenever there's a question mark in the hash, this gets extracted and put in the `location.search` *property! It is removed from the* `location.hash` *property. If there is a real query string, however,* `location.search` *will contain that one instead, and you'll only be able to get the whole true hash by parsing the* `location.href` *property.*
***Surprise quirk bonus #2!*** If the `location.search` *property is set, any subsequent* `#` *characters will be removed from the* `location.href` *(and* `location.hash`*) property. In Internet Explorer 6 this means that whenever there's a question mark in the path or the hash, you'll experience this quirk. In Internet Explorer 7, this quirk only occurs when there's a question mark in the path. Don't you just love the consistency in Internet Explorer?*
***Surprise quirk bonus #3!*** If another element on the page has the same id as the value of a hash, that hash will totally mess up the history. So rule of thumb is to avoid hashes with the same id as any elements on the page. If the hashes are generated dynamically and may collide with ids, consider using a prefix/suffix.
### Other browsers
Unless you've got an out-of-the-ordinary user base, you won't need to support more browsers. The browsers not listed above are in the <1% usage category. | Based on the effort that you've put into this, I would assume that you've seen [YUI Browser History Manager](http://developer.yahoo.com/yui/history/), but just in case ...
They give a nice write up of their implementation, and I find their source code very readable.
Here's what it says about Opera
```
* location.hash is a bit buggy on Opera. I have seen instances where
* navigating the history using the back/forward buttons, and hence
* changing the URL, would not change location.hash. That's ok, the
* implementation of an equivalent is trivial ... more below
```
Searching the source I found some accomodations for Safari 1.x & 2.0 also. Seems like you'd be interested in it.
Hope that helps. | Keeping history of hash/anchor changes in JavaScript | [
"",
"javascript",
"fragment-identifier",
""
] |
I have `asp:TextBox` to keep a value of money, i.e. '1000', '1000,0' and '1000,00' (comma is the delimiter because of Russian standard).
What `ValidationExpression` have I to use into appropriate `asp:RegularExpressionValidator`?
I tried `\d+\,\d{0,2}` but it doesn't allows a number without decimal digits, e.g. just '1000'. | ```
\d+(,\d{1,2})?
```
will allow the comma only when you have decimal digits, and allow no comma at all. The question mark means the same as `{0,1}`, so after the `\d+` you have either zero instances (i.e. nothing) or one instance of
```
,\d{1,2}
```
As Helen points out correctly, it will suffice to use a non-capturing group, as in
```
\d+(?:,\d{1,2})?
```
The additional `?:` means that the parentheses are only meant to group the `,\d{1,2}` part for use by the question mark, but that there is no need to remember what was matched within these parenthesis. Since this means less work for the regex enginge, you get a performance boost. | We use this very liberal regular expression for money validation:
```
new Regex(@"^\-?\(?\$?\s*\-?\s*\(?(((\d{1,3}((\,\d{3})*|\d*))?(\.\d{1,4})?)|((\d{1,3}((\,\d{3})*|\d*))(\.\d{0,4})?))\)?$");
```
It allows all these:
$0, 0, (0.0000), .1, .01, .0001, $.1, $.01, $.0001, ($.1), ($.01), $(.0001), 0.1, 0.01, 0.0001, 1., 1111., 1,111., 1, 1.00, 1,000.00, $1, $1.00, $1,000.00, $ 1.0000, $ 1.0000, $ 1,000.0000, -1, -1.00, -1,000.00, -$1, -$1.00, -$1,000.00, -$ 1, -$ 1.00, -$ 1,000.00, $-1, $-1.00, $-1,000.00, $(1), $(1.00), $(1,000.00), $ (1), $ (1.00), $ (1,000.00), ($1), ($1.00), ($1,000.00) | Regex for Money | [
"",
"c#",
"asp.net",
".net",
"regex",
"currency",
""
] |
How to change and update the title of the command prompt window from the java command line application? Every time I run my application, the command prompt window title shows:
`C:\WINDOWS\system32\cmd.exe - java MyApp`.
I'd like to change and update the window title as the java program runs, for example as wget(win32) updates downloading status in the title: `Wget [12%]`. | Although I haven't tried it myself, in Windows, one can use the Win32 API call to [`SetConsoleTitle`](http://msdn.microsoft.com/en-us/library/ms686050(VS.85).aspx) in order to change the title of the console.
However, since this is a call to a native library, it will require the use of something like [Java Native Interface (JNI)](http://en.wikipedia.org/wiki/Java_Native_Interface) in order to make the call, and this will only work on Windows 2000 and later.
**Edit - A solution using JNI**
The following is an example of using JNI in order to change the title of the console window from Java in Windows. To implement this, the prerequiste is some knowledge in C and using the compiler/linker.
First, here's result:
[](https://i.stack.imgur.com/6sXQA.png)
(source: [coobird.net](http://coobird.net/img/jni-change-console-title.png))
Disclaimer: This is my first Java application using JNI, so it's probably not going to be a good example of how to use it -- I don't perform any error-checking at all, and I may be missing some details.
The Java program was the following:
```
class ChangeTitle {
private static native void setTitle(String s);
static {
System.loadLibrary("ChangeTitle");
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
String title = "Hello! " + i;
System.out.println("Setting title to: " + title);
setTitle(title);
Thread.sleep(1000);
}
}
}
```
Basically, the title is changed every 5 seconds by calling the `setTitle` native method in an external native library called `ChangeTitle`.
Once the above code is compiled to make a `ChangeTitle.class` file, the [`javah`](http://java.sun.com/javase/6/docs/technotes/tools/windows/javah.html) command is used to create a C header that is used when creating the C library.
**Writing the native library**
Writing the library will involve writing the C source code against the C header file generated by `javah`.
The `ChangeTitle.h` header was the following:
```
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ChangeTitle */
#ifndef _Included_ChangeTitle
#define _Included_ChangeTitle
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: ChangeTitle
* Method: setTitle
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_ChangeTitle_setTitle
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
```
Now, the implementation, `ChangeTitle.c`:
```
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <jni.h>
#include "ChangeTitle.h"
JNIEXPORT void JNICALL
Java_ChangeTitle_setTitle(JNIEnv* env, jclass c, jstring s) {
const jbyte *str;
str = (*env)->GetStringUTFChars(env, s, NULL);
SetConsoleTitle(str);
(*env)->ReleaseStringUTFChars(env, s, str);
};
```
A `String` that is passed into the native function is changed into an UTF-8 encoded C string, which is sent to the [`SetConsoleTitle` function](http://msdn.microsoft.com/en-us/library/ms686050(VS.85).aspx), which, as the function name suggests, changes the title of the console.
(Note: There may be some issues with just passing in the string into the `SetConsoleTitle` function, but according to the documentation, it does accept Unicode as well. I'm not too sure how well the code above will work when sending in various strings.)
The above is basically a combination of sample code obtained from [Section 3.2: Accessing Strings](http://java.sun.com/docs/books/jni/html/objtypes.html#4001) of [The Java Native Interface Programmer's Guide and Specification](http://java.sun.com/docs/books/jni/html/jniTOC.html), and the [`SetConsoleTitle` Function](http://msdn.microsoft.com/en-us/library/ms686050(VS.85).aspx) page from MSDN.
For a more involved sample code with error-checking, please see the [Section 3.2: Accessing Strings](http://java.sun.com/docs/books/jni/html/objtypes.html#4001) and [`SetConsoleTitle` Function](http://msdn.microsoft.com/en-us/library/ms686050(VS.85).aspx) pages.
**Building the DLL**
The part that turned out to take the most amount of time for me to figure out was getting the C files to compile into an DLL that actually could be read without causing an [`UnsatisfiedLinkError`](http://java.sun.com/javase/6/docs/api/java/lang/UnsatisfiedLinkError.html).
After a lot of searching and trying things out, I was able to get the C source to compile to a DLL that could be called from Java. Since I am using MinGW, I found a page form `mingw.org` which [described exactly how to build a DLL for JNI](http://www.mingw.org/node/41).
Sources:
* [The Java Native Interface Programmer's Guide and Specification](http://java.sun.com/docs/books/jni/html/jniTOC.html)
+ [Chapter 2: Getting Started](http://java.sun.com/docs/books/jni/html/start.html#769) - Details the process using JNI.
* [JNI-MinGW-DLL](http://www.mingw.org/node/41) - Building a JNI DLL on MinGW with gcc. | This depends on your terminal emulator, but essentially it's just printing out control sequences to the console.
Now I'm not clear on what control sequences CMD.EXE responds to (I haven't one available to try this on) but I hear there's a command called [TITLE](http://www.ss64.com/nt/title.html) which sets the title of the window. I tried piping TITLE's output to a file, but apparently, it doesn't actually set the title by outputting control characters. The START command can take a parameter which is title of the window followed by the command to run in the window. So something like
```
cmd TITLE "lovely Application that is in a command window." && "java" MyApp
REM or
start "lovely Application that is java based." java MyApp
```
Personally I would just bundle the whole thing with a shortcut where you can edit the properties such as the current directory, the command, it's parameters, and the window size, style and title (if I remember rightly). Give it a nice icon and people will use it. | How to change command prompt (console) window title from command line Java app? | [
"",
"java",
"windows",
"command-line",
""
] |
Consider the following 3 standard statements
```
$queryString = "SOME SQL SELECT QUERY";
$queryResult = mysql_query($queryString);
$queryArray = mysql_fetch_array($queryResult);
```
Question is :
If the result set of the query is empty, what will be the resultant datatype and value of `$queryArray` after all three statements are executed ? | From the [`mysql_fetch_array` manual page](http://docs.php.net/mysql_fetch_array):
> Returns an array of strings that corresponds to the fetched row, or **`FALSE`** if there are no more rows.
So the data type of the final return value would be [*boolean*](http://docs.php.net/manual/en/language.types.boolean.php). | You should Read The Fine Manual. All the `mysql_fetch_*` functions return false if the result set is empty. False is a boolean type, although types aren't super-important in PHP.
Maybe consider using PDO instead of `mysql_*`, because it (1) doesn't tie your PHP code to a particular database vendor (allowing you to test with sqlite databases, for instance), and (2) PDO is more performant than the `mysql_*` functions in general. | Return Data and Type of mysql_fetch_array() | [
"",
"php",
"mysql",
"types",
"return-value",
""
] |
I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported.
I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?
Thanks! | See if [this](http://www.devshed.com/c/a/Python/Windows-Programming-in-Python/2/) gives you a start on word automation using python.
Once you open a document, you could do the following.
After the following code, you can Close the document & open another.
```
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "test"
.Replacement.Text = "test2"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
```
The above code replaces the text "test" with "test2" and does a "replace all".
You can turn other options true/false depending on what you need.
The simple way to learn this is to create a macro with actions you want to take, see the generated code & use it in your own example (with/without modified parameters).
EDIT: After looking at some code by Matthew, you could do the following
```
MSWord.Documents.Open(filename)
Selection = MSWord.Selection
```
And then translate the above VB code to Python.
Note: The following VB code is shorthand way of assigning property without using the long syntax.
(VB)
```
With Selection.Find
.Text = "test"
.Replacement.Text = "test2"
End With
```
Python
```
find = Selection.Find
find.Text = "test"
find.Replacement.Text = "test2"
```
Pardon my python knowledge. But, I hope you get the idea to move forward.
Remember to do a Save & Close on Document, after you are done with the find/replace operation.
In the end, you could call `MSWord.Quit` (to release Word object from memory). | I like the answers so far;
here's a tested example (slightly modified from [here](http://www.programmingforums.org/post105986.html))
that replaces all occurrences of a string in a Word document:
```
import win32com.client
def search_replace_all(word_file, find_str, replace_str):
''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
wdFindContinue = 1
wdReplaceAll = 2
# Dispatch() attempts to do a GetObject() before creating a new one.
# DispatchEx() just creates a new one.
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
app.Documents.Open(word_file)
# expression.Execute(FindText, MatchCase, MatchWholeWord,
# MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
app.Selection.Find.Execute(find_str, False, False, False, False, False, \
True, wdFindContinue, False, replace_str, wdReplaceAll)
app.ActiveDocument.Close(SaveChanges=True)
app.Quit()
f = 'c:/path/to/my/word.doc'
search_replace_all(f, 'string_to_be_replaced', 'replacement_str')
``` | Can I use Win32 COM to replace text inside a word document? | [
"",
"python",
"winapi",
"com",
"ms-word",
"replace",
""
] |
My image is passed into my program from a server and saved as a string. I want to convert that string into an image, and then in turn display that image within a label inside of a `GridBagLayout`. When I execute the below code, I get a blank frame. No exceptions during execution. When I look at the image object from the `ToolKit` in debug, it does say height and width are -1 (but the "imagedata" within the `source = ByteArrayImageSource` has byte[5144]). Any ideas?
Added Note: Image is stored in program as a String because the data is serialized in C# and is being deserialized within Java. This process apparently does not like `byte[]` in the deserialize process so I save it as a string and use `getBytes` when I want to use the image.
```
imageToDisplay = Toolkit.getDefaultToolkit().createImage(myString.getBytes());
ImageIcon logoIcon = new ImageIcon(imageToDisplay);
JLabel logolabel = new JLabel(logoIcon);
mainPanel.add(logolabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0));
mainFrame.add(mainPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
``` | Turns out this was my own fault. There is nothing wrong with the code I have written above other than I forgot to decode the image string. It is passed from the server Base64 encoded, and I was using getBytes on that encoded string and passing that into the "createImage" function. Thanks for your suggestions and help. The correct code is below:
```
try
{
imageToDisplay = Toolkit.getDefaultToolkit().createImage(Base64.decode(myString));
} catch (Exception e1) {
// // TODO Auto-generated catch block
e1.printStackTrace();
}
ImageIcon logoIcon = new ImageIcon(imageToDisplay);
JLabel logolabel = new JLabel(logoIcon);
mainPanel.add(logolabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0));
``` | First you need to find out if the problem is the image or the layout. Do mmyers suggestion and place it a panel (possibly by itself) with a FlowLayout. If it still doesn't show up, it might the image. Is there a reason why the input is converted to a String? The default charset may not be able to handle the conversion cleanly (that is, bytes -> String -> bytes may not give you the same initial bytes). | Image display within GridBagLayout Java | [
"",
"java",
"arrays",
"image",
""
] |
**Update:** This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.
I have a custom exception (let's call it `CustomException`), that lives in a file named `exceptions.py`. Now imagine, that I can import this file via two paths:
```
import application.exceptions
```
or
```
import some.application.exceptions
```
with the same result. Furthermore I have no control over which way the module is imported in other modules.
Now to show my problem: Assume that the function `do_something` comes from another module that imports exceptions.py in a way I don't know. If I do this:
```
import application.exceptions
try:
do_something ()
except application.exceptions.CustomException:
catch_me ()
```
it **might** work or not, depending on how the sub-module imported `exceptions.py` (which I do not know).
**Question:** Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?
Cheers,
## Update
It is a Django app. `some` would be the name of the Django 'project', `application` the name of one Django app. My code with the try..except clause sits in another app, `frontend`, and lives there as a view in a file `some/frontend/views.py`.
The PYTHONPATH is clean, that is, from my project only `/path/to/project` is in the path. In the `frontend/views.py` I import the exceptions.py via `import application.exceptions`, which seems to work. (Now, in retrospective, I don't know exactly, **why** it works...)
The exception is raised in the `exceptions.py` file itself.
## Update 2
It might be interesting for some readers, that I finally found the place, where imports went wrong.
The `sys.path` didn't show any suspect irregularities. My Django project lay in `/var/www/django/project`. I had installed the apps `app1` and `app2`, but noted them in the settings.py as
```
INSTALLED_APPS = [
'project.app1',
'project.app2',
]
```
The additional **`project.`** was the culprit for messing up `sys.modules`. Rewriting the settings to
```
INSTALLED_APPS = [
'app1',
'app2',
]
```
solved the problem. | Why that would be a problem? exception would me matched based on class type and it would be same however it is imported e.g.
```
import exceptions
l=[]
try:
l[1]
except exceptions.IndexError,e:
print e
try:
l[1]
except IndexError,e:
print e
```
both catch the same exception
you can even assign it to a new name, though not recommended usually
```
import os
os.myerror = exceptions.IndexError
try:
l[1]
except os.myerror,e:
print e
``` | "If not, what would be best practices to avoid these name clashes?"
That depends entirely on why they happen. In a normal installation, you can not import from both application.exceptions and somepath.application.exceptions, unless the first case is a relative path from within the module somepath. And in that case Python will understand that the modules are the same, and you won't have a problem.
You are unclear on if you really have a problem or if it's theory. If you do have a problem, I'd guess that there is something fishy with your PYTHONPATH. Maybe both a directory and it's subdirectory is in the PATH? | Custom Python exception with different include paths | [
"",
"python",
"django",
"exception",
""
] |
Is there a way to read a ByteBuffer with a BufferedReader without having to turn it into a String first? I want to read through a fairly large ByteBuffer as lines of text and for performance reasons I want to avoid writing it to the disk. Calling toString on the ByteBuffer doesn't work because the resulting String is too large (it throws java.lang.OutOfMemoryError: Java heap space). I would have thought there would be something in the API to wrap a ByteBuffer in a suitable reader, but I can't seem to find anything suitable.
Here's an abbreviated code sample the illustrates what I am doing):
```
// input stream is from Process getInputStream()
public String read(InputStream istream)
{
ReadableByteChannel source = Channels.newChannel(istream);
ByteArrayOutputStream ostream = new ByteArrayOutputStream(bufferSize);
WritableByteChannel destination = Channels.newChannel(ostream);
ByteBuffer buffer = ByteBuffer.allocateDirect(writeBufferSize);
while (source.read(buffer) != -1)
{
buffer.flip();
while (buffer.hasRemaining())
{
destination.write(buffer);
}
buffer.clear();
}
// this data can be up to 150 MB.. won't fit in a String.
result = ostream.toString();
source.close();
destination.close();
return result;
}
// after the process is run, we call this method with the String
public void readLines(String text)
{
BufferedReader reader = new BufferedReader(new StringReader(text));
String line;
while ((line = reader.readLine()) != null)
{
// do stuff with line
}
}
``` | It's not clear why you're using a byte buffer to start with. If you've got an `InputStream` and you want to read lines for it, why don't you just use an `InputStreamReader` wrapped in a `BufferedReader`? What's the benefit in getting NIO involved?
Calling `toString()` on a `ByteArrayOutputStream` sounds like a bad idea to me even if you had the space for it: better to get it as a byte array and wrap it in a `ByteArrayInputStream` and then an `InputStreamReader`, if you really have to have a `ByteArrayOutputStream`. If you *really* want to call `toString()`, at least use the overload which takes the name of the character encoding to use - otherwise it'll use the system default, which probably isn't what you want.
EDIT: Okay, so you really want to use NIO. You're still writing to a `ByteArrayOutputStream` eventually, so you'll end up with a BAOS with the data in it. If you want to avoid making a copy of that data, you'll need to derive from `ByteArrayOutputStream`, for instance like this:
```
public class ReadableByteArrayOutputStream extends ByteArrayOutputStream
{
/**
* Converts the data in the current stream into a ByteArrayInputStream.
* The resulting stream wraps the existing byte array directly;
* further writes to this output stream will result in unpredictable
* behavior.
*/
public InputStream toInputStream()
{
return new ByteArrayInputStream(array, 0, count);
}
}
```
Then you can create the input stream, wrap it in an `InputStreamReader`, wrap that in a `BufferedReader`, and you're away. | You can use NIO, but there's no real need here. As Jon Skeet suggested:
```
public byte[] read(InputStream istream)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // Experiment with this value
int bytesRead;
while ((bytesRead = istream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
// after the process is run, we call this method with the String
public void readLines(byte[] data)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)));
String line;
while ((line = reader.readLine()) != null)
{
// do stuff with line
}
}
``` | BufferedReader for large ByteBuffer? | [
"",
"java",
"nio",
"bufferedreader",
"bytebuffer",
""
] |
I need to download a *large* file (2 GB) over HTTP in a C# console application. Problem is, after about 1.2 GB, the application runs out of memory.
Here's the code I'm using:
```
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
byte[] fileData = request.DownloadData(baseURL + fName);
```
As you can see... I'm reading the file directly into memory. I'm pretty sure I could solve this if I were to read the data back from HTTP in chunks and write it to a file on disk.
How could I do this? | If you use [WebClient.DownloadFile](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfile(VS.80).aspx) you could save it directly into a file. | The WebClient class is the one for simplified scenarios. Once you get past simple scenarios (and you have), you'll have to fall back a bit and use WebRequest.
With WebRequest, you'll have access to the response stream, and you'll be able to loop over it, reading a bit and writing a bit, until you're done.
### From the Microsoft documentation:
> We don't recommend that you use WebRequest or its derived classes for
> new development. Instead, use the [System.Net.Http.HttpClient](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1) class.
>
> Source: [learn.microsoft.com/WebRequest](https://learn.microsoft.com/en-us/dotnet/api/system.net.webrequest?view=netcore-3.1)
---
Example:
```
public void MyDownloadFile(Uri url, string outputFilePath)
{
const int BUFFER_SIZE = 16 * 1024;
using (var outputFileStream = File.Create(outputFilePath, BUFFER_SIZE))
{
var req = WebRequest.Create(url);
using (var response = req.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[BUFFER_SIZE];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
outputFileStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
}
}
```
Note that if WebClient.DownloadFile works, then I'd call it the best solution. I wrote the above before the "DownloadFile" answer was posted. I also wrote it way too early in the morning, so a grain of salt (and testing) may be required. | How do I download a large file (via HTTP) in .NET? | [
"",
"c#",
".net",
"http",
"large-files",
""
] |
## Old question
My understanding is that C# has in some sense `HashSet` and `set` types. I understand what `HashSet` is. But why `set` is a separate word? Why not every set is `HashSet<Object>`?
## New question
Why does C# has no generic `Set` type, similar to `Dictionary` type? From my point of view, I would like to have a set with standard lookup/addition/deletion performance. I wouldn't care much whether it is realized with hashes or something else. So why not make a set class that would actually be implemented as a `HashSet` in this version of C# but perhaps somewhat different in a future version?
Or why not at least interface `ISet`?
# Answer
Learned thanks to everyone who answered below: `ICollection` implements a lot of what you'd expect from `ISet`. From my point of view, though, `ICollection` implements `IEnumerable` while sets don't have to be enumerable --- example: set of real numbers between 1 and 2 (even more, sets can be generated dynamically). I agree this is a minor rant, as 'normal programmers' rarely need uncountable sets.
Ok, I think I get it. `HashSet` was absolutely meant to be called `Set` but the word `Set` is reserved in some sense. More specifically, creators of .NET architecture wanted to have a consistent set (sic!) of classes for different languages. This means that every name of the standard class must not coincide with any keyword in the .NET languages. The word `Set`, however, is used in VB.NET which is actually case-insensitive (is it?) so unfortunately there is no room for maneuvre there.
Mystery solved :)
# Epilogue
The new answer by Alex Y. links to the [MSDN page](http://msdn.microsoft.com/en-us/library/dd412081%28VS.100%29.aspx) which describes the upcoming .NET 4.0 interface **`ISet`** which behaves pretty much as I thought it should and is implemented by `HashedSet`. Happy end. | (Your original question about `set` has been answered. IIRC, "set" is the word with the most different meanings in the English language... obviously this has an impact in computing too.)
I think it's fine to have `HashSet<T>` with that name, but I'd certainly welcome an `ISet<T>` interface. Given that `HashSet<T>` only arrived in .NET 3.5 (which in itself was surprising) I suspect we may eventually get a more complete collection of set-based types. In particular, the equivalent of Java's `LinkedHashSet`, which maintains insertion order, would be useful in some cases.
To be fair, the `ICollection<T>` interface actually covers most of what you'd want in `ISet<T>`, so maybe that isn't required. However, you could argue that the core purpose of a set (which is mostly about containment, and only tangentially about being able to iterate over the elements) isn't quite the same as a collection. It's tricky. In fact, a truly mathematical set may not be iterable or countable - for instance, you could have "the set of real numbers between 1 and 2." If you had an arbitrary-precision numeric type, the count would be infinite and iterating over it wouldn't make any sense.
Likewise the idea of "adding" to a set doesn't always make sense. Mutability is a tricky business when naming collections :(
EDIT: Okay, responding to the comment: the keyword `set` is in no way a legacy to do with Visual Basic. It's the operation which *sets* the value of a property, vs `get` which *retrieves* the operation. This has nothing to do with the idea of a set as an operation.
Imagine that instead the keywords were actually `fetch` and `assign`, e.g.
```
// Not real code!
public int Foo
{
fetch
{
return fooField;
}
assign
{
fooField = value;
}
}
```
Is the purpose clear there? Now the *real* equivalent of that in C# is just
```
public int Foo
{
get
{
return fooField;
}
set
{
fooField = value;
}
}
```
So if you write:
```
x = y.Foo;
```
that will use the `get` part of the property. If you write:
```
y.Foo = x;
```
that will use the `set` part.
Is that any clearer? | The only reason for this seems lack of resources to implement this ideally in .NET 3.5.
.NET 4.0 will include [ISet](http://msdn.microsoft.com/en-us/library/dd412081(VS.100).aspx), as well as its new implementation in addition to [HashSet](http://msdn.microsoft.com/en-us/library/bb359438(VS.100).aspx) - [SortedSet](http://msdn.microsoft.com/en-us/library/dd412070(VS.100).aspx). Check out the provided links to MSDN library - they're already available in .NET 4.0 beta1. | Why have HashSet but not Set in C#? | [
"",
"c#",
"set",
"hashset",
""
] |
I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references.
I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just *before* the data is dropped.
So obviously this code megafails when I put in velocity\_func:
```
class Body(object):
def __init__(self, mass, inertia):
self._body = body.New(mass, inertia)
def __del__(self):
print '__del__ %r' % self
if body:
body.Free(self._body)
...
def set_velocity_func(self, func):
self._body.contents.velocity_func = ctypes_wrapping(func)
```
I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable.
Even if I don't put in the velocity\_func, there will appear cycles at least then when I do this:
```
class Toy(object):
def __init__(self, body):
self.body.owner = self
...
def collision(a, b, contacts):
whatever(a.body.owner)
```
So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library?
There's repository if you are interested about more details: <http://bitbucket.org/cheery/ctypes-chipmunk/> | If weakrefs aren't broken, I guess this may work:
```
from weakref import ref
pointers = set()
class Pointer(object):
def __init__(self, cfun, ptr):
pointers.add(self)
self.ref = ref(ptr, self.cleanup)
self.data = cast(ptr, c_void_p).value # python cast it so smart, but it can't be smarter than this.
self.cfun = cfun
def cleanup(self, obj):
print 'cleanup 0x%x' % self.data
self.cfun(self.data)
pointers.remove(self)
def cleanup(cfun, ptr):
Pointer(cfun, ptr)
```
I yet try it. The important piece is that the Pointer doesn't have any strong references to the foreign pointer, except an integer. This should work if ctypes doesn't free memory that I should free with the bindings. Yeah, it's basicly a hack, but I think it may work better than the earlier things I've been trying.
Edit: Tried it, and it seem to work after small finetuning my code. A surprising thing is that even if I got **del** out from all of my structures, it seem to still fail. Interesting but frustrating.
Neither works, from some weird chance I've been able to drop away cyclic references in places, but things stay broke.
Edit: Well.. weakrefs WERE broken after all! so there's likely no solution for reliable cleanup in python, except than forcing it being explicit. | What you want to do, that is create an object that allocates things and then deallocates automatically when the object is no longer in use, is almost impossible in Python, unfortunately. The **del** statement is not guaranteed to be called, so you can't rely on that.
The standard way in Python is simply:
```
try:
allocate()
dostuff()
finally:
cleanup()
```
Or since 2.5 you can also create context-managers and use the with statement, which is a neater way of doing that.
But both of these are primarily for when you allocate/lock in the beginning of a code snippet. If you want to have things allocated for the whole run of the program, you need to allocate the resource at startup, before the main code of the program runs, and deallocate afterwards. There is one situation which isn't covered here, and that is when you want to allocate and deallocate many resources dynamically and use them in many places in the code. For example of you want a pool of memory buffers or similar. But most of those cases are for memory, which Python will handle for you, so you don't have to bother about those. There are of course cases where you want to have dynamic pool allocation of things that are NOT memory, and then you would want the type of deallocation you try in your example, and that *is* tricky to do with Python. | How to do cleanup reliably in python? | [
"",
"python",
"ctypes",
"cyclic-reference",
""
] |
I've inherited a piece of code that makes intensive use of String -> byte[] conversions and vice versa for some homegrown serialisation code. Essentially the Java objects know how to convert their constituent parts into Strings which then get converted into a byte[]. Said byte array is then passed through JNI into C++ code that reconstitutes the byte[] into C++ std::strings and uses those to bootstrap C++ objects which mirror the Java objects. There is a little more to it but this is a high level view of how this piece of code works; The communication works like this in both directions such that the C++ -> Java transition is a mirror image of the Java -> C++ transition I mentioned above.
One part of this code - the actual conversion of a String into a byte[] - is unexpectedly showing up in the profiler as burning a lot of CPU. Granted, there is a lot of data that is being transferred but this is an unexpected bottleneck.
The basic outline of the code is as follows:
```
public void convertToByteArray(String convert_me, ByteArrayOutputStream stream)
{
stream.write(convert_me.getBytes());
}
```
There is a little more to the function but not much. The above function gets called once for every String/Stringified object and after all of the constituents are written to the ByteArrayOutputStream, the ByteArrayOutputStream gets converted into a byte[]. Breaking the above down into a more profiler-friendly version by extracting the `convert_me.getBytes()` call shows that over 90% of the time in this function is spent in the getBytes() call.
Is there a way to improve upon the performance of the getBytes() call or is there another, potentially faster way to achieve the same conversion?
The number of objects that are being converted is quite large. On the profiling runs which are using only a small subset of the production data, I'm seeing something like 10 million plus calls to the above conversion function.
Due to the fact that we're very close to releasing the project into production, there are a few workarounds that aren't possible at this point in time:
* Rewrite the serialisation interface to just pass String objects across the JNI layer. This is the obvious (to me) way of improving the situation but it would require major reengineering of the serialisation layer. Given the fact that we're going into UAT early this week, it's far too late to make this sort of complex change. It is my top todo for the next release so it will be done; I however do need a workaround until then, but so far the code is working, has been used for years and has most of the kinks worked out. Well, aside from the performance.
* Changing the the JVM (currently 1.5) is also not an option. Unfortunately this is the default JVM that is installed on the client's machines and updating to 1.6 (which might or might not be faster in this case) is unfortunately not possible. Anybody who has worked in large organisations probably understands why...
* In addition to this, we're already running into memory constraints so attempting to cache at least the larger Strings and their byte array representation, while being a potentially elegant solution, is likely to cause more problems than it will solve | I'm guessing part of the problem may be that a Java String is in UTF-16 format - i.e. two bytes per character; so `getBytes()` is doing a bunch of work to convert each UTF-16 element into one or two bytes, dependent on your current character set.
Have you tried using [CharsetEncoder](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/CharsetEncoder.html) - this should give you more control over the String encoding and allow you to skip some of the overhead in the default `getBytes` implementation.
Alternatively, have you tried explicitly specifying the charset to `getBytes`, and use *US-ASCII* as the character set? | I see several options:- If you have Latin-1 strings, you could just split the higher byte of the chars in the string (Charset does this too I think)
- You could also split the work among multiple cores if you have more (the fork-join framework had backport to 1.5 once)
- You could also build the data into a stringbuilder and only convert it to byte array once at the end.
- Look at your GC/memory usage. Too much memory utilization might slow your algorithms down due frequent GC interruptions | Any suggestion on how to improve the performance of a Java String to byte[] conversion? | [
"",
"java",
"performance",
"java-native-interface",
""
] |
I'm using jsf 1.2. When a particular jsp has more than one form with a specified id, for example when using something like below, jsf gives the form a seemingly random id.
```
<ui:repeat>
<h:form id="repeatingform">
...
```
I would like submit all forms using javascript. Is there a way to do this without knowing the ids of the forms? | Hmm, It won't work like that real easy. If you would use something like document.form1.submit(); it posts that specific form and all values in it.
So it's **no use looping through all the forms and submitting every single one**.
That would be the same as clicking on the submit button of each single form, resulting in each form being posted separately.
The solution is to collect the values of each field in each form in a single collector form, and post the collector form.
You can read (with code examples!) more about it here: <http://www.codetoad.com/forum/15_24387.asp> | Submitting more than one form at once it not really possible. The problem is that each form requires its own separate request - submitting a form is basically similar to clicking a link, and you can't open all links on a page at once (you can by opening them in new tabs/windows, but that's a different matter)
If you really do want to keep each form its separate form element, you can use Aquatic's example,
```
var forms = document.getElementsByTagName("FORM");
for (var i=0; i<forms.length; i++)
forms[i].submit();
```
but replace the code which runs `submit()` with code which submits the form using XMLHttpRequest. You can have multiple XMLHttpRequests running in the background. | Javascript submitting all the forms on a page | [
"",
"javascript",
"forms",
"jsf",
""
] |
Maybe I'm having a really bad day, but could someone possibly help me to turn this:
```
MessageID | SendingUserID | ReceivingUserID
-------------------------------------------
1073 | 1002 | 1001
1065 | 1001 | 1002
1076 | 1008 | 1002
```
Into:
```
MessageID | SendingUserID | ReceivingUserID
-------------------------------------------
1073 | 1002 | 1001
1076 | 1008 | 1002
```
Whereby,only the most recent message between two users is listed? | try this:
```
SELECT Message.*
FROM Message
WHERE Message.MessageID IN
(SELECT MAX(MessageID) FROM Message
GROUP BY
CASE WHEN ReceivingUserID > SendingUserID
THEN ReceivingUserID ELSE SendingUserID END,
CASE WHEN ReceivingUserID > SendingUserID
THEN SendingUserID ELSE ReceivingUserID END
)
``` | The exclusive self join approach:
```
select *
from YourTable a
left join YourTable b
on (
(a.SendingUserID = b.SendingUserID
and a.ReceivinggUserID = b.ReceivingUserID)
or (a.SendingUserID = b.ReceivingUserID
and a.ReceivinggUserID = b.SendingUserID)
) and b.messageid > a.messageid
where b.messageid is null
```
The join on "b" searches for later messages between the same users. The WHERE clause filters for messages that do not have a later message. This gives you only the latest message between each pair of users. | SQL Grouping: Most recent record between users | [
"",
"sql",
"grouping",
""
] |
```
function randomString( len ) {
// A random string of length 'len' made up of alphanumerics.
var out = '';
for (var i=0; i<len; i++) {
var random_key = 48 + Math.floor(Math.random()*42); //0-9,a-z
out += String.fromCharCode( random_key );
}
window.alert(out);
return out;
}
```
As far as I can tell the result of `String.fromCharCode` is system and/or browser dependent. All the workarounds I've seen are for when you are actually capturing keycodes, not generating them. Is there a more reliable way to do this (like converting from ASCII codes?). | > var random\_key = 48 +
> Math.floor(Math.random()\*42);
> //0-9,a-z
The code and the comment doesn't correspond. The characters that may be created is in the range 0-9, :, ;, <, =, >, ?, @, and A-Z.
The character codes in this range is in the ASCII character set, so they are the same for all commonly used western character sets. The fromCharCode method should use the character set that you have specified for the page, but in the range that you are using that doesn't matter.
Make the range seven smaller, and add 39 if it's not a digit to get 0-9 and a-z:
```
function randomString(len) {
// A random string of length 'len' made up of alphanumerics.
var out = '';
for (var i=0; i<len; i++) {
var random_key = 48 + Math.floor(Math.random() * 36);
if (random_key > 57) random_key += 39;
out += String.fromCharCode(random_key);
}
window.alert(out);
return out;
}
``` | Here is some partial[-](https://jsfiddle.net/Lamik/zr2vbfjh/)alternative which allows you to get `0-1` and `a-z`
```
let l= 30483235087530204251026473460499750369628008625670311705n.toString(36)
console.log(l[26], l[0], l[25].toUpperCase(), l);
``` | need a reliable alternative to String.fromCharCode | [
"",
"javascript",
""
] |
I have a function that is recursively calling itself, and i want to detect and terminate if goes into an infinite loop, i.e - getting called for the same problem again. What is the easiest way to do that?
EDIT: This is the function, and it will get called recursively with different values of x and y. i want to terminate if in a recursive call, the value of the pair (x,y) is repeated.
```
int fromPos(int [] arr, int x, int y)
``` | If the function is purely functional, i.e. it has no state or side effects, then you could keep a `Set` of the arguments (edit: seeing your edit, you would keep a Set of pairs of (x,y) ) that it has been called with, and every time just check if the current argument is in the set. That way, you can detect a cycle if you run into it pretty quickly. But if the argument space is big and it takes a long time to get to a repeat, you may run out of your memory before you detect a cycle. In general, of course, you can't do it because this is the halting problem. | One way is to pass a `depth` variable from one call to the next, incrementing it each time your function calls itself. Check that `depth` doesn't grow larger than some particular threshold. Example:
```
int fromPos(int [] arr, int x, int y)
{
return fromPos(arr, x, y, 0);
}
int fromPos(int [] arr, int x, int y, int depth)
{
assert(depth < 10000);
// Do stuff
if (condition)
return fromPos(arr, x+1, y+1, depth + 1);
else
return 0;
}
``` | How to detect an infinite loop in a recursive call? | [
"",
"java",
"detection",
"infinite-loop",
""
] |
I have a string "stack+ovrflow\*newyork;" i have to split this stack,overflow,newyork
any idea?? | First and foremost if available, I would always use boost::tokenizer for this kind of task (see and upvote the great answers below)
Without access to boost, you have a couple of options:
You can use C++ std::strings and parse them using a stringstream and getline (safest way)
```
std::string str = "stack+overflow*newyork;";
std::istringstream stream(str);
std::string tok1;
std::string tok2;
std::string tok3;
std::getline(stream, tok1, '+');
std::getline(stream, tok2, '*');
std::getline(stream, tok3, ';');
std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl
```
Or you can use one of the strtok family of functions (see Naveen's answer for the unicode agnostic version; see xtofls comments below for warnings about thread safety), if you are comfortable with char pointers
```
char str[30];
strncpy(str, "stack+overflow*newyork;", 30);
// point to the delimeters
char* result1 = strtok(str, "+");
char* result2 = strtok(str, "*");
char* result3 = strtok(str, ";");
// replace these with commas
if (result1 != NULL)
{
*result1 = ',';
}
if (result2 != NULL)
{
*result2 = ',';
}
// output the result
printf(str);
``` | [Boost tokenizer](http://www.boost.org/doc/libs/1_39_0/libs/tokenizer/index.html)
Simple like this:
```
#include <boost/tokenizer.hpp>
#include <vector>
#include <string>
std::string stringToTokenize= "stack+ovrflow*newyork;";
boost::char_separator<char> sep("+*;");
boost::tokenizer< boost::char_separator<char> > tok(stringToTokenize, sep);
std::vector<std::string> vectorWithTokenizedStrings;
vectorWithTokenizedStrings.assign(tok.begin(), tok.end());
```
Now vectorWithTokenizedStrings has the tokens you are looking for. Notice the boost::char\_separator variable. It holds the separators between the tokens. | How to split the strings in vc++? | [
"",
"c++",
"visual-c++",
""
] |
I've implemented a data access library that allows devs to mark up their derived classes with attributes to have them mapped directly to stored procedures. So far, so good. Now I'd like to provide a Serialize() method or override ToString(), and have the derived classes get free serialization into XML.
Where should I start? Will I have to use Reflection to do this? | ### XML Serialization using XmlSerializer
In the first instance, I would look at the [XML Serialization](http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx) in the .NET Framework that supports serialization of objects to and from XML using an [`XmlSerializer`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx). There's also an article from [Extreme XML on using this serialization framework](http://msdn.microsoft.com/en-us/library/ms950721.aspx).
The following links all provide examples of using this approach:
* [CodeProject article](http://www.codeproject.com/KB/XML/xml_serializationasp.aspx)
* [Microsoft KB article](http://support.microsoft.com/kb/815813)
* [DotNetJohn - XML Serialization Using C#](http://www.dotnetjohn.com/articles.aspx?articleid=173)
### ISerializable and SerializableAttribute
An alternative to this would be to use a formatter and the regular [`SerializableAttribute`](http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx) and [`ISerializable`](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx) system of serialization. However, there is no built-in XML formatter for this framework other than the [`SoapFormatter`](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.soap.soapformatter.aspx), so you'd need to roll your own or find a third party/open source implementation.
### Roll Your Own
Also, you could consider writing your own system using, for example, reflection to walk your object tree, serializing items according to their serialization visibility, which could be indicated by your own attributes or the existing [`DesignerSerializationVisibility`](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibilityattribute.aspx) attributes. The downside to this shown by most implementations is that it expects properties to be publicly read/write, so bear that in mind when evaluating existing custom solutions. | I would start by looking at [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx).
Hopefully you'll be able to end there too, since it already gives you this functionality :) | Providing serialization services in a base class that can be used in derived classes | [
"",
"c#",
"serialization",
""
] |
I've been seeing this in my Visual C# 2008 RSS Feed forever now:
<http://lincolnfair.net/oldLincolnFair/mad.jpg>
I'm pretty sure this is a VS 2010 only feature, but I was wondering if there is anyway to replicate this in VS 2008? | Similar to @Relster I have a code snippet with the following
```
#if DEBUG
if( node.Name == "Book" )
System.Diagnostics.Debugger.Break();
#endif
```
Where `node.Name == "Book"` changes based on the condition I want to test for. the `#if DEBUG` wrapper makes sure the checks never make it to release code.
This is also *a lot* faster than using the conditional breakpoints in Visual Studio. When you use the built in conditional bp visual studio has to break into the app, pause all the threads, evaluate the expression and determine if it is true each time it hits the breakpoint. In a tight loop this can be the difference between near full execution performance and running at a crawl. | You can do it in VS 2008 too. I'm sure there's many ways to do it, but one way is to right click on the red dot in the margin of an existing breakpoint & select `condition...`, then just give it a condition that evaluates to a `bool` and it will only break if that's true. The conditional statement should have access to anything that's in scope at the line where the breakpoint is set.
There's also other options in that context menu that allow you to filter what will cause a break (for example only certain threads), break based on the number of times the breakpoint has been hit, run macros when you hit the breakpoint, etc. | How Do I: Create a Breakpoint Using Conditions? [C# Express] | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"visual-studio-2010",
"breakpoints",
""
] |
In theory, is it more efficient to remove elements from an `ArrayList` or a `LinkedList`? | It is "easier" (that is, more efficient) to remove them from a `LinkedList`, because removal from an `ArrayList` requires moving all subsequent elements to a new position in the list—all subsequent elements of the array must be assigned a new value. With a linked list, only one pointer (or two, with a doubly-linked list) must be re-assigned. | Well, removal of an element from a (doubly-linked-)list is O(1). But removal from an array will require that the remaining elements are shifted down one space in the array, which is O(n).
That said, getting a specific element in a list by index is O(n), while getting a specific element in an array by index is O(1).
So, the for actual removal, LinkedList will be better. There is more info on Array's versus LinkedList [here](https://stackoverflow.com/questions/166884/array-vs-linked-list). | Is it more efficient to remove elements from an ArrayList or a LinkedList? | [
"",
"java",
"arraylist",
"linked-list",
""
] |
I'm writing a plug-in for another program in C#.NET, and am having performance issues where commands take a lot longer then I would. The plug-in reacts to events in the host program, and also depends on utility methods of the the host program SDK. My plug-in has a lot of recursive functions because I'm doing a lot of reading and writing to a tree structure. Plus I have a lot of event subscriptions between my plugin and the host application, as well as event subscriptions between classes in my plug-in.
How can I figure out what is taking so long for a task to complete? I can't use regular breakpoint style debugging, because it's not that it doesn't work it's just that it's too slow. I have setup a static "LogWriter" class that I can reference from all my classes that will allow me to write out timestamped lines to a log file from my code. Is there another way? Does visual studio keep some kind of timestamped log that I could use instead? Is there someway to view the call stack after the application has closed? | You need to use profiler. Here link to good one: [ANTS Performance Profiler](http://www.red-gate.com/products/ants_performance_profiler/index.htm).
**Update:** You can also write messages in control points using [Debug.Write](http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.write.aspx). Then you need to load [DebugView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx) application that displays all your debug string with precise time stamp. It is freeware and very good for quick debugging and profiling. | [My Profiler List](http://cid-600a2be4a82ea0a6.profile.live.com/Lists/cns!600A2BE4A82EA0A6!678/ "Profiler Tools for .NET") includes ANTS, dotTrace, and AQtime.
---
However, looking more closely at your question, it seems to me that you should do some unit testing at the same time you're doing profiling. Maybe start by doing a quick overall performance scan, just to see which areas need most attention. Then start writing some unit tests for those areas. You can then run the profiler while running those unit tests, so that you'll get consistent results. | What is the best way to debug performance problems? | [
"",
"c#",
".net",
"performance",
"debugging",
""
] |
I have a list `A`, and a function `f` which takes an item of `A` and returns a list. I can use a list comprehension to convert everything in `A` like `[f(a) for a in A]`, but this returns a list of lists. Suppose my input is `[a1,a2,a3]`, resulting in `[[b11,b12],[b21,b22],[b31,b32]]`.
How can I get the *flattened* list `[b11,b12,b21,b22,b31,b32]` instead? In other words, in Python, how can I get what is traditionally called `flatmap` in functional programming languages, or `SelectMany` in .NET?
(In the actual code, `A` is a list of directories, and `f` is `os.listdir`. I want to build a flat list of subdirectories.)
---
See also: [How do I make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914) for the more general problem of flattening a list of lists after it's been created. | You can have nested iterations in a single list comprehension:
```
[filename for path in dirs for filename in os.listdir(path)]
```
which is equivalent (at least functionally) to:
```
filenames = []
for path in dirs:
for filename in os.listdir(path):
filenames.append(filename)
``` | ```
>>> from functools import reduce # not needed on Python 2
>>> list_of_lists = [[1, 2],[3, 4, 5], [6]]
>>> reduce(list.__add__, list_of_lists)
[1, 2, 3, 4, 5, 6]
```
[The `itertools` solution](https://stackoverflow.com/a/1077074) is more efficient, but this feels very pythonic. | How can I get a flat result from a list comprehension instead of a nested list? | [
"",
"functional-programming",
"python",
"list-comprehension",
""
] |
I'm writing a simple program. There is only one class in it. There is a private member 'char \* number' and two function (there will be more, but first these should work correctly :) ).
The first one should copy the 'source' into 'number' variable (and I suppose somewhere here is the problem):
```
LongNumber::LongNumber(const char * source ){
int digits = strlen(source);
char* number = new char[digits+1];
strcpy( number, source );
// cout<<number<<endl; - if the line is uncommented,
// the output is correct and there isn't a problem
}
```
And a print function:
```
void LongNumber::print(){
cout<<number<<endl;
// when I try to print with the same line of code here..it crashes
}
```
Sure, I'm missing something...but what?
(As this is my first post...do you think the tags are corrected..how would you tagged the post?)
Thank you in advance :) | In the `LongNumber` constructor you declare a new local variable named `number` and initialize it with a new `char` array:
```
char* number = new char[digits+1];
```
Instead you should leave out the `char*`, so that it doesn't look like a new variable declaration and uses the object member variable:
```
number = new char[digits+1];
```
With the current code, the member variable `number` never gets initialized and using it later in `print` leads to an error. | Your number char\* array would be out of scope when it exits the constructor. When you reach the print(), since the program no longer has access to the memory that \*number is originally pointing to, it would crash (i.e. segmentation fault). To solve this problem do this instead:
```
class LongNumber
{
char *number;
LongNumber(const char *source);
~LongNumber();
void print();
};
LongNumber::LongNumber(const char * source ){
int digits = strlen(source);
number = new char[digits+1];
strcpy( number, source );
}
void LongNumber::print(){
cout<<number<<endl;
}
```
Don't forget to do the following:
```
LongNumber::~LongNumber()
{
delete [] number; // to avoid memory leaks
}
```
I would also highly recommend using STL::string rather than using char\* for your \*number variable, as you won't have to deal with memory management overhead yourself, and copying the string would be easier too. | Printing a char* in C++ | [
"",
"c++",
"printing",
"pointers",
"char",
""
] |
When I use CakePHP Paging I get an url like this:
```
http://example.com/php/page:2
```
What do I have to change in the controller, the view and the routes.php to create a working url like this:
```
http://example.com/php/2
``` | Try this link:
<http://www.sakic.net/blog/changing-cakephp-pagination-urls/> | Oh yes, now I see your question. Well you could do something like:
```
function index($page){
$this->paginate = array('page'=>$page);
$this->set('stuff', $this->paginate('YourControllerName'));
}
```
See here for more details:
<http://bakery.cakephp.org/articles/view/basic-pagination-overview-3>
Also, of course you should do some validation that the page is an actual number and that the page would even exist but that is the basics of it i think.
About the routes and views, I have never tried but have a look at these posts on the cake groups, I think they have a problem similar to yours.
<http://www.mail-archive.com/cake-php@googlegroups.com/msg45878.html> | CakePHP Pagination - how to remove "page:" from url for better seo/cleaner URL | [
"",
"php",
"cakephp",
"seo",
"pagination",
"paging",
""
] |
i just tinkered around with [Google Guice](http://code.google.com/p/google-guice/) for Dependency Injection and started integrating it into my existing application. So far, so good. I have many classes which need, beside their dependencies, Strings, DataSources, et cetera. I know there are NamedBindings, but i really do not want to create an annotation for every simple String i have to pass to the constructor for each class. Then, there is a thing called AssistedInject, creating Factory implementions for me. Wow, but i still have to define the interface of the factory. Thats okay for classes which DO HAVE dependencies, but what about this example class:
```
public class FooBarClass {
public FooBarClass(String name, String anotherOne) {
// Some stuff
}
}
```
There are cases where i am in doubt how to use Guice or, more generally, DI the right way. "Often i hear: XYZ Framework is the new **new**." But this implicit that i have to create **every** instance with the DI framework.
# Only one instance is required
What if i need only one instance of this class? This class has absolutly no dependencies beside two Strings. Think about a Shutdown Hook which will be instanciated only once and passed to the JVM as my Shutdown Hook. Should i create this instance with Guice? This looks very dumb to me, because there is nothing to inject, but i have to write a factory interface to pass Guide both parameters and have to create an interface for my FooBarClass to use DI.
# Multiple instances are required
The same thing applies to a case where i need multiple instances of this class. No dependencies, but i have to create a bunch of boilerplate code to get nothing out of it. This seems wrong to me.
So, how i am supposed to use DI and/or Guice?
Thanks a lot! | It might help to split **dependencies** from **data**.
* Dependencies are often services: databases, clocks, and RPC stubs. Plus all of the application code layered on these: `UserAuthenticator`, `PaymentHandler`, and `EmailGateway`.
* Data is just that: a `Date`, a `Map<String,InetAddress>` or even a `Customer`. These are simple, in-memory domain objects.
DI is naturally best suited for the dependency side of things. You should continue to use `new` for your data model classes. | Inject a dependency if you want to ignore (isolate) its complexity when testing a particular class. If the class is just a data holder, its code is trivial (get, set, equals). You don't need to mock it when testing the target class, so injecting the data instance is overkill (and usually hard). If the code is not trivial, the class is more than a data holder, and you should inject and mock it on unit tests. | Dependency Injection with Guice: Something that isn't covered by any tutorial | [
"",
"java",
"dependency-injection",
"guice",
""
] |
I have a streaming input which has repeated values. I can use any data structure but I have to count the number of occurence of each element. Suppose I have a list of mobile phone suppliers like the following:
```
Apple
Nokia
Samsung
Apple
LG
Nokia
HTC
Android
Apple
Nokia
Nokia
Apple
Samsung
```
I have to build any data structure preferably a map with details like
```
Apple,4
Nokia,4
Samsung,2
LG,1
Android,1
```
I am not sure whether this is optimal. Is there a better solution than this?
In fact I have yet to write the above as a code. So better code will also help. | Yes, I would use a `Map<String, Integer>`. I would wrap the `add` in something like this:
```
private static void incrementValue(Map<String, Integer> counters, String toAdd) {
Integer currValue = counters.get(toAdd);
if (currValue == null)
counters.put(toAdd, 1);
else
counters.put(toAdd, currValue+1);
}
```
Or without generics:
```
private static void incrementValue(Map counters, String toAdd) {
Integer currValue = (Integer) counters.get(toAdd);
if (currValue == null)
counters.put(toAdd, 1);
else
counters.put(toAdd, currValue+1);
}
``` | Since it was mentioned by the questioner that generics could not be used, as the target platform was Java 1.4, one could use the [Apache Commons Collections](http://commons.apache.org/collections/) which doesn't use generics.
The [answer by pjp](https://stackoverflow.com/questions/1059114/counting-the-list-items/1059159#1059159) mentions that a Bag can be used.
It turns out, the Apache Commons Collections has a [`Bag`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Bag.html) which has a [`getCount`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Bag.html#getCount(java.lang.Object)) method which will return the count of a certain object that was added to the `Bag`.
The following is an example that [`add`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Bag.html#add(java.lang.Object))s some `Integer` objects to a [`HashBag`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/bag/HashBag.html), and counts how many of each `Integer` object that the `Bag` contains:
```
Bag b = new HashBag();
b.add(Integer.valueOf(1));
b.add(Integer.valueOf(2));
b.add(Integer.valueOf(2));
b.add(Integer.valueOf(3));
System.out.println("Count for 1: " + b.getCount(Integer.valueOf(1)));
System.out.println("Count for 2: " + b.getCount(Integer.valueOf(2)));
System.out.println("Count for 3: " + b.getCount(Integer.valueOf(3)));
```
The results were:
```
Count for 1: 1
Count for 2: 2
Count for 3: 1
```
(I should add a disclaimer that this code was actually compiled and run on Java 6, but I believe I've only used features which were present from the pre-Java 5 days.) | Counting the number of occurrences of each item in a list | [
"",
"java",
"data-structures",
"collections",
""
] |
I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits
```
Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc.
Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD
Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH
Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems
Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc
Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems
Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH
Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems
Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard
Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc
Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems
```
What would be the best way to sort this correctly on the first field, so that this sample would read
```
Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc.
Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems
Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems
Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH
Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems
Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard
Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETT PACKARD
Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH
Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems
Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc
Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc
```
My efforts have been very messy, and resulted in numbers such as 12 coming before 5!
As ever, many thanks for your patience. | ```
def lineKey (line):
keyStr, rest = line.split(' ', 1)
a, b = keyStr.split('/', 1)
return (a, int(b))
sorted(lines, key=lineKey)
``` | to sort split each line such that you have two tuple, part before / and integer part after that, so each line should be sorted on something like ('Gi6', 12), see example below
```
s="""Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc.
Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD
Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH
Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems
Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc
Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems
Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH
Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems
Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard
Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc
Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems"""
lines = s.split("\n")
def sortKey(l):
a,b = l.split("/")
b=int(b[:2].strip())
return (a,b)
lines.sort(key=sortKey)
for l in lines: print l
``` | compound sorting in python | [
"",
"python",
"sorting",
""
] |
I am accessing a link on my site that will provide a new image each time it is accessed.
The issue I am running into is that if I try to load the image in the background and then update the one on the page, the image doesn't change--though it is updated when I reload the page.
```
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
number++;
newImage.src = "http://localhost/image/id/image.jpg?time=" + new Date();
}
setTimeout(updateImage, 1000);
}
```
Headers as FireFox sees them:
```
HTTP/1.x 200 OK
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: image/jpeg
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Server: Microsoft-HTTPAPI/1.0
Date: Thu, 02 Jul 2009 23:06:04 GMT
```
I need to force a refresh of just that image on the page. Any ideas? | What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.
E.g.
```
http://localhost/image.jpg
//and
http://localhost/image01.jpg
```
will request the same image generation code but it will look like different images to the browser.
```
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
}
setTimeout(updateImage, 1000);
}
``` | Try adding a cachebreaker at the end of the url:
```
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
```
This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache. | Refresh image with a new one at the same url | [
"",
"javascript",
"image",
"url",
"refresh",
""
] |
What is faster?
out.writeObject(someString) or out.writeUTF(someString) | I wrote a test case, and writeObject is faster. One possible reason is because "Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream." See the writeObject documentation.
EDIT: However, writeUnshared is still faster than writeUTF,
```
100000 runs of writeObject: 464
100000 runs of writeUnshared: 5082
100000 runs of writeUTF: 7541
import java.io.*;
public class WriteString
{
private static int RUNS = 100000;
private static int STR_MULTIPLIER = 100;
public static void main(String[] a) throws Throwable
{
StringBuilder builder = new StringBuilder(26 * STR_MULTIPLIER);
for(int i = 0; i < STR_MULTIPLIER; i++)
{
builder.append("abcdefghijklmnopqrstuvwxyz");
}
String str = builder.toString();
File f = new File("oos");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
long startObject = System.currentTimeMillis();
for(int i = 0; i < RUNS; i++)
{
oos.writeObject(str);
oos.flush();
}
long endObject = System.currentTimeMillis();
System.out.println(RUNS + " runs of writeObject: " + (endObject - startObject));
long startUnshared = System.currentTimeMillis();
for(int i = 0; i < RUNS; i++)
{
oos.writeUnshared(str);
oos.flush();
}
long endUnshared = System.currentTimeMillis();
System.out.println(RUNS + " runs of writeUnshared: " + (endUnshared - startUnshared));
long startUTF = System.currentTimeMillis();
for(int i = 0; i < RUNS; i++)
{
oos.writeUTF(str);
oos.flush();
}
long endUTF = System.currentTimeMillis();
System.out.println(RUNS + " runs of writeUTF: " + (endUTF - startUTF));
oos.close();
f.delete();
}
}
``` | There are two things I want people to learn from this quesiton: Java Serialisation is slow - live with it. Microbenchmarks are worse than failure.
Microbenchmarks tend to be misleading. There are some things that are worth doing as a general idiom (for instance, hoisting strlen out of loop in C). Optimisers have a habit of breaking microbenchmarks. Take your application and profile it under real load. If a piece of code is causing your program to slow down, don't bother to optimise it. Microbenchmarks will not help you find these places.
writeObject and writeUTF don't do the same thing. writeObject indicates what type of object it is going to write. Also writeObject just writes a back reference if the same object (string) has been written since the last reset. writeUnshared is closer to writeUTF.
So if you continue to write exactly the same long String writeObject should win because it just needs to write a back reference. Reducing serialised size may reduce file/network bandwidth or just memory, which may result in more significant performance improvements. For short strings, just writing out the data will be faster. writeUnshared should give almost writeUTF performance, but maintaining generality.
Note, in all cases that data is written as UTF-8 not UTF-16. If you want UTF-16 `String.toCharArray` or similar will do. | Java writeObject Vs. writeUTF | [
"",
"java",
"stream",
""
] |
In C++, it is legal to give an implementation of a pure virtual function:
```
class C
{
public:
virtual int f() = 0;
};
int C::f()
{
return 0;
}
```
Why would you ever want to do this?
Related question: The [C++ faq lite](http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.13) contains an example:
```
class Funct {
public:
virtual int doit(int x) = 0;
virtual ~Funct() = 0;
};
inline Funct::~Funct() { } // defined even though it's pure virtual; it's faster this way; trust me
```
I don't understand why the destructor is declared pure virtual and then implemented; and I don't understand the comment why this should be faster. | Declared destructors must always be implemented as the implementation will call them as part of derived object destruction.
Other pure virtual functions may be implemented if they provide a useful common functionality but always need to be specialized. In the case, typically derived class implementations will make an explicit call to the base implementation:
```
void Derived::f()
{
Base::f();
// Other Derived specific functionality
}
```
Typically, you make a destructor virtual if you need to make a class abstract (i.e. prevent non-derived instances from being created) but the class has no other functions that are naturally pure virtual. I think the 'trust me it's faster' is refering to the fact that because destructors called as part of derived object clean up don't need to use a vtable lookup mechanism, the inline implementation can be taken advantage of, unlike typical virtual function calls. | Just found out that Herb Sutter answered the first part of this question in his [Guru of the Week #31](http://www.gotw.ca/gotw/031.htm). | Under what circumstances is it advantageous to give an implementation of a pure virtual function? | [
"",
"c++",
"performance",
"pure-virtual",
""
] |
I am doing some byte[] comparisons.
I tried == but this is just like the base Equals, which:
```
byte[] a = {1,2,3};
byte[] b = {1,2,3};
bool equals = a == b; //false
equals = a.Equals(b); //false
```
I tried to add an extension method, but since the overloaded base class' Equals takes the same arguments, it goes to the base method rather to the extension, is there anyway I can use an Equals extension (wthout changing it's name...) or (even better) use == operator?
Here is what I actually have to Compare:
```
public static bool ContentEquals(this byte[] array, byte[] bytes)
{
if (array == null || bytes == null) throw new ArgumentNullException();
if( array.Length != bytes.Length) return false;
for (int i = 0; i < array.Length; i++)
if (array[i] != bytes[i]) return false;
return true;
}
``` | ```
using System.Linq;
byte[] a = {1,2,3};
byte[] b = {1,2,3};
bool same = a.SequenceEqual(b);
``` | You certainly can't do operator overloading with extension methods. The reason it doesn't work for the `Equals` method is that if *any* method is applicable without using extension methods, that method will be chosen before extension methods are even examined.
Even though your `Equals` method is "better" in terms of converting the argument types to the formal parameter types, the compiler always prefers "normal" methods. You'll have to give your method a different name.
However, you can always use the `Enumerable.SequenceEquals` method. I don't believe that short-circuits the length check though (even though it could, for `ICollection<T>` implementations). You could always implement a more efficient version yourself though. Indeed, if you just change your existing array implementation to be called `SequenceEquals` or even `ArrayEquals`, that would be fine:
```
public static bool ArrayEquals(this byte[] array, byte[] bytes)
{
// I'd personally use braces in all of this, but it's your call
if (array.Length != bytes.Length) return false;
for (int i = 0; i < array.Length; i++)
if (array[i] != bytes[i]) return false;
return true;
}
```
Note that it would be quite nice to make it generic, but that would certainly cost a bit of performance as the comparison couldn't be inlined:
```
public static bool ArrayEquals<T>(this T[] first, T[] second)
{
// Reference equality and nullity checks for safety and efficiency
if (first == second)
{
return true;
}
if (first == null || second == null)
{
return false;
}
if (first.Length != second.Length)
{
return false;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < first.Length; i++)
{
if (!comparer.Equals(first[i], second[i]))
{
return false;
}
}
return true;
}
``` | I want to have an Extension method "Equals" between 2 byte arrays | [
"",
"c#",
"comparison",
"binary",
"arrays",
"equality",
""
] |
Can a caught `std::exception`'s `what()` return `NULL`?
Is the checking for `e.what()` below necessary?
```
// ...
}
catch (const std::exception& e)
{
std::string error;
if(e.what())
error = e.what();
}
``` | The contents of the string is implementation defined, so I guess the answer is yes.
**Edit:** Belay that. The standard says:
```
virtual const char* what() const throw();
5 Returns: An implementation-defined NTBS.
```
So it must return a string, not just a pointer. And a string cannot be `NULL`. As others have pointed out it is easy to derive exceptions whose `what()` does return `NULL`, but I'm not sure how such things fit into standards conformance. Certainly, if you are implementing what() in your own exception class, I would consider it very bad practice to allow it to return NULL.
**More:**
For a further question addressing whether `what()` can return NULL, and similar exciting issues, please see [Extending the C++ Standard Library by inheritance?](https://stackoverflow.com/questions/1073958/extending-the-c-standard-library-by-inheritance) | If someone has inherited from std::exception and overridden what to return NULL, then this is possible.
```
class CMyException : public std::exception
{
...
virtual const char * what () const {return NULL;}
};
```
Despite Neil's excellent find in the standard, It might still be good to check for NULL. Although the specifications of what child classes of std::exception state they should not return a NULL, nothing in your compiler is going to enforce this and the above code will still be legal according to the language.
This may be an ideal situation to use an assert...
```
assert(except.what() != NULL);
```
or
```
if (except.what() != NULL)
{
... normal processing ...
}
else
{
assert(false);
}
```
because this is a case where something probably should never ever happen, and you are assuming it shouldn't happen, but would still like to know (in debug mode) when your assumptions are shown to be wrong. Then you can either address your incorrect assumption or address the incorrect code which may be going against your assumption (make sure what() doesn't return NULL). | Can what() return NULL for exceptions? | [
"",
"c++",
"exception",
"inheritance",
""
] |
I have a web page where I want to switch the background image of a div in response to user interaction. What I have so far is:
```
function updateImg() {
imgurl=buildImgURL(); // constructs a URL based on various form values
$('#mainImage').css("background-image", "url("+imgurl+")");
}
```
This works exactly like I want it to except for one thing. Due to a combination of relatively large background images and a relatively slow server (neither of which can easily be fixed) it takes a while for the image to load. So when the updateImg() function is called the div goes white for half a second or so before the new background image is loaded. What I want is for the old background image to remain until the new image is finished loading and then to switch instantly. Is this possible to do?
The background image is generated on the fly by the server so any sort of client side caching or preloading isn't possible. | What about setting the image to an empty element?
```
$("<img id='loaderImg' src='"+imgUrl+"' onload='setBg(this.src)'/>");
```
Then when the image is loaded
```
function setBg(imgUrl) {
$("#mainImage").css("background-image", "url("+imgUrl+")");
$("#loaderImg").remove();
}
```
This way, the image would be loaded into an image that will never be displayed, and set to the background when the image is fully loaded (and also cached)
Haven't tested this, but I think it should work. | You could define a CSS class with the background-image property set to the image, and then in your updateImg() function, set the class of that div instead of directly modifying the property. This might alleviate the problem.
Something like:
```
function updateImg() {
imgurl=buildImgURL(); // constructs a URL based on various form values
$('#mainImage').addClass('imageClassName');
}
```
And then in your CSS:
```
.imageClassName {
background-image: url([url to image]);
}
``` | loading image before switching div background in jquery | [
"",
"javascript",
"jquery",
""
] |
I am currently developing a program that uses C#'s Dictionary container (specifically, SortedDictionary). This container works very well for my purposes except for one specific case because I want random access. Specifically, I am generating a random position using a pseudorandom number generator and I need to be able to access that value in the SortedDictionary. At the point that this happens, I do not have a key value.
I could potentially switch to a List which would solve this problem, but would create problems in the rest of the algorithm where SortedDictionary works quite well. Any suggestions/solutions would be much appreciated.
I am currently developing Visual Studio 2005.
Thank you. | ```
public TValue GetRandomElement<TKey, TValue>(SortedDictionary<TKey, TValue> dict)
{
Random randGen = new Random();
int randIndex = randGen.Next(dict.Values.Count);
int i = 0;
foreach (TValue value in dict.Values)
{
if (i++ == randIndex)
return value;
}
// this shouldn't happen unless I have a bug above or you are accessing the dictionary from multiple threads
return default(TValue);
}
```
Blindly enumerating the ValueCollection is not the most efficient thing in the world. But it gets the job done. If this is a frequent operation in your scenario, you should consider a hybrid data structure that has the performance characteristics needed for both dictionary lookup and random access. | You can use a SortedList and it has a Values collection which you may access through an integer index. | Random Access by Position of Key/Value Pairs in .NET (C#) | [
"",
"c#",
".net",
".net-2.0",
"dictionary",
""
] |
I kind of feel like I'm abusing the DOM with my code...
```
for(var i=0; i<json.length; ++i){
var newobj = document.createElement("div");
var inner = "<img src='"+json[i].picture+"' alt='Item preview' class='icon' />";
inner += "<p>"+json[i].id+"<br />qty:"+json[i].qty;
inner += "<a href=\"javascript:clearProduct('"+json[i].id+"')\">";
inner += "<img alt='Seperator' src='images/form-sep.gif' />";
inner += "<img src='images/cross.png' alt='Remove this item.' title='Remove this item.' />";
inner += "</a></p>";
newobj.innerHTML = inner;
newobj.className = "cart_item";
$('cartitems').appendChild(newobj);
$('cartcount').innerHTML = json.length;
}
```
Is there a better way to do this? I mean, yes I could through and use createElement for each element and setting each attribute separately but that seems like a lot just when this is so simple. Is there a better way? | I like to create a nice element-creation interface; something like this:
```
function el( name, attrs ) {
var elem = document.createElement(name),
styles = attrs.style;
for (var prop in styles) {
try {
elem.style[prop] = styles[prop];
} catch(e) {}
}
for (var attr in attrs) {
if (attr === 'style') { continue; }
elem[attr] = attrs[attr];
}
return elem;
}
var myImage = el('img', {
src: '/path/to/image.jpg',
alt: 'Really cool image',
style: {
border: '1px solid red',
padding: '10px'
}
});
``` | I don't know prototype, but I usually build my objects in jQuery like this :
```
$("<p>").append(
$("<img>")
.attr("alt", "Sperator")
.attr("src", "images/form-sep.gif")
).append(
$("<img>")
... etc ...
)
``` | Alternative to innerHTML | [
"",
"javascript",
"ajax",
"json",
"prototypejs",
""
] |
The library I'm using has class G and class S which inherits G.
I needed to add functionality to them, so I wrapped G and S, rather I inherited from them making Gnew and Snew respectively.
So, my inheritance is:
```
G --> Gnew
|
v
S --> Snew
```
But, I want to *use* Gnew in Snew and when I try to include the Gnew header (in the Snew implementation file) to use it ... the include guards mask the definition of Gnew in Snew???
How can I use Gnew in Snew? Right now, the compiler wont even let me forward declare Gnew in the Snew definition file (which doesn't make sense to me) unless I forward declare inside the class.
In Snew (if I forward declare before the Snew definition) I have:
```
...
Gnew *g;
```
The error is:
```
error: ISO C++ forbids declaration of ‘Gnew’ with no type
```
If I change Snew to say:
```
...
class Gnew *g;
Gnew *g;
```
The error is:
```
error: invalid use of undefined type ‘struct Snew::Gnew’
```
NOTE:
I was trying to abstract the problem, so I'm closing this and reopening a better phrasing of the question ... | Where's the cycle? And why would Gnew include the header of Snew?
[Edit]
OK, I think your inheritance arrows are opposite of what's customary. But this should get you sorted out:
In Gnew.h:
```
#pragma once
#if !defined(Gnew_h)
#define Gnew_h
#include "G.h"
class Gnew : public virtual G
{
// added functionality here.
};
#endif // Gnew_h
```
In Snew.h:
```
#pragma once
#if !defined(Snew_h)
#define Snew_h
#include "S.h"
#include "Gnew.h"
class Snew : public virtual Gnew, public virtual S
{
// added functionality here.
};
#endif // Snew_h
```
You should not have to forward declare anything.
*Note however that this only works as expected if S inherits virtually from G.* If all these multiple inheritance issues are too much trouble, you should probably just adapt the library classes instead of inheriting from them.
Does this help? | Do not include header files into header files when they aren't needed. Just forward declare the type you want to use and include the header file in the .cpp file that needs to know about the implementation of that type (Gnew in this case). The header file doesn't need this information.
```
// snew.h
// forward declare Gnew
class Gnew;
class Snew : public S
{
Gnew* gnew;
};
// snew.cpp
#include "gnew.h"
// ..
```
I dont see the point in using multiple and virtual inheritance. First you have a normal simple inheritance chain like this: G -> S -> Snew. And you want to use Gnew in S but you send G into the constructor of S and do a dynamic\_cast to Gnew. Why dont you just send in Gnew directly into the constructor of S? Like this:
```
SteadyStateDBGA(const Genome& g, const std::string& rootD,
const std::string& parName);
``` | Inheritance issue when wrapping (inheriting) from a C++ library | [
"",
"c++",
"inheritance",
"include",
""
] |
I have some javascript that goes out and fetches a javascript "class" on another xhtml page. The remote javascript looks something like the following:
```
(function() {
this.init = function() {
jQuery("#__BALLOONS__tabs").tabs();
};
})
```
After this is fetched into this.javascript, I try to eval it and instantiate:
```
this.javascript = eval("(" + this.javascript + ")");
this.javascript = new this.javascript();
this.javascript.init();
```
Of course, this works perfectly in all browsers except IE. In IE, it fails at the eval line. Does anyone have suggestions on how I can make this work in IE or an alternative.
Thanks, Pete | Have you tried:
```
eval("this.javascript = (" + this.javascript + ")");
```
...? | This worked with good browsers and bad ones (which means ie) :
```
var code_evaled;
function eval_global(codetoeval) {
if (window.execScript)
window.execScript('code_evaled = ' + '(' + codetoeval + ')',''); // execScript doesn’t return anything
else
code_evaled = eval(codetoeval);
return code_evaled;
}
```
Enjoy | How can I get this eval() call to work in IE? | [
"",
"javascript",
"jquery",
"eval",
""
] |
I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve.
Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them in one of two possible ways: one are "common" categories, which are in a many-to-many relationship: they are predefined, and each Site can relate to zero or more of the Categories, and vice versa. The other type of categories are individually defined for each site, and one such category "belongs" only to that site and none other; i.e. they are in a many-to-one relationship, as each Site may have a number of those Categories.
Internally, those two type of Categories are completely identical, they only differ in the way they are related to the Sites. It could, however, separate them in two different models (with a common parent model probably), but that solves only half of my problem: the Item model is in a many-to-one relationship with the Categories, i.e. each Item belongs to only one Category, and ideally it shouldn't care how it is related to a Site.
Another solution would be to allow the two separate types of Site-Category relations to coexist (i.e. to have both a ForeignKey and a ManyToMany field on the same Category model), but this solution feels like opening a whole other can of worms.
Does anyone have an idea if there is a third, better solution to this dead end? | Why not just have both types of category in one model, so you just have 3 models?
```
Site
Category
Sites = models.ManyToManyField(Site)
IsCommon = models.BooleanField()
Item
Category = models.ForeignKey(Category)
```
You say "Internally, those two type of Categories are completely identical". So in sounds like this is possible. Note it is perfectly valid for a ManyToManyField to have only one value, so you don't need "ForeignKey and a ManyToMany field on the same Category model" which just sounds like a hassle. Just put only one value in the ManyToMany field | As as alternative implementation you could use django content types (generic relations) to accomplish the connection of the items. A bonus for using this implementation is that it allows you to utilize the category models in different ways depending on your data needs down the road.
You can make using the site categories easier by writing model methods for pulling and sorting categories. Django's contrib admin also supports the generic relation inlines.
Your models would be as follow:
```
Site(models.Model):
label = models.CharField(max_length=255)
Category(models.Model):
site = models.ManyToManyField(Site)
label = models.CharField(max_length=255)
SiteCategory(models.Model):
site = models.ForeignKey(Site)
label = models.CharField(max_length=255)
Item(models.Model):
label = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
```
For a more in depth review of content types and how to query the generic relations you can read here: [<http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/>](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/) | Modeling a complex relationship in Django | [
"",
"python",
"django",
"django-models",
"entity-relationship",
""
] |
I'm writing a class in C++ that I cannot debug by using F5. The code will run from another "service" that will invoke it.
In the past I've used `__debugbreak()` and when I got a window telling me that an exception was thrown selected to debug it.
Recently I've updated to windows 7 and it kept working for a while.
Today when I've tried to debug a piece of my code instead of shown the regular dialog that tells me that VSTestHost has stopped working and enable me to to debug the application I got a different dialog suggesting I send the data to microsoft for analysis.
Does anyone knows how can I fix this issue so I'll be able to debug my code? | Finally I found the cause of the issue.
It's a Vista/Win7 cause:
1. Open The Action center control
2. Goto Action Center settings
3. Goto Problem Reporting Settings
4. Choose "Each time a problem occurs, ask me before checking for solution"
Although this is more of IT solution/question I've been plagued with this problem all day and wanted to share the solution with other developers who encounter this problem. | I finally found the solution for Windows 10/11 here:
<https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/enabling-postmortem-debugging>
And also: <https://learn.microsoft.com/en-us/windows/desktop/Debug/configuring-automatic-debugging>
To enable automatic debugger launch, you should add a registry value:
* key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug`, value `Auto` = `1` (of type `REG_DWORD`)
The configured debugger is set the by the value `Debugger` (type `REG_SZ`); a Visual Studio installation sets this to:
```
"C:\WINDOWS\system32\vsjitdebugger.exe" -p %ld -e %ld
```
Note that on 64 bit OS this only works for **64 bit** executables. To enable the same behaviour in **32 bit** executables set the same values in this key:
* `HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug` | DebugBreak not breaking | [
"",
"c++",
"windows",
"debugging",
"windows-7",
""
] |
How do you get the length of a string in jQuery? | You don't need jquery, just use `yourstring.length`. See reference [here](https://www.w3schools.com/jsref/jsref_length_string.asp) and also [here](http://www.quirksmode.org/js/strings.html).
**Update**:
To support unicode strings, length need to be computed as following:
```
[...""].length
```
or create an auxiliary function
```
function uniLen(s) {
return [...s].length
}
``` | The easiest way:
```
$('#selector').val().length
``` | How do you get the length of a string? | [
"",
"javascript",
"jquery",
"string-length",
""
] |
I have the following existing classes:
```
class Gaussian {
public:
virtual Vector get_mean() = 0;
virtual Matrix get_covariance() = 0;
virtual double calculate_likelihood(Vector &data) = 0;
};
class Diagonal_Gaussian : public Gaussian {
public:
virtual Vector get_mean();
virtual Matrix get_covariance();
virtual double calculate_likelihood(Vector &data);
private:
Vector m_mean;
Vector m_covariance;
};
class FullCov_Gaussian : public Gaussian {
public:
virtual Vector get_mean();
virtual Matrix get_covariance();
virtual double calculate_likelihood(Vector &data);
private:
Vector m_mean;
Matrix m_covariance;
};
```
As you see, the class Gaussian acts as an interface but doesn't have any implementation. This is all working fine.
Now I want to make an class "AdaptedGaussian" where the data vector provided to the calculated\_likelihood will be changed before the likelihood is calculated.
Some requirements:
* The AdaptedGaussian must be a child-class of Gaussian
* AdaptedGaussian must be able to "wrap" or "be an instance of" every possible Gaussian class
* AdaptedGaussian must be constructed from an already existing Gaussian Object
The idea I have now is:
```
class Adapted_Gaussian : public Gaussian {
private:
Gaussian* m_g;
public:
virtual Vector get_mean() { return m_g->get_mean(); }
virtual Matrix get_covariance() { return m_g->get_covariance(); }
virtual double calculate_likelihood(Vector &data)
{
//do something with data
return g->calculate_likelihood(Vector &data);
}
}
```
There are maybe some disadvantages:
* For every method (and there are more than showed here) a dummy method must be written in the new class
* If Gaussian is ever extended, and this class would be forgotten, nasty bugs can appear.
Am I doing this in the right way? Or are there better methods to implement this?
Is there maybe a good way to standard delegate every non-implemented method to the same named method of m\_g? | Looks good, I think this is a pretty classic implementation of the Adapter pattern. Just don't forget to declare a virtual destructor for your Gaussian class. As for the disadvantages.
1. The way Java class library deal with the dummy method problem is to create a dummy class that provides empty implementation for every single method. All classes that do not want to implement every single method can just inherit from this dummy class and selectively override methods that interests them.
2. If you extend your Gaussian class with few more methods, as long as you declare them as pure virtual method you will get a compiler error in your child class file anyway. | As you point out writing a lot of basic pass-through functions is tedious and adds an implied maintenance overhead. Also, having a pointer member implies extra (albeit simple) lifetime management issues of the owned pointer. Probably the simplest way to address these issues is to make AdaptedGaussian a template, templated on the specific instance of Gaussian to be adapted.
```
template<class BaseGaussian> class AdaptedGaussian : public BaseGaussian
{
virtual double calculate_likelihood(Vector &data)
{
// do something with data
return BaseGaussian::calculate_likelihood(Vector &data);
}
};
```
This does rely on all adapted instances of Gaussian being default constructible, or at least conforming to a common constructor signature.
If you want to construct an `AdaptedGaussian` from an existing `XXXGaussian`, then so long as the `XXXGaussian` is itself copyable you can add a suitable constructor:
```
template<class BaseGaussian> class AdaptedGaussian : public BaseGaussian
{
public:
AdaptedGaussian(const BaseGaussian& other) : BaseGaussian(other)
{
}
// ...
};
``` | Implementing complex inheritance in C++ | [
"",
"c++",
"inheritance",
""
] |
I'm not sure if there is a proper term for what I want to because any I've tried in google haven't bought anything up.
Basically, on an application crash I would like to perform a final action to clean up database record locking.
I would also like to catch this when debugging is stopped using the stop button, as I understand it using the stop button is very different to exiting your application by a normal process in your application.
Is there a normal way for achieving what I'm trying to do? The application is a C#, .NET 3.5 Windows Forms Application written in VS2008.
Cheers | You can't do anything within a process after it's killed.
Your only way to achieve what you want would be to have a second process that watched for the first one dying, and then did the cleanup on its behalf.
You have to worry about the second process crashing, or being killed, and so on. Not easy to make it work in all conceivable cases, but a lot better than nothing. | The answer to your first requirement is to have (at it's most basic):
```
try
{
// Main application
}
catch // Though you might not want this
{
}
finally
{
// This code always executed even if application crashes.
}
```
However there are other considerations when dealing with Windows applications as RichardOD indicates in his comments here - <http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx> and here <http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx>
The answer to your second requirement is no you can't trap the application being stopped in the debugger (or at least there's not a way I've come across). It just kills the process.
For instance if you have stopped at a break point and then press stop the code doesn't carry on executing to termination - it just exits.
The same is true if the application stops due to some external factor like the power being turned off. In scenarios like this there's no way that the program can execute *any* code whether it's in a finally block or not!
However, I've just come across this question [Visual Studio : executing clean up code when debugging stops](https://stackoverflow.com/questions/1033441/visual-studio-executing-clean-up-code-when-debugging-stops) which has an answer that states:
> You can use the DTE (VisualStudio
> Automation Model) to write a macro
> that will be invoked when a stop debug
> happens, below is a snippet of the
> idea.
```
Private Sub DebuggerEvents_OnEnterDesignMode(ByVal Reason As EnvDTE.dbgEventReason, ByRef ExecutionAction As EnvDTE.dbgExecutionAction) Handles DebuggerEvents.OnEnterDesignMode
If (Reason = dbgEventReason.dbgEventReasonStopDebugging) Then
// DO YOUR CLEAN UP CODE HERE
End If
End Sub
```
So while you can't trap the stopping of the execution in your application you can do something about it in Visual Studio.
NOTE: Answer provided by [Shay Erlichmen](https://stackoverflow.com/users/48387/shay-erlichmen) not me! | C# Perform one last action on application crash | [
"",
"c#",
"exception",
""
] |
Why is it that in C++ containers, it returns a `size_type` rather than an `int`? If we're creating our own structures, should we also be encouraged to use `size_type`? | In general, `size_t` should be used whenever you are measuring the size of something. It is really strange that `size_t` is only required to represent between 0 and `SIZE_MAX` bytes and `SIZE_MAX` is only required to be 65,535...
The other interesting constraints from the C++ and C Standards are:
* the return type of `sizeof()` is `size_t` and it is an *unsigned integer*
* `operator new()` takes the number of bytes to allocate as a `size_t` parameter
* `size_t` is defined in `<cstddef>`
* `SIZE_MAX` is defined in `<limits.h>` in C99 but not mentioned in C++98?!
* `size_t` is not included in the list of *fundamental integer types* so I have always assumed that `size_t` is a type alias for one of the fundamental types: `char`, `short int`, `int`, and `long int`.
If you are counting bytes, then you should definitely be using `size_t`. If you are counting the number of elements, then you should probably use `size_t` since this seems to be what C++ has been using. In any case, you don't want to use `int` - at the very least use `unsigned long` or `unsigned long long` if you are using TR1. Or... even better... `typedef` whatever you end up using to `size_type` or just include `<cstddef>` and use `std::size_t`. | A few reasons might be:
* The type (size\_t) can be defined as the largest unsigned integer on that platform. For example, it might be defined as a 32 bit integer or a 64 bit integer or something else altogether that's capable of storing unsigned values of a great length
* To make it clear when reading a program that the value is a size and not just a "regular" int
If you're writing an app that's just for you and/or throwaway, you're probably fine to use a basic int. If you're writing a library or something substantial, size\_t is probably a better way to go. | size_t vs int in C++ and/or C | [
"",
"c++",
"c",
"size-type",
""
] |
I'm writing a JNI application and I want the app to download the correct binary library for the current architecture. Is there any way to retrieve this information from code?
I need to know where it's ARM, x86 or any other architecture really.
Kind regards,
Gavin | `java.lang.System.getProperty("os.arch")` should help -- giving "arm", "amd64", and the like. | ```
System.getProperty("os.arch")
```
<http://www.roseindia.net/java/beginners/OSInformation.shtml> | Retrieve Architecture from Java | [
"",
"java",
"architecture",
"system",
""
] |
Listing all files in a drive other than my system drive throws an `UnauthorizedAccessException`.
How can I solve this problem?
Is there a way to grant my application the access it needs?
---
### My code:
```
Directory.GetFiles("S:\\", ...)
``` | I solved the problem. Not really but at least the source.
It was the SearchOption.AllDirectories option that caused the exception.
But when I just list the immediate files using Directories.GetFiles, it works.
This is good enough for me.
Any way to solve the recursive listing problem? | Here's a class that will work:
```
public static class FileDirectorySearcher
{
public static IEnumerable<string> Search(string searchPath, string searchPattern)
{
IEnumerable<string> files = GetFileSystemEntries(searchPath, searchPattern);
foreach (string file in files)
{
yield return file;
}
IEnumerable<string> directories = GetDirectories(searchPath);
foreach (string directory in directories)
{
files = Search(directory, searchPattern);
foreach (string file in files)
{
yield return file;
}
}
}
private static IEnumerable<string> GetDirectories(string directory)
{
IEnumerable<string> subDirectories = null;
try
{
subDirectories = Directory.EnumerateDirectories(directory, "*.*", SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (subDirectories != null)
{
foreach (string subDirectory in subDirectories)
{
yield return subDirectory;
}
}
}
private static IEnumerable<string> GetFileSystemEntries(string directory, string searchPattern)
{
IEnumerable<string> files = null;
try
{
files = Directory.EnumerateFileSystemEntries(directory, searchPattern, SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (files != null)
{
foreach (string file in files)
{
yield return file;
}
}
}
}
```
You can the use it like this:
```
IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(@"C:\", "*.txt");
foreach (string fileOrDirectory in filesOrDirectories)
{
// Do something here.
}
```
It's recursive, but the use of yield gives it a low memory footprint (under 10KB in my testing). If you want only files that match the pattern and not directories as well just replace `EnumerateFileSystemEntries` with `EnumerateFiles`. | Solving UnauthorizedAccessException issue for listing files | [
"",
"c#",
".net",
"security",
"exception",
""
] |
I've done the other way around (calling pure C++ code from .NET) with C++/CLI, and it worked (for the most part).
How is the native-to-C++/CLI direction done?
I really don't want to use COM interop... | You can always [host the CLR](http://msdn.microsoft.com/en-us/magazine/cc163567.aspx) in your native app. | If you have an existing native C++ app and want to avoid "polluting" it with too much CLR stuff, you can switch on the `/clr` flag for just one specific file and use a standard C++ header to provide an interface to it. I've done this in an old bit of code. In the header I have:
```
void SaveIconAsPng(void *hIcon, const wchar_t *pstrFileName);
```
So the rest of the program has a simple API to which it can pass an HICON and a destination filepath.
Then I have a separate source file which is the only one that has `/clr` switched on:
```
using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Imaging;
using namespace System::Drawing::Drawing2D;
#include <vcclr.h>
#include <wchar.h>
void SaveIconAsPng(void *hIcon, const wchar_t *pstrFileName)
{
try
{
Bitmap bitmap(16, 16, PixelFormat::Format32bppArgb);
Graphics ^graphics = Graphics::FromImage(%bitmap);
graphics->SmoothingMode = SmoothingMode::None;
Icon ^icon = Icon::FromHandle(IntPtr(hIcon));
graphics->DrawIcon(icon, Rectangle(0, 0, 15, 15));
graphics->Flush();
bitmap.Save(gcnew String(pstrFileName), ImageFormat::Png);
}
catch (Exception ^x)
{
pin_ptr<const wchar_t> unmngStr = PtrToStringChars(x->Message);
throw widestring_error(unmngStr); // custom exception type based on std::exception
}
}
```
That way I can convert HICONs into PNG files from my hairy old C++ program, but I've isolated the use of the .NET framework from the rest of the code - so if I need to be portable later, I can easily swap in a different implementation.
You could take this a stage further and put the CLR-dependent code in a separate DLL, although there would be little added value in that unless you wanted to be able to patch it separately. | Can C++/CLI be used to call .NET code from native C++ applications? | [
"",
".net",
"c++",
"interop",
"c++-cli",
""
] |
I have done this operation millions of times, just using the `+` operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:
```
["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
```
I want to discard the first and the last elements, the code is:
```
ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
```
Look at the output:
```
extract_the_info, lineList ["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
ediMsg : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 3
```
Why is it doing so!? | You should use the following and forget about this nightmare:
```
''.join(list_of_strings)
``` | While the two answers are correct (use " ".join()), your problem (besides *very* ugly python code) is this:
Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start *of the same line*, hence overwrite what was written on that line so far. | How to append two strings in Python? | [
"",
"python",
"string",
""
] |
I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following:
```
>>> re.split('-\d', 'foo-bar-1.23-4', 1)
['foo-bar', '.23-4']
```
and
```
>>> re.split('-(\d)', 'foo-bar-1.23-4', 1)
['foo-bar', '1', '.23-4']
```
with suboptimal results. Is there a one-liner that will get me what I want, without having to munge the delimiter with the last element? | You were very close, try this:
```
re.split('-(?=\d)', 'foo-bar-1.23-4', 1)
```
I am using [positive lookahead](http://www.regular-expressions.info/lookaround.html) to accomplish this - basically I am matching a dash that is immediately followed by a numeric character. | ```
re.split('-(?=\d)', 'foo-bar-1.23-4', 1)
```
Using [lookahead](http://docs.python.org/library/re.html), which is exactly what Andrew did but beat me by a minute... :-) | Context-sensitive string splitting, preserving delimiters | [
"",
"python",
"string",
"split",
""
] |
I've got a struts2 action that responds to an AJAX request by taking some request parameters, calling a remote service that returns XML data, then transforming the data via XSL and returning the resulting XHTML via a Stream Result. The response is different depending on the given parameters.
Here is the action class with a bunch of stuff taken out:
```
public class ServiceHandler extends ActionSupport {
private ByteArrayInputStream inputStream;
public String execute(){
String response = "";
// Get request parameters
// Make a request to a remote server via an http connection
// Transform result via XSL
//uses dom4j for XML/XSL stuff
//this should never be empty
response = resultDoc.asXML();
inputStream = new ByteArrayInputStream(response.getBytes());
return "success";
}
public ByteArrayInputStream getInputStream(){
return inputStream;
}
}
```
And here are the important struts.xml bits:
```
<action name="sh" class="ServiceHandler">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="contentDisposition">inline;filename="response.html"</param>
<param name="bufferSize">1024</param>
<param name="allowCaching">false</param>
</result>
</action>
```
My problem is that when I have multiple requests going at the same time, all calling the ServiceHandler action, sometimes the response is totally blank (should never happen), sometimes the response is cut off at the beginning or end by some random amount, and sometimes the responses are switched, so that the wrong response is received by a an AJAX requestor.
I know this is an issue of thread safety, and I've moved all important variable definitions into the execute() method so that they are not instance variables (and hence shared by all). The only interesting variable that is an instance variable is the inputStream, and I'm looking at that as the cause of my problems.
Is there a way to make the inputStream variable thread-safe? Or is there another solution I'm not seeing? | Thanks for Henning for leading me in the right direction. I hadn't thought of writing directly to the response output stream, as it isn't mentioned anywhere in struts2 documentation.
The benefit of writing the response directly to the output stream is that you don't need to create an instance object for inputStream. This keeps all data in the execute() method, which is safe from other threads.
Here is a modified action class that writes directly to the output stream and returns a null result.
```
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
public class ServiceHandler extends ActionSupport {
public String execute(){
String response = "";
// Get request parameters
// Make a request to a remote server via an http connection
// Transform result via XSL
//uses dom4j for XML/XSL stuff
//this should never be empty
response = resultDoc.asXML();
HttpServletResponse httpResponse = ServletActionContext.getResponse();
try{
httpResponse.getOutputStream().print(response);
}
catch(IOException e){
return "failure";
}
return null;
}
}
```
This appears to have fixed the issues I was having. | I'm familiar with Struts 1 only but take a look into DonwloadAction. Or just use a plain struts Action, write the result directly to the response object and return null as forward. | Handling many simultaneous AJAX requests with a struts2 action | [
"",
"java",
"multithreading",
"tomcat",
"struts2",
""
] |
My application throws 'Access denied' errors when writing temporary files in the installation directory where the executable resides. However it works perfectly well in Windows XP. How to provide access rights to Program Files directory in Windows 7?
EDIT:
How to make the program ask the user to elevate rights? (ie run program with full admin rights) | Your program should not write temporary files (or anything else for that matter) to the program directory. Any program should use %TEMP% for temporary files and %APPDATA% for user specific application data. This has been true since Windows 2000/XP so you should change your aplication.
The problem is not Windows 7.
You can ask for appdata folder path:
```
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
```
or for TEMP path
```
string dir = Path.GetTempPath()
``` | Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a [wiki](http://en.wikipedia.org/wiki/User_Account_Control#Requesting_elevation) on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".
However, I wouldn't suggest doing this. It would be better to use something like this:
```
Environment.GetFolderPath(SpecialFolder.ApplicationData);
```
to get the AppData Folder path and create a folder there for your app. Then put the temp files there. | Allow access permission to write in Program Files of Windows 7 | [
"",
"c#",
""
] |
I compress my own JS using YuiCompressor, but is there any reason why MicrosoftAjax.js not minified? Or is there some setting to say run the compressed version of it (if there is a compressed version). Or do I need to decompile it and minify the script resource myself? | I'm surprised at these misleading answers.
ASP.NET AJAX has always provided both debug and compressed versions of MicrosoftAjax.js. A combination of the web.config's debug setting and [ScriptManager's ScriptMode property](http://www.asp.net/Ajax/Documentation/Live/mref/T_System_Web_UI_ScriptMode.aspx) control which script is referenced.
Additionally, you may use [the "retail" setting](http://msdn.microsoft.com/en-us/library/system.web.configuration.deploymentsection.retail%28v=vs.110%29.aspx) to force compressed scripts regardless. | All the scripts in System.Web.Extensions are minified -- there are two versions of each, as Dave Ward's excellent answer points out. ScriptManager by default will use the debug version when the web.config is in debug mode. Flip it to release with the retail setting or debug="false", and look at the script then.
Also, scripts served through WebResourceHandler or ScriptResourceHandler are in fact cached. They are cached in the best possible way -- forever, so they don't even need to 301 on future visits. The querystring is as it is, because it contains encrypted data. It is encrypted because it contains information about the script resource, including an assembly name, and also because it prevents cache flooding attacks.
Not looking for rep here, just wanted to give more detail. | Is there any reason why MicrosoftAjax.js is not minified? | [
"",
"javascript",
"asp.net-ajax",
"minify",
""
] |
Okay I have a series of objects based on a base class which are stored randomly in a Dictionary object. e.g.
```
class TypeA
{
public int SomeNumber {get; set;}
public void SomeFunction()
}
class TypeB : TypeA
{
public string SomeString {get; set;}
}
class TypeC : TypeA
{
public bool StuffReady()
}
Dictionary listOfClasses <long, TypeA>;
```
The Key value is a running count of the number of objects that have ever been placed into the dictionary. It does not match the current Dictionary count.
I wish to locate an object of TypeB where its SomeString == "123" say, and remove it.
What would be the best way of doing this? | If you're sure that there will only be a single matching object (or if you only want to remove the first occurrence):
```
var found = listOfClasses.FirstOrDefault
(
x => (x.Value is TypeB) && (((TypeB)x.Value).SomeString == "123")
);
if (found.Value != null)
{
listOfClasses.Remove(found.Key);
}
```
If there could be multiple matching objects and you want to remove them all:
```
var query = listOfClasses.Where
(
x => (x.Value is TypeB) && (((TypeB)x.Value).SomeString == "123")
);
// the ToArray() call is required to force eager evaluation of the query
// otherwise the runtime will throw an InvalidOperationException and
// complain that we're trying to modify the collection in mid-enumeration
foreach (var found in query.ToArray())
{
listOfClasses.Remove(found.Key);
}
``` | There doesn't appear to be a mapping between the TypeA class and the Key of the Dictionary. The key is of type long and there is no property of that type on the class. So you'll have to search the collection of KeyValuePair instances which will give you direct access to the key.
Try the following
```
var found = listOfClasses
.Where(p => p.Value.SomeString == "123").
.Where(p => p.Value.GetType() == typeof(TypeB))
.Single();
listOfClasses.Remove(found.Key);
``` | Most efficient way to select a specific object type in Dictionary and delete it | [
"",
"c#",
"linq",
"collections",
""
] |
I'm using the Enerjy (<http://www.enerjy.com/>) static code analyzer tool on my Java code. It tells me that the following line:
System.err.println("Ignored that database");
is bad because it uses System.err. The exact error is: "JAVA0267 Use of System.err"
What is wrong with using System.err? | Short answer: It is considered a bad practice to use it for logging purposes.
It is an observation that in the old times when there where no widely available/accepted logging frameworks, everyone used System.err to print error messages and stack traces to the console. This approach might be appropriate during the development and local testing phase but is not appropriate for a production environment, because you might lose important error messages. Because of this, in almost all static analysis tools today this kind of code is detected and flagged as bad practice (or a similarly named problem).
Logging frameworks in turn provide the structured and logical way to log your events and error messages as they can store the message in various persistent locations (log file, log db, etc.).
The most obvious (and free of external dependencies) hack resolution is to use the built in Java Logging framework through the `java.util.logging.Logger` class as it forwards the logging events to the console by default. For example:
```
final Logger log = Logger.getLogger(getClass().getName());
...
log.log(Level.ERROR, "Something went wrong", theException);
```
(or you could just turn off that analysis option) | the descriptor of your error is:
> The use of System.err may indicate residual debug or boilerplate code. Consider using a
> full-featured logging package such as Apache Commons to handle error logging.
It seems that you are using System.err for logging purposes, that is suboptimal for several reasons:
* it is impossible to enable logging at runtime without modifying the application binary
* logging behavior cannot be controlled by editing a configuration file
* problably many others | What's wrong with using System.err in Java? | [
"",
"java",
"static-analysis",
"stderr",
""
] |
I find the nature of this question to be quite suited for the practical-minded people on Stack Overflow.
I'm setting out on making a rather large-scale project in Java. I'm not going to go into specifics, but it is going to involve data management, parsing of heterogeneous formats, and need to have an appealing interface with editor semantics. I'm a undergraduate student and think it would evolve into a good project to show my skill for employment -- heck, ideally it would even be the grounds for a startup.
I write to ask you what shortcuts I might not be thinking about that will help with a complicated project in Java. Of course, I am planning to go at it in Eclipse, and will probably use SWT for the GUI. However, I know that Java has the unfortunately quality of overcomplicating everything, and I don't want to get stuck.
Before you tell me that I want to do it in Python, or the like, I just want to reiterate why I would choose Java:
1. Lots more experience with algorithms in Java, and there will be quite a bit of those.
2. Want a huge library of APIs to expand functionality. ANTLR, databases, libraries for dealing with certain formats
3. Want to run it anywhere with decent performance
I am open-minded to all technologies (most familiar with Java, perl, sql, a little functional).
**EDIT**: *For the moment*, I am giving it to djna (although the low votes). I think all of your answers are definitely helpful in some respect.
I think djna hit better the stuff I need to watch out for as novice programmer, recognizing that I'm not taking shortcuts but rather trying not to mess up. As for the suggestions of large frameworks, esp. J2EE, that is way too much in this situation. I am trying to offer the simplest solution and one in which my API can be extended by someone who is not a J2EE/JDBC expert.
Thanks for bringing up Apache Commons, although I was already aware. Still confused over SWT vs. Swing, but every Swing program I've used has been butt ugly. As I alluded to in the post, I am going to want to focus most on the file interchange and *limited DB* features that I have to implement myself (but will be cautious -- I am aware of the concurrency and ACID problems).
Still a community wiki to improve. | There's getting the "project" completed efficiently and there are "short cuts". I suspect the following may fall into the "avoiding wasted effort" category rather be truly short cuts but if any of them get you to then end more quickly then I perhaps they help.
1). Decomposition and separation of concerns. You've already identified high-level chunks (UI, persistence layer, parser etc.). Define the interfaces for the provider classes as soon as possible and have all dependent classes work against those interfaces. Pay a lot of attention to the usability of those interfaces, make them easy to understand - names matter. Even something as simple as the difference between setShutdownFlag(true) and requestShutdown(), the second has explicit meaning and hence I prefer it.
Benefits: Easier maintenance. Even during initial development "maintenance" happens. You will want to change code you've already written. Make it easy to get that right by strong encapsulation.
2). Expect iterative development, to be refining and redesigning. Don't expect to "finish" any one component in isolation before you use it. In other words don't take a purely bottom up approach to developing your componenets. As you use them you find out more information, as you implement them you find out more about what's possible.
So enable development of higher level components especially the UI by mocking and stubbing low level components. Something such as JMock is a short-cut.
3). Test early, test often. Use JUnit (or equivalent). You've got mocks for your low level components so you can test them.
Subjectively, I feel that I write better code when I've got a "test hat" on.
4). Define your error handling strategy up front. Produce good diagnostics when errors are detected.
Benefits: Much easier to get the bugs out.
5). Following on from error handling - use diagostic debugging statements. Sprinkle them liberally throughout your code. Don't use System.out.println(), instead use the debugging facilities of your logging library - use java.util.logging. Interactive debuggers are useful but not the only way of analysing problems. | Learn/use [Spring](http://www.springsource.org/), and create your project so it will run *without* a Spring config (those things tend to run out of control), while retaining the possibility to configure the parameters of your environment in a later stage. You also get a uniform way to integrate other frameworks like Hibernate, Quartz, ...
And, in my experience, stay away from the GUI builders. It may seem like a good deal, but I like to retain control of my code all the time. | Java Time Savers | [
"",
"java",
"frameworks",
""
] |
How to cast an object (of type Object) into its real type?
I need to do some thing like this
```
Myobject [i] += Myobject [j];
```
Myobject's type is Object.
Myobject [i] and myobject [j] will always be of same type.
Myobject[i].Gettype() would give me the type... but how would i actually cast the object into that type to perform the '+' operator | I'm assuming the addition (`+`) operator is defined for your custom type (`MyType` in this example).
If so, you simply need to cast the LHS and RHS of the assignment. This is required because both operands must be of *known* types at compile-time in order to choose the correct operator overload. This is something required by static languages, though dynamic languages (possibly C# 4.0) may resolve this.
```
((MyType)Myobject[i]) += (MyType)Myobject[j];
```
**Update:**
Some reflection magic can get around this problem in C# 2.0/3.0 (with lack of dynamic typing).
```
public static object Add(object a, object b)
{
var type = a.GetType();
if (type != b.GetType())
throw new ArgumentException("Operands are not of the same type.");
var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public);
return op.Invoke(null, new object[] { a, b });
}
```
Note that this only works for *non-primitive types*. For primitive types such as `int`, `float`, etc., you would need to add a switch statement on the type that manually cast the operands and applied the addition operator. This is because operator overloads aren't actually defined for primitive types, but rather built in to the CLR.
Anyway, hope that solves your problem. | Is the type known at compile time?
C# does not (until C# 4.0) support operators on anything except known, fixed types.
You can use operators with *generics* via a few tricks - [like so](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html). Let me know if generics are a factor here (I can talk at length on this...)
In 4.0, you can use:
```
dynamic x = MyObject[i];
x += MyObject[j];
MyObject[i] = x;
```
The use of `dynamic` causes a lot of magic to happen ;-p
Other than those two scenarios, you need to know their type at compile-time, or do a *lot* of work. | How to cast an object into its type? | [
"",
"c#",
""
] |
I am a beginner and I cannot understand the real effect of the `Iterable` interface. | Besides what Jeremy said, its main benefit is that it has its own bit of syntactic sugar: the [enhanced for-loop](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html). If you have, say, an `Iterable<String>`, you can do:
```
for (String str : myIterable) {
...
}
```
Nice and easy, isn't it? All the dirty work of creating the `Iterator<String>`, checking if it `hasNext()`, and calling `str = getNext()` is handled behind the scenes by the compiler.
And since most collections either implement `Iterable` or have a view that returns one (such as `Map`'s `keySet()` or `values()`), this makes working with collections much easier.
The [`Iterable` Javadoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) gives a full list of classes that implement `Iterable`. | If you have a complicated data set, like a tree or a helical queue (yes, I just made that up), but you *don't care* how it's structured internally, you just want to get all elements one by one, you get it to return an iterator.
The complex object in question, be it a tree or a queue or a WombleBasket implements Iterable, and can return an iterator object that you can query using the Iterator methods.
That way, you can just ask it if it `hasNext()`, and if it does, you get the `next()` item, without worrying where to get it from the tree or wherever. | What is the Iterable interface used for? | [
"",
"java",
"iterable",
""
] |
In a C# desktop application, I have a customer widget which contains a text box. I also have a menu item on a menu strip that has the Delete key as its short-cut key. The behaviour I'm finding is that pressing delete in the text box, which the user will expect to delete a character, is actually triggering the menu item and deleting the whole object they are working on.
Is there any way to let the text box have "first crack" at handling the key press rather than the menu item?
Thanks. | Are you handling the delete key at the form level? Either way, you could check for the widget having focus and then not handle the event. Even better would be to not use delete as a global shortcut, this seems along the lines of reassigning what ctrl+c, alt+f4, or tab do. | **What we did**
The solution we ended up using was to disable those menu items, thereby disabling their respective short-cut keys, when the control that those menu items were intended to act upon.
This solved the problem where clicking delete in an unrelated text box deletes the selected item in the main widget. However, it introduces the problem that the user has to click on the main widget in order to access those menu items. To counter this a little bit, I did make it such that the main widget regains focus when the panel with the hideable widgets is hidden.
I'm not advocating this solution, just including it for completeness.
**What I would have liked**
My ultimate solution would be to only perform the action only if:
1. the main widget has focus, OR
2. the even was triggered via clicking the menu item
but there doesn't seem to be a way to detect whether the even was triggered by a short-cut key within the framework. | C# prevent Delete key on custom widget from triggering short-cut on menu | [
"",
"c#",
"visual-studio",
"user-interface",
""
] |
I have an SHA-1 byte array that I would like to use in a GET request. I need to encode this. `URLEncoder` expects a string, and if I create a string of it and then encode it, it gets corrupt?
To clarify, this is kinda a follow up to another question of mine.
([Bitorrent Tracker Request](https://stackoverflow.com/questions/1019454/bitorrent-tracker-request)) I can get the value as a hex string, but that is not recognized by the tracker. On the other hand, encoded answer mark provided return 200 OK.
So I need to convert the hex representation that I got:
```
9a81333c1b16e4a83c10f3052c1590aadf5e2e20
```
into encoded form
```
%9A%813%3C%1B%16%E4%A8%3C%10%F3%05%2C%15%90%AA%DF%5E.%20
``` | **Question was edited while I was responding, following is ADDITIONAL code and should work (with my hex conversion code):**
```
//Inefficient, but functional, does not test if input is in hex charset, so somewhat unsafe
//NOT tested, but should be functional
public static String encodeURL(String hexString) throws Exception {
if(hexString==null || hexString.isEmpty()){
return "";
}
if(hexString.length()%2 != 0){
throw new Exception("String is not hex, length NOT divisible by 2: "+hexString);
}
int len = hexString.length();
char[] output = new char[len+len/2];
int i=0;
int j=0;
while(i<len){
output[j++]='%';
output[j++]=hexString.charAt(i++);
output[j++]=hexString.charAt(i++);
}
return new String(output);
}
```
You'll need to convert the raw bytes to hexadecimal characters or whatever URL-friendly encoding they are using. Base32 or Base64 encodings are possible, but straight hexadecimal characters is the most common. URLEncoder is not needed for this string, because it shouldn't contain any characters that would require URL Encoding to %NN format.
The below will convert bytes for a hash (SHA-1, MD5SUM, etc) to a hexadecimal string:
```
/** Lookup table: character for a half-byte */
static final char[] CHAR_FOR_BYTE = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/** Encode byte data as a hex string... hex chars are UPPERCASE*/
public static String encode(byte[] data){
if(data == null || data.length==0){
return "";
}
char[] store = new char[data.length*2];
for(int i=0; i<data.length; i++){
final int val = (data[i]&0xFF);
final int charLoc=i<<1;
store[charLoc]=CHAR_FOR_BYTE[val>>>4];
store[charLoc+1]=CHAR_FOR_BYTE[val&0x0F];
}
return new String(store);
}
```
This code is fairly optimized and fast, and I am using it for my own SHA-1 byte encoding. Note that you may need to convert uppercase to lowercase with the String.toLowerCase() method, depending on which form the server accepts. | Use [Apache Commons-Codec](http://commons.apache.org/codec/userguide.html) for all your encoding/decoding needs (except ASN.1, which is a pain in the ass) | Java Encode SHA-1 Byte Array | [
"",
"java",
"encode",
"sha",
""
] |
I am trying to do a little bit of math using dates in PHP. I am modifying a shoutbox, and I want to implement the following functionality.
---
If post date = today, return time of post
else if date = yesterday, return "yesterday"
else date = X days ago
---
How would I use php's date functions to calculate how many days ago a timestamp is (the timestamp is formatted in UNIX time) | Try this:
```
$shoutDate = date('Y-m-d', $shoutTime);
if ($shoutDate == date('Y-m-d'))
return date('H:i', $shoutTime);
if ($shoutDate == date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'))))
return 'yesterday';
return gregoriantojd(date('m'), date('d'), date('y')) - gregoriantojd(date('m', $shoutTime), date('d', $shoutTime), date('y', $shoutTime)) . ' days ago';
``` | In php 5.3.0 or higher, you can use [DateTime::diff](http://www.php.net/manual/en/datetime.diff.php) (aka date\_diff()).
In pretty much any php, you can convert the dates to Unix timestamps and divide the difference between them by 86400 (1 day in seconds). | PHP Date Question | [
"",
"php",
"date",
""
] |
I'd like to get into ejb3 to gain some practice in writing for it.
I searched for tutorials and how-to's but could find some scarce unhelpful information.
I'm looking for a tutorial or walkthrough that will guide me from the very basics (Which software do I need to install?) to write a "Hello World" for EJB3 with JBoss.
In short - Where do I start?
Thanks! | It would make sense to start with JBoss Seam as it's an easy introduction into EJB3 (and JSF). Have a look at their "[Getting Started](http://www.seamframework.org/Documentation/GettingStarted)" page. | [EJB in Action](http://www.manning.com/panda/) is a **great** book | How do I start with EJB3 and JBoss? | [
"",
"java",
"jboss",
"ejb-3.0",
""
] |
I'm working on some SharePoint web parts and I'm trying to make them as locale-independent as possible. I've got all most text in resource files, and I'm looking at the attributes on my Web Part:
```
[WebBrowsable(true),
Category("My Category"),
WebDisplayName("Display Name here"),
WebDescription("Tells you all about it"),
Personalizable(PersonalizationScope.Shared)]
public string SomeProperty { get; set; }
```
It would be nice to replace those hard-coded strings with something more useful to users (SharePoint administrators in this case) who don't use English.
What are my options, if any? | You are looking for the [`Microsoft.SharePoint.WebPartPages.ResourcesAttribute`](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.resourcesattribute%28loband%29.aspx) class.
[This blog post](http://stephenbrown2008.spaces.live.com/blog/cns!AA0F935BFBFEDCD!129.entry?sa=531919256) has a description of it's use and a simple example.
```
//RESOURCES LOCALIZATION
//Property that is localized. Use the ResourceAttibute.
//[ResourcesAttribute (PropertyNameID=1, CategoryID=2, DescriptionID=3)]
[Resources("PropNameResID", "PropCategoryResID", "PropDescriptionResID")]
``` | Here's my implementation of spoon16's answer:
```
[WebBrowsable(true),
Resources("SearchWebPartWebDisplayName",
"SearchWebPartCategory",
"SearchWebPartWebDescription"),
FriendlyName("Display Name here"),
Description("Tells you all about it"),
Category("My Category"),
Personalizable(PersonalizationScope.Shared)]
public string SomeProperty { get; set; }
public override string LoadResource(string id)
{
string result = Properties.Resources.ResourceManager.GetString(id);
return result;
}
```
Note the change of property names and their order in the attributes block.
I also had to change my WebPart to derive from Microsoft.SharePoint.WebPartPages.WebPart, with the attendant changes to how I handle the Width and Height of my WebPart. | Internationalization and C# method attributes? | [
"",
"c#",
"sharepoint",
"resources",
"attributes",
"internationalization",
""
] |
When calling functions that always throw from a function returning a value, the compiler often warns that not all control paths return a value. Legitimately so.
```
void AlwaysThrows() { throw "something"; }
bool foo()
{
if (cond)
AlwaysThrows();
else
return true; // Warning C4715 here
}
```
Is there a way to tell the compiler that AlwaysThrows does what it says?
I'm aware that I can add another `throw` after the function call:
```
{ AlwaysThrows(); throw "dummy"; }
```
And I'm aware that I can disable the warning explicitly. But I was wondering if there is a more elegant solution. | With Visual C++, you can use `__declspec(noreturn)`. | Use the [`noreturn`](https://en.cppreference.com/w/cpp/language/attributes/noreturn) attribute. This is specified in section *"7.6.3 Noreturn attribute [dcl.attr.noreturn]"* of the latest version of the C++ standard third edition ISO/IEC 14882:2011.
Example from the standard:
```
[[ noreturn ]] void f()
{
throw "error";
}
``` | How to signify to the compiler that a function always throws? | [
"",
"c++",
"exception",
"visual-c++",
""
] |
Using .NET 3.5, ASP.NET, Enterprise Library 4.1 Exception Handling and Logging blocks, I wrote a custom exception handler to display a standard error page, as follows:
```
[ConfigurationElementType(typeof(CustomHandlerData))]
public class PageExceptionHandler : IExceptionHandler {
public PageExceptionHandler(NameValueCollection ignore) {
}
public Exception HandleException(Exception ex, Guid handlingInstanceID) {
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentEncoding = Encoding.UTF8;
response.ContentType = "text/html";
response.Write(BuildErrorPage(ex, handlingInstanceID));
response.Flush();
//response.End(); // SOMETIMES DOES NOT WORK
return ex;
}
}
```
This is called from an exception handling policy like this:
```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<exceptionHandling>
<exceptionPolicies>
<add name="Top Level">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None" name="Exception">
<exceptionHandlers>
<add logCategory="General" eventId="0" severity="Error" title="Application Error"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Log Full Details" />
<add type="PageExceptionHandler, Test, Culture=neutral, PublicKeyToken=null"
name="Display Error Page" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
```
It all works fine, except that the error page was being incorporated into whatever markup was displayed at the time the error occurred. I thought that adding `response.End()` into the exception handler would solve this problem. It did, but I then observed that, sometimes, ASP.NET throws a `ThreadAbortException` while trying to end the response stream. This is the only exception type that cannot be caught and ignored. Grrr! Can anyone tell me:
1. Under what conditions ASP.NET would throw a `ThreadAbortException` when trying to end the response stream?
2. Is there a safer alternative to `response.End()` that I could use?
3. If not, is there a way of detecting whether the response stream is "end-able" before calling `response.End()`?
**EDIT - More Context**
The design goal for this code is to make it as simple as possible to add EHAB-style error handling to a web app. I have a custom `IHttpModule` that must be added to the `web.config` file. In the module's `Application_Error` event it calls `ExceptionPolicy.HandleException`. The exception handling policy must be configured to call the `PageExceptionHandler` class described above. This whole procedure involves only a small amount of XML config, no extra files, and no extra lines of code in the consuming web app.
In fact, the code as it stands seems to work fine. However, in some situations it is desirable to have an explicit catch block in the web app code that calls the exception handling policy directly. This sort of scenario is what does not work properly. I would like a single solution that works under all possible methods of calling it. I do get the impression that it would be a lot simpler if the EHAB was not involved, but unfortunately it is used throughout all our code, and provides so many other benefits that I would prefer to keep it in.
**EDIT - Testing Results**
I created a test harness to exercise the code in six different ways:
1. Writing to the current page's `HttpResponse` directly.
2. Constructing an exception object and calling `ExceptionPolicy.HandleException(ex, "Top Level")` directly.
3. Throwing an exception object, catching it, and calling `ExceptionPolicy.HandleException(ex, "Top Level")` in the catch block.
4. Throwing an exception object and letting the `Page_Error` event call `ExceptionPolicy.HandleException(ex, "Top Level")`.
5. Throwing an exception object and letting the `Application_Error` event call `ExceptionPolicy.HandleException(ex, "Top Level")`.
6. Throwing an exception object and letting my custom `IHttpModule` class call `ExceptionPolicy.HandleException(ex, "Top Level")`.
Test results for each method with no code to terminate the response after writing the error page markup:
* Methods 1, 2, 3 - Error page markup combined with the test page markup.
* Methods 4, 5, 6 - Error page markup replaced the test page markup (desired result).
Test results for each method when `HttpContext.Current.ApplicationInstance.CompleteRequest` was called:
* Methods 1, 2, 3 - Error page markup combined with the test page markup.
* Methods 4, 5, 6 - Error page markup replaced the test page markup (desired result).
Test results for each method when `HttpContext.Current.Response.End` was called:
* Methods 1, 5, 6 - Error page markup replaced the test page markup (desired result).
* Methods 2, 3, 4 - Error page markup replaced the test page markup, but the EHAB throws a `ExceptionHandlingException` *twice*.
Test results for each method when `HttpContext.Current.Response.End` was called, but wrapped in a `try` ... `catch` block:
* Methods 5, 6 - Error page markup replaced the test page markup (desired result).
* Methods 1, 3, 4 - Error page markup replaced the test page markup, but ASP.NET throws a `ThreadAbortException` which is caught and absorbed by the catch block.
* Method 2 - Error page markup replaced the test page markup, but I get a
`ThreadAbortException` *and also* two `ExceptionHandlingException`s.
It's a ridiculous set of behaviours. :-( | After a lot of testing, I have found only two approaches that work without error.
**Solution 1**
No change to the current architecture at all. The global exception handler already works as desired. If an explicit catch block is needed in code for any reason (e.g. to render validation errors on an input form), then I will tell developers to call `Response.End` explicitly, e.g.
```
try {
// ...
} catch(Exception ex) {
if(ExceptionPolicy.HandleException(ex, "Top Level")) {
throw;
}
Response.End();
}
```
**Solution 2**
Give up trying to overwrite the current response stream and do a genuine redirect to an error page. This works fine with all six test harness methods. The next problem was finding a way of doing this that required the minimum possible changes to the consuming project and abstracted away all the dirty details.
Step 1 - Add a placeholder `ErrorPage.ashx` file to the project which contains only a reference to a standard web page handler class and no code-behind.
```
<%@ WebHandler Class="WebApplicationErrorPage" %>
```
Step 2 - Redirect to this page in the `PageExceptionHandler` class, using a session key to pass all required data.
```
public Exception HandleException(Exception ex, Guid handlingInstanceID) {
HttpResponse response = HttpContext.Current.Response;
HttpSessionState session = HttpContext.Current.Session;
session["ErrorPageText"] = BuildErrorPage(ex, handlingInstanceID);
response.Redirect(errorPageUrl, false);
return ex;
}
```
Step 3 - Make the `WebApplicationErrorPage` class a really dumb HTTP handler that just writes to the response stream.
```
public class WebApplicationErrorPage : IHttpHandler, IReadOnlySessionState {
public bool IsReusable {
get {
return true;
}
}
public void ProcessRequest(HttpContext context) {
response.Clear();
response.ContentEncoding = Encoding.UTF8;
response.ContentType = "text/html";
response.Write((string) context.Session["ErrorPageText"]);
response.Flush();
}
}
```
**Conclusion**
I think I'll stick with solution 1 because it doesn't involve chopping and changing the existing architecture (implementing solution 2 for real will be a lot more complex than the code snippets above suggest). I'll file away solution 2 for possible use elsewhere. | Have a look at [ELMAH](http://code.google.com/p/elmah/).
There are lots of articles and how-to's on ELMAH, just google or bing for it :-)
**Advantages**
+ It logs almost everything
+ Email notification
+ Remote viewing of errors
I would suggest to use that and redirect to a default error page, as Ariel mentioned. | Exception Handling Application Block Exception Handler running in ASP.NET cannot call Response.End() | [
"",
"c#",
".net",
"asp.net",
"enterprise-library",
""
] |
I've created a web.py application, and now that it is ready to be deployed, I want to run in not on web.py's built-in webserver. I want to be able to run it on different webservers, Apache or IIS, without having to change my application code. This is where WSGI is supposed to come in, if I understand it correctly.
However, I don't understand what exacly I have to do to make my application deployable on a WSGI server? Most examples assume you are using Pylons/Django/other-framework, on which you simply run some magic command which fixes everything for you.
From what I understand of the (quite brief) web.py documentation, instead of running `web.application(...).run()`, I should use `web.application(...).wsgifunc()`. And then what? | Exactly what you need to do to host it with a specific WSGI hosting mechanism varies with the server.
For the case of Apache/mod\_wsgi and Phusion Passenger, you just need to provide a WSGI script file which contains an object called 'application'. For web.py 0.2, this is the result of calling web.wsgifunc() with appropriate arguments. For web.py 0.3, you instead use wsgifunc() member function of object returned by web.application(). For details of these see mod\_wsgi documentation:
<http://code.google.com/p/modwsgi/wiki/IntegrationWithWebPy>
If instead you are having to use FASTCGI, SCGI or AJP adapters for a server such as Lighttpd, nginx or Cherokee, then you need to use 'flup' package to provide a bridge between those language agnostic interfaces and WSGI. This involves calling a flup function with the same WSGI application object above that something like mod\_wsgi or Phusion Passenger would use directly without the need for a bridge. For details of this see:
<http://trac.saddi.com/flup/wiki/FlupServers>
Important thing is to structure your web application so that it is in its own self contained set of modules. To work with a particular server, then create a separate script file as necessary to bridge between what that server requires and your application code. Your application code should always be outside of the web server document directory and only the script file that acts as bridge would be in server document directory if appropriate. | As of July 21 2009, there is a much fuller installation guide at [the webpy install site](http://webpy.org/install), that discusses **flup**, **fastcgi**, **apache** and more. I haven't yet *tried* it, but it seems like it's much more detailed. | Deploying a Web.py application with WSGI, several servers | [
"",
"python",
"wsgi",
"web.py",
""
] |
I'm not too familiar with networking in JAVA but what i'm basically trying to do is create a couple of threads that will "talk" to each other using HTTPS for security reasons.
I'm not sure about the terminology so what I'm looking for is a pointing in the right direction. Hopefully, this should be pretty easy for experienced JAVA networking programmers.
I've tried to research this myself but there are different methods of doing this (HttpsURLConnection? [Sending a POST Request Using a URL](http://www.exampledepot.com/egs/java.net/Post.html)?) and a tip from someone who's done this before could save me alot of research time.
Thanks! | [HttpsURLConnection](http://java.sun.com/javase/6/docs/api/javax/net/ssl/HttpsURLConnection.html) is indeed the main class, but for simple uses you can actually just do:
```
InputStream is = new URL("https://example.com").openStream();
```
Consider whether you actually want to use HTTP for your application. It may make more sense to use another protocol, or raw SSL. Look at [SSLSocket](http://java.sun.com/javase/6/docs/api/javax/net/ssl/SSLSocket.html), [SSLServerSocket](http://java.sun.com/javase/6/docs/api/javax/net/ssl/SSLServerSocket.html), and the associated classes.
Java RMI ([Remote Method Invocation](http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp)) may also be relevant. It allows calling Java methods on remote computers, and has built-in security options. See [Using RMI with SSL](http://java.sun.com/j2se/1.4.2/docs/guide/rmi/socketfactory/SSLInfo.html) if you're interested in that route. | If you want to stick with Http, have a look at the apache [httpclient](http://hc.apache.org/httpclient-3.x/) library.Its has a lot of useful http abstractions. | How do I communicate with HTTPS? (Basic Stuff) | [
"",
"java",
"networking",
"https",
""
] |
As far as I know document.getElementById('myId') will only look for HTML elements that are already in the document. Let's say I've created a new element via JS, but that I haven't appended it yet to the document body, is there's a way I can access this element by its id like I would normally do with getElementById?
```
var newElement = document.createElement('div');
newElement.id = 'myId';
// Without doing: document.body.appendChild(newElement);
var elmt = document.getElementById('myId'); // won't work
```
Is there a workaround for that?
(I must tell that I don't want to store any reference to this particular element, that's why I need to access it via its Id)
Thank you! | If it isn't part of the document, then you can't grab it using `document.getElementById`. `getElementById` does a DOM lookup, so the element must be in the tree to be found. If you create a floating DOM element, it merely exists in memory, and isn't accessible from the DOM. It has to be added to the DOM to be visible.
If you need to reference the element later, simply pass the reference to another function--all objects in JavaScript are passed by reference, so working on that floating DOM element from within another function modifies the original, not a copy. | For anyone stumbling upon this issue in or after 2019, here is an updated answer.
The accepted answer from Andrew Noyes is correct in that `document.getElementById` won't work unless the element exists in the document and the above code already contains a reference to the desired element anyway.
However, if you can't otherwise retrieve a direct reference to your desired element, consider using [selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors). Selectors allow you to retrieve nodes that aren't necessarily in the DOM by using their relationship to other nodes, for example:
```
var child = document.createElement("div");
child.id = "my_id";
var parent = document.createElement("div");
parent.appendChild(child);
var child2 = parent.querySelector("#my_id");
``` | Use getElementById for elements that are not [yet] in the DOM? | [
"",
"javascript",
"getelementbyid",
""
] |
I have an SQL database with a set of tables that have Unique Id's. For the longest time I have been using the unique Identifier datatype and passing in a guid from my C# interface. However for the purpose of speed when querying I have decided to switch to using a bigint and passing in a long.
Whats the easiest way to create unique longs each time I run the code so that there is no duplication of ID? | The only way you could guarantee that the bigint is unique within the database table, is to let SQL Server generate it for you - make it an IDENTITY column.
Did you actually measure performance with uniqueidentifier and found it too slow? | There are other options for generating unique numbers besides a seed. One possibility is to generate a number based on time, something like the ticks, or better calculate the number of seconds since the start of 2009. Then append a unique digit based on the location (or account if you are not doing it on the server) the number was created to the end of the number (the least significant digit).
So if your new unique number was created on *app server 1* and it's id was 42 and it's has been 4000 seconds since the start of 2009, your new identifier would be 400042. The next one generated could be 400942, and one generated from a different server at exactly the same time could be 400943. | Generate C# Long Unique ID | [
"",
"c#",
"uniqueidentifier",
"long-integer",
""
] |
I have a scripts that retrieves huge data on a table. I want to create a mysqldump to insert data into another database table with different fields. I want the format of phpMyAdmin where it repeats the INSERT INTO Table VALUES(values1),(values2), ...(values100); if reaches certain amount of value sets depends on what you set.
ex: If I have 550 data sets and i want to be devided the data by 100 so that i will have 6 sets of INSERT INTO query.
```
INSERT INTO tablename VALUES(value1), (value2), .... (value100);
INSERT INTO tablename VALUES(value101), (value102), .... (value200);
INSERT INTO tablename VALUES(value201), (value202), .... (value300);
INSERT INTO tablename VALUES(value301), (value302), .... (value400);
INSERT INTO tablename VALUES(value401), (value402), .... (value500);
INSERT INTO tablename VALUES(value501), (value502), .... (value550);
``` | You could use [`array_chunk()`](http://php.net/array_chunk), something like:
```
$toInsert = array( '(values1)', '(values2)', '(values3)', '(values4)' ); //etc.
$sqlStart = 'INSERT INTO tablename (field1, field2, field3, etc) VALUES ';
foreach (array_chunk($toInsert, 100) as $insertSet) {
$sql = $sqlStart . implode(', ', $insertSet);
//execute $sql
}
```
Are you actually doing much with the data though? You might be able to do it all in SQL with `INSERT INTO table (field1, field2) SELECT somefield, somefield2 FROM another table` | If you're using mysqldump and wish to output mutiple rows into a single insert, then you need to use the --extended-insert option:
[mysqldump extended insert option](http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_extended-insert)
I'm not sure it's possible to specify with mysqldump to specify that a specific number of rows are included in each INSERT statement generated in the dump. Rather you can set the net\_buffer\_length (although it's not recommended that you do change it), so the actual amount may vary depending on the data in each row. | creating mysql dump like phpMyAdmin | [
"",
"php",
"mysql",
""
] |
As I had written in title, I have SQL query, run on Oracle DB, lets say:
```
SELECT * FROM TABLE WHERE TABLE.NAME Like 'IgNoReCaSe'
```
If I would like, that the query would return either "IGNORECASE", "ignorecase" or combinations of them, how can this be done? | Use ALTER SESSION statements to set comparison to case-insensitive:
```
alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;
```
If you're still using version 10gR2, use the below statements. See [this FAQ for details](http://www.orafaq.com/node/91).
```
alter session set NLS_COMP=ANSI;
alter session set NLS_SORT=BINARY_CI;
``` | ```
Select * from table where upper(table.name) like upper('IgNoreCaSe');
```
Alternatively, substitute lower for upper. | Oracle DB: How can I write query ignoring case? | [
"",
"sql",
"database",
"oracle",
""
] |
I'm pretty sure there is no way, but i'm putting this out there for those expert beyond my knowledge.
What i am looking to do is to somehow alter SELECT statements before they are executed, at the database level. For a seriously pared-down example, i'd like to do something like the following... when someone executes the following SQL
```
SELECT * FROM users.MESSAGES
```
i'd like to catch it, before it executes, and alter the statement to something like
```
SELECT * FROM users.MESSAGES WHERE RECIPIENT = ORIGINAL_LOGIN()
```
allowing me to enforce user limitations on the data in a fashion similar to ORACLE's VPDs, without needing to resort to creating views on top of all my tables that might need this. | Sadly, this is not possible.
Even the Microsoft SQL Server row-level security features (e.g. in the security catalogs) are implemented using views.
So, if you really need the feature, you're going to have to set up views with SUSER\_NAME() or some similar individual- or role-identifier in the WHERE clauses.
Sorry! | Look into using a [VIEW](http://msdn.microsoft.com/en-us/library/ms187956(SQL.90).aspx). | Sql Server modify select | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.