Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have company, customer, supplier etc tables which all have address information related columns.
I am trying to figure out if I should create a new table 'addresses' and separate all address columns to that.
Having address columns on all tables is easy to use and query but I am not sure if it is the right way of doing it from a good design perspective, having these same columns repeat over few tables is making me curious.
Content of the address is not important for me, I will not be checking or using these addresses on any decision making processes, they are purely information related. Currently I am looking at 5 tables that have address information | The answer to all design questions is this:
It depends.
So basically, in the Address case it depends on whether or not you will have more than 1 address per customer. If you will have more than 1, put it in a new Addresses table and give each address a CustomerID. It's overkill (most times, it depends!) to create a generic Address table and map it to the company/customer/supplier tables.
It's also often overkill (and dangerous) to map addresses in a many-to-many relationship between your objects (as addresses can seem to magically change on users if you do this).
The one big rule is: Keep it simple! | This is called [Database Normalization](http://databases.about.com/od/specificproducts/a/normalization.htm). And yes, you want to split them up, if for no other reason because if you need to in the future it will be much harder when you have code and queries in place.
As a rule, you should always design your database in 3rd Normal Form, even for simple apps (there will be a few cases where you won't for performance or logistic reasons, but starting out I would always try to make it 3rd Normal Form, and then learn to cheat after you know the right way of doing it).
EDIT: To expand on this and add some of the comments I have made on other's posts, I am a big believer in starting with a simple design when it comes to code and refactoring when it becomes clear that it is becoming too complex and more indepth object oriented principles would be appropriate. However, refactoring a database that is in production is not so simple. It is all about ROI. It is just too easy to design a normalized database from the outset to justify not doing it. The consequences of a poorly designed database can be catastrophic and it is usually too late before you come to that realization. | When to separate columns into new table | [
"",
"asp.net",
"sql",
"performance",
"design-patterns",
""
] |
The question is confusing, but it is much more clear as described by the following code:
```
List<List<T>> listOfList;
// add three lists of List<T> to listOfList, for example
/* listOfList = new {
{ 1, 2, 3}, // list 1 of 1, 3, and 3
{ 4, 5, 6}, // list 2
{ 7, 8, 9} // list 3
};
*/
List<T> list = null;
// how to merger all the items in listOfList to list?
// { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
// list = ???
```
Not sure if it possible by using C# LINQ or Lambda?
**Essentially, how can I concatenate or "*flatten*" a list of lists?** | Use the SelectMany extension method
```
list = listOfList.SelectMany(x => x).ToList();
``` | Here's the C# integrated syntax version:
```
var items =
from list in listOfList
from item in list
select item;
``` | How to merge a list of lists with same type of items to a single list of items? | [
"",
"c#",
"linq",
"lambda",
""
] |
I need to restrict cookies to my www subdomain, this works by me adding the line session.cookie\_domain = www.example.com in the php.ini file. However I have a number of virtual hosts on my server so I need this domain to be different for each one. After a bit of a web-seach, I have tried using:
```
'SetEnv session.cookie_domain www.example.com' - in my httpd.conf
'php_flag session.cookie_domain www.example.com' in .htaccess
```
However both seem to stop cookies working all together!
Any help much appreciated!
Stu | The easiest way to achieve this is to use [`session_set_cookie_params()`](https://www.php.net/manual/en/function.session-set-cookie-params.php) instead of setting it via `.htaccess` (the `.htaccess` method only works if PHP is used as a module). You can use it in the following way:
```
session_set_cookie_params(0, '/', 'www.example.com');
session_start();
``` | The problem is that `php_flag` is actually meant only for Boolean values. So when using the `php_flag` command, you're actually setting `cookie_domain` to `0`, which is why it stops working.
For text values, you need to use `php_value` in the .htaccess or apache config. Also quoting the value is recommended:
```
php_value session.cookie_domain ".domain.com"
```
see: <http://www.php.net/manual/en/configuration.changes.php> | PHP / Apache how to set session.cookie_domain from outside php.ini | [
"",
"apache",
".htaccess",
"php",
"httpd.conf",
""
] |
If my markup looks like this:
```
<button id="button-1" class="nice">
<button id="button-2" class="nice">
<button id="button-3" class="nice">
```
and I define the following jQuery:
```
$(".nice").click(function () {
// something happens
});
```
1. How many event listeners are established? 1 or 3?
2. If I have 1000 buttons instead of 3, should I use event delegation instead?
3. Is it best, performance-wise, to not define jQuery calls on classes of elements if those classes contain a large number of elements in the markup? | 1) 3 event listeners all pointing to the same function.
2) That depends on what you're trying to accomplish
3) Try doing some benchmarks, see where the performance hit becomes noticeable. I've had up to 1000 elements being selected then animated at the same time - and (in FF) the performance hit was unnoticeable up until about 600-700 elements. Performance of course depends on browser and JS engine. Some (Chrome) will be faster than others (IE). Its worth mentioning that for that site I used the same method as you have in your question. | 1) 3
2) Yes
3) Yes, as you have said use event delegation which in jQuery is available through the [.live](http://docs.jquery.com/Events/live) function. Be carefull, too many .live function can also impact performance so do consider native event delegation. | Performance overhead of event listeners on CSS classes used in JQuery code | [
"",
"javascript",
"jquery",
"event-delegation",
""
] |
Is there a good way to allow only a certain class to have read/write access to properties in another class without having inheritance structure between them during design mode in .NET?
So if a class has public properties, only a certain class has visibility to these properties?
If not possible during design mode, then during run time. I know of a hokey way using flags in set and get statements but I think there are better ways. | There is no `friend` access in C#. You have `public`/`protected`/`internal` (including `[InternalsVisibleTo]`), but nothing more granular (i.e. at the inter-type level). So, no. | You can implement this using the [internal](http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx) keyword in C#:
> The internal keyword is an access
> modifier for types and type members.
> Internal types or members are
> accessible only within files in the
> same assembly, as in this example:
>
> ```
> public class BaseClass
> {
> // Only accessible within the same assembly
> internal static int x = 0;
> }
> ```
See also: [Practical usings of “internal” keyword in C#](https://stackoverflow.com/questions/165719/practical-usings-of-internal-keyword-in-c) | Restricting read/write access of class properties to certain classes in .NET | [
"",
"c#",
".net",
""
] |
I need a simple way to test SQL queries for speed. I am not to worried about hardware differences, I basically need a relative number.
This is what I've been doing with PHP (its fuzzy, but works):
```
// CONNECT TO DB HERE
$sub = new YomoSubscription(95,783);
$t = microtime(TRUE);
// contains the SQL db call i'm testing
$fp = $sub->generateFingerprint();
echo microtime(TRUE)-$t;
```
The **PROBLEM** I am having is that, sometimes on initial connect/run my test takes 1.25 sec for example. However on subsequent connects it takes 0.004 sec ... **Why is this**?
I'm pretty sure MySQL query cache is off in my.ini:
```
query_cache_size=0
``` | Your first query may be slower because MySQL is actually hitting the disk on the first query, and not on the second.
Your operating system may cache files in memory as they are read; as a result, subsequent reads may not need to actually hit the disk, and will return much faster.
As a rule of thumb, I generally run a query a few times, and look for consistency. More often than not, the first run will take several times longer, while the 2nd 3rd and 4th take about the same amount of time. Those subsequent runs are probably more representative of the sort of performance you'll see on an actual production system -- since your production database should keep that data in the OS cache, while your dev system is rarely accessed.
In the end, when it comes to query performance, for the most part, you should just give it a quick pass in development, and monitor the slow query log in production to see which queries *really* need work.
As far as programatically running queries for performance data goes -- take several samples, and use the median. But in practice, this isn't going to be terribly representative of the actual performance issues you'll run into in production. | Try using SELECT BENCHMARK(times, query)
More information: <http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_benchmark> | How to test MySQL query speed, with less inconsistencies? | [
"",
"php",
"mysql",
"performance",
""
] |
So I am desperatley trying to get some scrolling functionality to work on a page. After not having a luck I decide to just stick `window.scrollTo(0, 800);` on my page to see if I could get any scrolling to happen. Nothing does happen. I have an accordion that expands and then I want to scroll to a specific element with in it. But for now I would be happy to just see the thing scroll at all. Anyone run into this?
Thanks! | I was able to resolve this problem using jQuery method animate(). Here is an example of the implementation I went with:
```
$('#content').animate({ scrollTop: elementOffset }, 200);
```
The selector is getting the div with ID = "content". I am then applying the animate method on it with scrollTop as an option. The second parameter is the time in milliseconds for the animation duration. I hope this helps someone else. | If you have something like this:
```
html, body { height: 100%; overflow:auto; }
```
If both body and html have a height definition of 100% and also scrolling enabled, window.scrollTo (and all derived scrolling mechanisms) do not work, despite a scrollbar being displayed (which can be used by the user), when the contents exceed that 100% body height.
This is because the scrollbar you see is not that of the window, but that of the body.
Solution:
```
html { height: 100%; overflow:auto; }
body { height: 100%; }
``` | JavaScript scrollTo method does nothing? | [
"",
"javascript",
"jquery",
"dom",
""
] |
I am trying to make a class from a member variable like this:
```
<?
class A{
private $to_construct = 'B';
function make_class(){
// code to make class goes here
}
}
class B{
function __construct(){
echo 'class constructed';
}
}
$myA = new A();
$myA->make_class();
?>
```
I tried using:
```
$myClass = new $this->to_construct();
```
and
```
$myClass = new {$this->to_construct}();
```
but neither worked. I ended up having to do this:
```
$constructor = $this->to_construct;
$myClass = new $constructor();
```
It seems like there should be a way to do this without storing the class name in a local variable. Am I missing something? | Have you tried this?
```
$myClass = new $this->to_construct;
``` | Are you using PHP 4 or something? On 5.2.9 `$myClass = new $this->to_construct();` works perfectly.
In the end it's what you have to live with, with PHP. PHP syntax and semantics are VERY inconsistent. For example, an array access to the result of a call is a syntax error:
```
function foo() {
return array("foo","bar");
}
echo $foo()[0];
```
Any other language could do that but PHP can't. Sometimes you simply need to store values into local variables.
Same is true for `func_get_args()` in older versions of PHP. If you wanted to pass it to a function, you needed to store it in a local var first. | PHP syntax: constructing a class from a member variable | [
"",
"php",
"syntax",
""
] |
I have a WebBrowser in my form that accesses a website that is too wide for the control. I would like to know if there is a way to resize the control to fit the website. It seems simple, but i have not found a way yet. I know how to resize the control, I just need to find the width of the website. Just like when you press the green button in safari it automatically resized the window to the correct size. | You should be able to access the size of the WebBrowser's Document and get it's size through the WebBrowser.Document.Window.Size.
I would use the WebBrowser Controls's DocumentCompleted event to wait until the page is loaded then use your resize code to resize the webControl container with this size.
```
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Size = WebBrowser1.Document.Body.ScrollRectangle.Size
End Sub
``` | Answered [here](https://stackoverflow.com/questions/18818089/): use `WebBrowser.Document.Body.ScrollRectangle.Size` instead of `WebBrowser.Document.Window.Size`. Working like a charm for me. | WebBrowser control resize | [
"",
"c#",
".net",
"winforms",
"resize",
"webbrowser-control",
""
] |
Assume i have the following XML data:
```
<?xml version="1.0" encoding="utf-8" ?>
<Accounts>
<Account name="Account1">
<Campaign name="Camp1">
<RemoteCampaign>RC1</RemoteCampaign>
<RemoteCampaign>RC2</RemoteCampaign>
</Campaign>
<Campaign name="Camp2">
<RemoteCampaign>RC3</RemoteCampaign>
</Campaign>
</Account>
<Account name="Account2">
<Campaign name="Camp3">
<RemoteCampaign>RC4</RemoteCampaign>
</Campaign>
<Campaign name="Camp4">
<RemoteCampaign>RC5</RemoteCampaign>
</Campaign>
</Account>
</Accounts>
```
I need to determine the Campaign name when given the account and the remote campaign name. Is there an easy way to do this in Linq to Xml? It can be assumed that all values are unique. | The following could work:
```
var query = from aa in xdoc.Descendants("Account")
where aa.Attribute("name") != null
&& aa.Attribute("name").Value == accountName
from cc in aa.Descendants("Campaign")
where cc.Attribute("name") != null
&& cc.Descendants("RemoteCampaign").Any(elt => elt.Value == remoteName)
select cc.Attribute("name").Value;
``` | This works, but might not be most efficient:
```
XDocument xml = XDocument.Load(Server.MapPath("XMLFile.xml"));
string account = "Account1";
string remoteCampaign = "RC1";
string campaign = xml.Descendants()
.Where(rc => rc.Value == remoteCampaign && rc.Ancestors("Account").Any(a => a.Attribute("name").Value == account))
.Where(n => n.Parent.Name == "Campaign")
.Select(c => c.Parent.Attribute("name").Value).FirstOrDefault();
``` | Linq to Xml: Complex query help | [
"",
"c#",
"linq-to-xml",
""
] |
I am creating a new database for a web site using SQL Server 2005 (possibly SQL Server 2008 in the near future). As an application developer, I've seen many databases that use an `integer` (or `bigint`, etc.) for an ID field of a table that will be used for relationships. But lately I've also seen databases that use the `unique identifier` (`GUID`) for an ID field.
My question is whether one has an advantage over the other? Will `integer` fields be faster for querying and joining, etc.?
**UPDATE:** To make it clear, this is for a primary key in the tables. | GUIDs are problematic as clustered keys because of the high randomness. This issue was addressed by Paul Randal in the last Technet Magazine Q&A column: [I'd like to use a GUID as the clustered index key, but the others are arguing that it can lead to performance issues with indexes. Is this true and, if so, can you explain why?](http://technet.microsoft.com/en-us/magazine/dd776512.aspx)
Now bear in mind that the discussion is specifically about **clustered** indexes. You say you want to use the column as 'ID', that is unclear if you mean it as clustered key or just primary key. Typically the two overlap, so I'll assume you want to use it as clustered index. The reasons why that is a poor choice are explained in the link to the article I mentioned above.
For non clustered indexes GUIDs still have some issues, but not nearly as big as when they are the leftmost clustered key of the table. Again, the randomness of GUIDs introduces page splits and fragmentation, be it at the non-clustered index level only (a much smaller problem).
There are many urban legends surrounding the GUID usage that condemn them based on their size (16 bytes) compared to an int (4 bytes) and promise horrible performance doom if they are used. This is slightly exaggerated. A key of size 16 can be a very peformant key still, on a properly designed data model. While is true that being 4 times as big as a int results in more a *lower density non-leaf pages* in indexes, this is not a real concern for the vast majority of tables. The b-tree structure is a naturally well balanced tree and the *depth* of tree traversal is seldom an issue, so seeking a value based on GUID key as opposed to a INT key is similar in performance. A leaf-page traversal (ie. a table scan) does not look at the non-leaf pages, and the impact of GUID size on the page size is typically quite small, as the record itself is significantly larger than the extra 12 bytes introduced by the GUID. So I'd take the hear-say advice based on 'is 16 bytes vs. 4' with a, rather large, grain of salt. Analyze on individual case by case and decide if the size impact makes a real difference: how many *other* columns are in the table (ie. how much impact has the GUID size on the leaf pages) and how many references are using it (ie. how many *other* tables will increase because of the fact they need to store a larger foreign key).
I'm calling out all these details in a sort of makeshift defense of GUIDs because they been getting a lot of bad press lately and some is undeserved. They have their merits and are indispensable in any distributed system (the moment you're talking data movement, be it via replication or sync framework or whatever). I've seen bad decisions being made out based on the GUID bad reputation when they were shun without proper consideration. But is true, **if you have to use a GUID as clustered key, make sure you address the randomness issue: use sequential guids** when possible.
And finally, to answer your question: **if you don't have a *specific* reason to use GUIDs, use INTs.** | The GUID is going to take up more space and be slower than an int - even if you use the newsequentialid() function. If you are going to do replication or use the sync framework you pretty much have to use a guid. | INT vs Unique-Identifier for ID field in database | [
"",
"sql",
"sql-server",
"t-sql",
"uniqueidentifier",
""
] |
How do I count the number of occurrences of a character in a string?
e.g. `'a'` appears in `'Mary had a little lamb'` 4 times. | > [`str.count(sub[, start[, end]])`](https://docs.python.org/3/library/stdtypes.html#str.count)
>
> Return the number of non-overlapping occurrences of substring `sub` in the range `[start, end]`. Optional arguments `start` and `end` are interpreted as in slice notation.
```
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
``` | You can use [`.count()`](https://docs.python.org/2/library/string.html#string.count) :
```
>>> 'Mary had a little lamb'.count('a')
4
``` | Count the number of occurrences of a character in a string | [
"",
"python",
"string",
"count",
""
] |
I am running a query from my java based web app running in a Websphere container.
This query however, being pretty simple, fails with a weird erorr as follows:
```
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R com.ibm.db2.jcc.b.zd: Invalid data conversion:Requested conversion would result in a loss of precision of 40000
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.q.a(q.java:137)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.q.a(q.java:1189)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.a(ad.java:1217)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.kb(ad.java:2977)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.d(ad.java:1970)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.d(ad.java:2342)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.U(ad.java:489)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.db2.jcc.b.ad.executeQuery(ad.java:472)
[5/15/09 16:50:33:828 IST] 0000001e SystemErr R at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.executeQuery(WSJdbcPreparedStatement.java:559)
```
The query is pretty simple : it is as simple as
```
select field1, field2 from <xyz table> where <xyz_pk> = ?
```
The primary key is a INTEGER(4) and has data that has values up to 99999999. But however,
when I run this query is run in my web app on a connection obtained from websphere connection pool, it starts failing for pk values > 35k+. In the jdbc binding code, I tried doing a preparedStatement.setInt() and preparedStatement.setFloat(). But nothing seems to work!! It just works for anything below 35k+ and fails for everything above that.
Java's int size is much bigger than 35k+, so why would this query fail with this error? This happens just from my application, when I try the same query with a database client of my choice, proper results are being obtained for all values of the pkey!
Did anyone faced this issue before? If yes, how did you get around it? | My bad.. the issue was in binding. My query had an integer and small int field and I was binding small to int and int to smallint, hence the problem. | Could you maybe post the code that causes the failure?
I remember having something like this on websphere and had to change the precision of the database fields. It had to do with the conversion the database and the java space in that on the java side the data type was far bigger than the datatype on the database.
We changed the data type on the database and things improved. | Weird DB2 database issue : Websphere Connection Pooling | [
"",
"java",
"jdbc",
"jakarta-ee",
"db2",
"websphere",
""
] |
I have an old drupal site that I'd like to upgrade, but I need to move all the site data files (like jpgs, gifs, etc.) from /files to /sites/default/files.
I'd like to use a PHP script or just a MySQL command to find any instance of /files/\* and change it to /sites/default/files/\* (without messing up the string in the \* part of the name, of course!).
Is this pretty easy to do? Any pointers on a function I could use? | MySQL does have some built-in string replacement functions. How about something like this?
```
UPDATE table SET field = REPLACE(field,'/files/','/sites/default/files/');
```
There's [other functions](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html) you can use for more complex replacements (ie. regular expressions) if you need as well. | If you're just changing the files table, you can do an UPDATE with SQL, like zombat said. If you have a significant number of other instances of the paths ( IE - full HTML node bodies and the like ) your best bet would be to export the DB to a text file (can do it with mysqldump or the export feature of PHPMyAdmin) and then just update the strings there - either with a suitable text editor, a command-line tool like sed or a bunch of interns. | How to change a string globally in a MySQL database | [
"",
"php",
"drupal",
""
] |
I'm refactoring some code in C++, and I want to deprecate some old methods. My current method for finding all of the methods looks like this:
1. Comment out the original method in the source file in which I'm working.
2. Try to compile the code.
3. If a compiler error is found, then make a note comment out the call and try to recompile.
4. Once the compile has completed successfully, I've found all of the calls.
This totally sucks. I've also tried grepping source for the name of the function calls, but I sometimes run into problems with functions of the same name with different arguments, so my compilation makes the C++ compiler resolve the names for me. I've found [this question](https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method) for C#, but my code base is entirely implemented in C++.
Is there a better way to find all of the callers of a class method or function in C++? I'm using GCC on Unix systems, but cross-platform solutions would be superlative. | GCC allows you to decorate variables, functions, and methods with [`__attribute__((deprecated))`](http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Function-Attributes.html#index-g_t_0040code_007bdeprecated_007d-attribute_002e-2202), which will cause a warning on all callsites (unless [`-Wno-deprecated-declarations`](http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Warning-Options.html#index-Wno_002ddeprecated_002ddeclarations-417) is given).
```
class A {
public:
A() __attribute__((deprecated)) {}
};
int main() {
A a;
}
```
```
$ g++ test.c
test.cc: In function ‘int main()’:
test.cc:6: warning: ‘A::A()’ is deprecated (declared at test.cc:3)
``` | Eclipse can do this without any plugins. It can be a useful tool for stuff like this even if you don't want to use it for your day-to-day editor.
1. Download, install, and run the [Eclipse CDT](http://www.eclipse.org/cdt/).
2. Go under File, New, C++ Project. Enter a project name and choose an Empty Makefile project from the Project Type tree view. Uncheck "Use default location" and enter the folder where your project is kept.
3. Click Next, then click Finish.
4. Eclipse will automatically start indexing your project. If it really is a Makefile project, and since you're using g++, you can do a full clean then build from within Eclipse (under the Project menu), and it should automatically use your existing makefiles and automatically discover your include directories and other project settings.
5. Find the prototype of the overloaded function in a source file, right-click on it, choose References, and choose Project. Eclipse will find all references to that function, and only to that particular overload of that function, within your project.
You can also use Eclipse's built-in refactoring support to rename overloaded functions so that they're no longer overloaded. Eclipse is also fully cross-platform; you can use features like its indexer, search references, and refactoring even for projects that are maintained and built in other IDEs. | How to Find All Callers of a Function in C++? | [
"",
"c++",
"c",
"refactoring",
"function",
""
] |
Ok, dumb question. I'm trying to set up my first TypeMock demo project in VS2005 but it doesn't recognize the [TestMethod] attribute. I've included both the TypeMock and TypeMock.ArrangeActAssert assemblies and I'm referencing them with "using" statements. Even intellisense can't find the attribute. What am I doing wrong here? | [TestMethod] is from the Visual Studio unit testing 'framework'.
The following code shows basically how to use the attribute:
```
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class MyTests
{
[TestMethod]
public void MyFirstTest()
{
Assert.AreEqual(1, 1);
}
}
```
If you're using NUnit or another framework, the attributes are possibily different. | Which unit testing framework are you using? `TestMethod` sounds like the [Visual Studio test](http://msdn.microsoft.com/en-us/library/ms182516(VS.80).aspx) system, while the [NUnit](http://www.nunit.org/index.php) counterpart is called `Test`. | Where is the [TestMethod] Attribute in TypeMock? | [
"",
"c#",
".net",
"testing",
"typemock",
""
] |
I have to deal with a mssql database and the information given in a table like this:
```
Users:
ID Name Countries
--------------------
1 User1 1,2,3
2 User2 2,5
Countries:
ID Country
----------
1 Australia
2 Germany
3 USA
4 Norway
5 Canada
```
Now, what i am looking for is a select statement that will give me a result like this:
```
Result:
ID User CountriesByName
-----------------------------
1 User1 Australia, Germany, USA
2 User2 Germany, Canada
```
I'd prefer a solution that won't depend on special MSSQL syntax over something special, but there is no way for me to use some LINQ-magic :( | First, you'll need to split that string up. Here's a workable split function:
```
Create Function [dbo].[split]
(@input varChar(8000) -- List of delimited items
,@delimit varChar(8000) = ',') -- delimiter that separates items
Returns @List Table ([item] varChar(8000)) As
Begin
Declare @item VarChar(8000);
while charIndex(@delimit, @input, 0) <> 0 Begin
Select
@item = rTrim(lTrim(subString(@input, 1, charIndex(@delimit, @input, 0) - 1))),
@input = rTrim(lTrim(subString(@input, charIndex(@delimit, @input, 0) + Len(@delimit), Len(@input))));
If Len(@item) > 0 Insert Into @List Select @item
End
If Len(@input) > 0 Insert Into @List Select @input
Return;
End
```
Then you'll need to join the values back to your countries table, and re-join them. This will get you most of the way:
```
Select ID
,[Name] as [User]
,(
Select [country] + ', '
From [Countries]
Where [ID] In (
Select Cast([item] As Integer)
From dbo.split(U.Countries, ',')
Where IsNumeric(item) = 1)
Order By [country]
For XML Path('')) As [CountriesByName]
From [Users] As U
```
However, that leaves a trailing comma. You may want to remove that on some other layer, but just in case you MUST do it in SQL, this should work:
```
Select ID
,[User]
,Left([CountriesByName], Len([CountriesByName]) - 1) As [CountriesByName]
From (
Select ID
,[Name] as [User]
,(
Select [country] + ', '
From [Countries]
Where [ID] In (
Select Cast([item] As Integer)
From dbo.split(U.Countries, ',')
Where IsNumeric(item) = 1)
Order By [country]
For XML Path('')) As [CountriesByName]
From [Users] As U) As [Results]
``` | Try a [Common Table Expression](http://msdn.microsoft.com/en-us/library/ms190766.aspx) query. Simple-Talk has a very nice [walkthrough](http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/) that explains different approaches to SQL contacenation and gives examples of using CTEs (look for the WITH statements). | SQL select joined string for set of ids | [
"",
"sql",
"sql-server",
"select",
"join",
""
] |
I'm trying to implement without success a Date iterator with Joda time.
I need something that allows me to iterate all the days form startDate to endDate
Do you have any idea on how to do that? | Here's something to get you started. You may want to think about whether you want it to be inclusive or exclusive at the end, etc.
```
import org.joda.time.*;
import java.util.*;
class LocalDateRange implements Iterable<LocalDate>
{
private final LocalDate start;
private final LocalDate end;
public LocalDateRange(LocalDate start,
LocalDate end)
{
this.start = start;
this.end = end;
}
public Iterator<LocalDate> iterator()
{
return new LocalDateRangeIterator(start, end);
}
private static class LocalDateRangeIterator implements Iterator<LocalDate>
{
private LocalDate current;
private final LocalDate end;
private LocalDateRangeIterator(LocalDate start,
LocalDate end)
{
this.current = start;
this.end = end;
}
public boolean hasNext()
{
return current != null;
}
public LocalDate next()
{
if (current == null)
{
throw new NoSuchElementException();
}
LocalDate ret = current;
current = current.plusDays(1);
if (current.compareTo(end) > 0)
{
current = null;
}
return ret;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
class Test
{
public static void main(String args[])
{
LocalDate start = new LocalDate(2009, 7, 20);
LocalDate end = new LocalDate(2009, 8, 3);
for (LocalDate date : new LocalDateRange(start, end))
{
System.out.println(date);
}
}
}
```
It's a while since I've written an iterator in Java, so I *hope* it's right. I think it's pretty much okay...
Oh for C# iterator blocks, that's all I can say... | <http://code.google.com/p/google-rfc-2445> ? | Java Joda Time - Implement a Date range iterator | [
"",
"java",
"date",
"iterator",
"jodatime",
""
] |
What are the best C# (csharp) equivalents for the following VB (VB.NET, VisualBasic) statements:
```
My.Application.Info.DirectoryPath
My.Computer.Clipboard
My.Computer.Audio.PlaySystemSound()
My.Application.Shutdown()
``` | Application.ExecutablePath
System.Windows.Forms.Clipboard
System.Media.\*
Application.Exit | ```
My.Application.Info.DirectoryPath
AppDomain.CurrentDomain.BaseDirectory
My.Computer.Clipboard
System.Windows.Clipboard //(WPF)
System.Windows.Forms.Clipboard //(WinForms)
My.Computer.Audio.PlaySystemSound()
System.Media.SystemSounds.*.Play()
My.Application.Shutdown()
System.Windows.Forms.Application.Exit() //(WinForms)
or
System.Windows.Application.Current.Shutdown() //(WPF)
or
System.Environment.Exit(ExitCode) //(Both WinForms & WPF)
``` | Convert VB to C# - My.Application.Info.DirectoryPath | [
"",
"c#",
"vb.net",
""
] |
I've got this:
```
private IEnumerable _myList;
```
I need to get a count off of that object. I was previously typing \_myList to an array and getting the length, but now we are using this same bit of code with a different kind of object. It's still a Collection type (it's a strongly typed Subsonic Collection object), and everything works great, except for the bit that we need to get the total number of items in the object.
I've tried typing it to CollectionBase, and many many other types, but nothing works that will let me get a .Count or .Length or anything like that.
Can anyone point me in the right direction?
EDIT: I'm not using 3.5, I'm using 2. So, anything dealing with Linq won't work. Sorry for not posting this earlier. | Is this actually `IEnumerable` instead of `IEnumerable<T>`? If so, LINQ won't help you directly. (You can use `Cast<T>()` as suggested elsewhere, but that will be relatively slow - in particular, it won't be optimised for `IList`/`IList<T>` implementations.)
I suggest you write:
```
public static int Count(this IEnumerable sequence)
{
if (sequence == null)
{
throw new ArgumentNullException("sequence");
}
// Optimisation: won't optimise for collections which
// implement ICollection<T> but not ICollection, admittedly.
ICollection collection = sequence as ICollection;
if (collection != null)
{
return collection.Count;
}
IEnumerator iterator = sequence.GetEnumerator();
try
{
int count = 0;
while (iterator.MoveNext())
{
// Don't bother accessing Current - that might box
// a value, and we don't need it anyway
count++;
}
return count;
}
finally
{
IDisposable disposable = iterator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
``` | The [System.Linq.Enumerable.Count](http://msdn.microsoft.com/en-us/library/bb338038.aspx) extension method does this for a typed `IEnumerable<T>`.
For an untyped `IEnumerable` try making your own extension:
```
public static int Count(this IEnumerable source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
ICollection collectionSource = source as ICollection;
if (collectionSource != null)
{
return collectionSource.Count;
}
int num = 0;
IEnumerator enumerator = source.GetEnumerator();
//try-finally block to ensure Enumerator gets disposed if disposable
try
{
while (enumerator.MoveNext())
{
num++;
}
}
finally
{
// check for disposal
IDisposable disposableEnumerator = enumerator as IDisposable;
if(disposableEnumerator != null)
{
disposableEnumerator.Dispose();
}
}
return num;
}
``` | IEnumerable to something that I can get a Count from? | [
"",
"c#",
"collections",
"ienumerable",
""
] |
I've tried setting the zIndex for my OBJECT and it seems that I cannot place any content above it. Is this an IE issue? Any workarounds? I'm trying to display a lightbox type dialog directly above the OBJECT. | Since you've specified that it wasn't flash, the other way to fix this problem is by using a technique known as an IFrame Shim.
> [More information on the IFrame Shim technique](http://www.macridesweb.com/oltest/IframeShim.html)
The technique basically involves putting an IFrame between your object your content. | If all else fails, and your object has a fairly consistent appearance, you can swap in an image of it when the lightbox opens.
Or, if the object doesn't need to be visible underneath the lightbox, you can just remove the object and then re-append it when the lightbox closes. | Placing content above an <OBJECT> | [
"",
"javascript",
"html",
"css",
"internet-explorer",
""
] |
I have a solution in VS 2008 which has one web project and 3 Class libraries as 3 different Projects. One project is for DataAccess and one is for BusinessLogic.
I have a class in DataAccessLayer. From there when I am trying to access the Class of BusinessLogic class library (project) it is not coming in the IntelliSense when I type. I used the same namespace in both projects. Still same results.
Do I need to to create DLLs for the first project and add as reference to second? | You need to add reference to this project in another project in your soultion.
Visual studio has an option to add project as a reference, so you don't have to add assembly files directly | You need to reference the library in the other projects.
To do that, right-click the references folder in the Solution Explorer, click Add Reference, go to the Projects tab, and select the library that you want to reference.
**EDIT**: Also, make sure that the class you are trying to use is declared as `public` (eg, `public class MyClass`).
If you leave out the `public` modifier (which is the default), the class will only be usable in its project. To expose classes and members to other projects, add the `public` modifier to their declaration | VS 2008 C# : Class library is not accessible in another class library in same solution | [
"",
"c#",
"reference",
"project",
""
] |
I'm writing a C# app to read a file that another application holds open. As some of you may guess, all I get is IOExceptions because "the file is being used by another process". I've tried tweaking File.Open() a little; this is my current try:
```
FileStream fsIn = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
```
(I know that the FileShare flag is more meaningful for other processes that *will* access the file thereafter, but I have tried with it anyway.)
What puzzles me is that Notepad.exe will open the file just fine. Before I dig into Filemon for more clues, does any of you know how to open the file the way Notepad does? Thanks. | You almost have it. You actually want `FileShare.ReadWrite`:
```
FileStream fsIn = File.Open(fileName,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
```
`FileShare.Read` disallows other processes from writing to that file. `FileShare.ReadWrite` allows this.
> **Write** Allows subsequent opening of
> the file for writing. If this flag is
> not specified, any request to open the
> file for writing (by this process or
> another process) will fail until the
> file is closed. However, even if this
> flag is specified, additional
> permissions might still be needed to
> access the file.
>
> **ReadWrite** Allows
> subsequent opening of the file for
> reading or writing. If this flag is
> not specified, any request to open the
> file for reading or writing (by this
> process or another process) will fail
> until the file is closed. However,
> even if this flag is specified,
> additional permissions might still be
> needed to access the file.
It's backwards to me as well. | Well, if you are dealing with small files, just use
```
string myFileContents = System.IO.File.ReadAllText(@"c:\daniellesteele.txt");
```
for text or
```
byte[] myfileContents = System.IO.File.ReadAllBytes(@"c:\aleagueoftheirmoan.mpg");
```
for binary files. | Which flags to open a file the way Notepad.exe does? | [
"",
"c#",
"file-io",
""
] |
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (*EDIT*: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine)
The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help.
```
>>> cache = {}
>>> rule = {"foo":"bar"}
>>> cache[(rule, "baz")] = "quux"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
```
I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, `collections.namedtuple` has a very different syntax, but *can* be used as a key. continuing from above session:
```
>>> from collections import namedtuple
>>> Rule = namedtuple("Rule",rule.keys())
>>> cache[(Rule(**rule), "baz")] = "quux"
>>> cache
{(Rule(foo='bar'), 'baz'): 'quux'}
```
Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule.
Edit: An additional problem with `namedtuple`s is that they are strictly positional. Two tuples that look like they should be different can in fact be the same:
```
>>> you = namedtuple("foo",["bar","baz"])
>>> me = namedtuple("foo",["bar","quux"])
>>> you(bar=1,baz=2) == me(bar=1,quux=2)
True
>>> bob = namedtuple("foo",["baz","bar"])
>>> you(bar=1,baz=2) == bob(bar=1,baz=2)
False
```
tl'dr: How do I get `dict`s that can be used as keys to other `dict`s?
Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling `dict.__setitem__(instance, key, value)` but we're all adults here.
```
class hashdict(dict):
"""
hashable dict implementation, suitable for use as a key into
other dicts.
>>> h1 = hashdict({"apples": 1, "bananas":2})
>>> h2 = hashdict({"bananas": 3, "mangoes": 5})
>>> h1+h2
hashdict(apples=1, bananas=3, mangoes=5)
>>> d1 = {}
>>> d1[h1] = "salad"
>>> d1[h1]
'salad'
>>> d1[h2]
Traceback (most recent call last):
...
KeyError: hashdict(bananas=3, mangoes=5)
based on answers from
http://stackoverflow.com/questions/1151658/python-hashable-dicts
"""
def __key(self):
return tuple(sorted(self.items()))
def __repr__(self):
return "{0}({1})".format(self.__class__.__name__,
", ".join("{0}={1}".format(
str(i[0]),repr(i[1])) for i in self.__key()))
def __hash__(self):
return hash(self.__key())
def __setitem__(self, key, value):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def __delitem__(self, key):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def clear(self):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def pop(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def popitem(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def setdefault(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def update(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
# update is not ok because it mutates the object
# __add__ is ok because it creates a new object
# while the new object is under construction, it's ok to mutate it
def __add__(self, right):
result = hashdict(self)
dict.update(result, right)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
``` | Here is the easy way to make a hashable dictionary. Just remember not to mutate them after embedding in another dictionary for obvious reasons.
```
class hashabledict(dict):
def __hash__(self):
return hash(tuple(sorted(self.items())))
``` | Hashables should be immutable -- not enforcing this but TRUSTING you not to mutate a dict after its first use as a key, the following approach would work:
```
class hashabledict(dict):
def __key(self):
return tuple((k,self[k]) for k in sorted(self))
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.__key() == other.__key()
```
If you DO need to mutate your dicts and STILL want to use them as keys, complexity explodes hundredfolds -- not to say it can't be done, but I'll wait until a VERY specific indication before I get into THAT incredible morass!-) | Python hashable dicts | [
"",
"python",
""
] |
I have been trying to get the latest version of phpmailer from here:
<http://sourceforge.net/projects/phpmailer/files/>
but I keep getting "file not found" / "unable to load mirrors" errors. I tried other files it seems like sourceforge is messed up right now or something is wrong with my connection to it.
Any ideas? And if it is sourceforge does anyone have/know where I can get an alt link? | I get 500 error
Try here. I downloaded and opened it.
<http://www.mirrorservice.org/sites/download.sourceforge.net/pub/sourceforge/p/ph/phpmailer/>
Dam | I do get 500 error,
you know there is something wrong with SF site,
I've also needed to upgrade my server and tried to download something, but it does not working. and same error I got it. | PHPMailer 1.5 / Sourceforge not working? | [
"",
"php",
"email",
"sourceforge",
""
] |
I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look!
```
#!/usr/bin/python
#
# This is a simple python program designed to show my problems with regular expressions and character encoding in python
# Written by Brian J. Stinar
# Thanks for the help!
import urllib # To get files off the Internet
import chardet # To identify charactor encodings
import re # Python Regular Expressions
#import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using
rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()
print (chardet.detect(rawdata))
#print (rawdata)
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text
UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8
print(chardet.detect(UTF_8_encoded)) # Looks good
# This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML
# Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE)
print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8")
print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data")
re_amsterdam = re.compile(".*Adobe.*", re.UNICODE)
print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!?
print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8")
'''
# In additon, I tried this regular expression library much to the same unsatisfactory result
new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data")
'''
```
I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again.
<http://brian-stinar.blogspot.com>
-Brian J. Stinar- | You probably want to either enable the DOTALL flag or you want to use the `search` method instead of the `match` method. ie:
```
# DOTALL makes . match newlines
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE | re.DOTALL)
```
or:
```
# search will find matches even if they aren't at the start of the string
... re_UNSUB_amsterdam.search(foo) ...
```
These will give you different results, but both should give you matches. (See which one is the type you want.)
As an aside: You seem to be getting the encoded text (which is bytes) and decoded text (characters) confused. This isn't uncommon, especially in pre-3.x Python. In particular, this is very suspicious:
```
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2')
```
You're **de**-coding with ISO-8859-2, not **en**-coding, so call this variable "decoded". (Why not "ISO\_8859\_2\_decoded"? Because ISO\_8859\_2 is an encoding. A decoded string doesn't have an encoding anymore.)
The rest of your code is trying to do matches on rawdata and on UTF\_8\_encoded (both encoded strings) when it should probably be using the decoded unicode string instead. | With default flag settings, .\* doesn't match newlines. UNSUBSCRIBE appears only once, after the first newline. Adobe occurs before the first newline. You could fix that by using re.DOTALL.
HOWEVER you haven't inspected what you got with the Adobe match: it's 1478 bytes wide! Turn on re.DOTALL and it (and the corresponding UNSUBSCRIBE pattern) will match the whole text!!
You definitely need to lose the trailing .\* -- you're not interested and it slows down the match. Also you should lose the leading .\* and use search() instead of match().
The re.UNICODE flag is of no use to you in this case -- read the manual and see what it does.
Why are you transcoding your data into UTF-8 and searching on that? Just leave in Unicode.
Someone else pointed out that in general you need to decode `Ӓ` etc thingies before doing any serious work on your data ... but didn't mention the `«` etc thingies with which your data is peppered :-) | Python Unicode Regular Expression | [
"",
"python",
"regex",
"character-encoding",
""
] |
**I have $\_GET['tags'] = "apples, oranges, bananas, grapes, cherries"**
I need to place the data into an array (**$tags**).
What is a **quick way to trim each item and perform security functions** (stripping html, special chars)? | With [array\_walk()](http://php.net/array_walk) you could write your tag cleaning function separately, and then easily apply it to your incoming data.
```
function sterilize(&$val,$key)
{
//do whatever security you need here
$val = trim($val);
$val = strip_tags($val);
//etc
return htmlspecialchars($val);
}
$bad_values = explode(',',$_GET['tags']);
array_walk($bad_values,'sterilize');
``` | Try the following:
```
function process_tags($tags) {
$tags = strip_tags($tags);
$tags = explode(',', $tags);
foreach($tags as $key => $value) {
$tags[$key] = htmlentities($tags[$key]);
$tags[$key] = trim($tags[$key]);
}
return $tags;
}
```
You can simply call the function in the following way:
```
$myTags = "apples, berries, oranges";
$tags = process_tags($myTags);
``` | How to quickly retrieve tags in array from string? | [
"",
"php",
"security",
"arrays",
"tags",
"performance",
""
] |
I want map a List of beans to a JTable. The idea is that each column will be a preselected field in the bean and each row will be a bean in the List. Slide #32 here looks very promising: <http://swinglabs.org/docs/presentations/2007/DesktopMatters/beans-binding-talk.pdf>
However, NetBeans is not very friendly in letting me assign a bean field to a column. I can right-click the JTable and click Bind->Elements and bind it to my List of beans. However, it will not let me specify what goes in each column. The only option is to create the binding myself which pretty much makes NetBeans useless for this type of thing.
Is there a detail I'm missing? It appears that JTable BeansBinding in NetBeans is just broken.
Thanks | I have it working. You can't really use the "Bind" menu option for JTables. Here's how to get it to work:
1. Right-Click the JTable.
2. Click "Table Contents".
1. Binding Source: Form
2. Binding expression: ${var} (where var is the name of the list of beans).
3. Click the "Columns" tab.
4. Map the column to the expression. It should look something like ${id} not ${var.id}.
Note: Each field mapped to a column must have a getter. | As appealing as it may be to use the IDE for this sort of stuff, there's really no substitute for just coding it yourself.
Personally, I prefer [Glazed Lists](http://publicobject.com/glazedlists/) for presenting beans in tables. Take the 2 minutes and watch the video, and I guarantee that you'll be hooked. With less than 15 lines of code, you'll get what you are looking for, and have a huge amount of control over the display - plus filtering, sorting and all sorts of other cool stuff when you are ready for it. | BeansBinding a JTable in NetBeans | [
"",
"java",
"netbeans",
"jtable",
""
] |
I am using date function along with strtotime function to format the date.
Ex:
```
<?php
$input_date = '03-JUL-09 14:53';
$formatted_date = date("Y-m-d H:i:s", strtotime($input_date));
echo $formatted_date;
?>
```
Gives me a expected output: **2009-07-03 14:53:00**
while if the input is changed to(I am removing the minute part)-
```
<?php
$input_date = '03-JUL-09 14';
$formatted_date = date("Y-m-d H:i:s", strtotime($input_date));
echo $formatted_date;
?>
```
The output here is **1970-01-01 05:30:00**, which is not at all expected.
Whats the mistake I am doing and how it can be fixed.
Thanks
Amit | This looks like it comes down to the inability of strtotime() to determine which numbers are what in your 2nd date string.
My best advice is to normalize your date-time value before passing it to strtotime(). Something simple like this might be enough
```
if ( false === strpos( $input_date, ':' ) )
{
$input_date .= ':00';
}
``` | **1970-01-01 05:30:00** is the time in India at the Unix epoch (**1970-01-01 00:00:00** GMT/UTC). This means that `strtotime` returned either `0`, or `false`, which was converted to `0` by `date`. This is because it could not process its input, as others have explained. | Problem in fomating date, when using date function with strtotime function | [
"",
"php",
""
] |
Is there a way to find out all the available baud rates that a particular
system supports via C#? This is available through Device Manager-->Ports
but I want to list these programmatically. | I have found a couple of ways to do this. The following two documents were a starting point
* <http://support.microsoft.com/default.aspx/kb/99026>
* <http://msdn.microsoft.com/en-us/library/aa363189(VS.85).aspx>
The clue is in the following paragraph from the first document
> The simplest way to determine what baud rates are available on a particular serial port is to call the GetCommProperties() application programming interface (API) and examine the COMMPROP.dwSettableBaud bitmask to determine what baud rates are supported on that serial port.
At this stage there are two choices to do this in C#:
# 1.0 Use interop (P/Invoke) as follows:
Define the following data structure
```
[StructLayout(LayoutKind.Sequential)]
struct COMMPROP
{
short wPacketLength;
short wPacketVersion;
int dwServiceMask;
int dwReserved1;
int dwMaxTxQueue;
int dwMaxRxQueue;
int dwMaxBaud;
int dwProvSubType;
int dwProvCapabilities;
int dwSettableParams;
int dwSettableBaud;
short wSettableData;
short wSettableStopParity;
int dwCurrentTxQueue;
int dwCurrentRxQueue;
int dwProvSpec1;
int dwProvSpec2;
string wcProvChar;
}
```
Then define the following signatures
```
[DllImport("kernel32.dll")]
static extern bool GetCommProperties(IntPtr hFile, ref COMMPROP lpCommProp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess,
int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
```
Now make the following calls (refer to <http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx>)
```
COMMPROP _commProp = new COMMPROP();
IntPtr hFile = CreateFile(@"\\.\" + portName, 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
GetCommProperties(hFile, ref commProp);
```
Where *portName* is something like COM?? (COM1, COM2, etc). *commProp.dwSettableBaud* should now contain the desired information.
# 2.0 Use C# reflection
Reflection can be used to access the SerialPort BaseStream and thence the required data as follows:
```
_port = new SerialPort(portName);
_port.Open();
object p = _port.BaseStream.GetType().GetField("commProp", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_port.BaseStream);
Int32 bv = (Int32)p.GetType().GetField("dwSettableBaud", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(p);
```
Note that in both the methods above the port(s) has to be opened at least once to get this data.
--- | I don't think you can.
I recently had this problem, and ended up hard coding the baud rates I wanted to use.
MSDN simply states, "The baud rate must be supported by the user's serial driver". | How to programmatically find all available Baudrates in C# (serialPort class) | [
"",
"c#",
"serial-port",
"baud-rate",
""
] |
I have the following jQuery code which I'm using to populate a jqGrid. It works perfectly posting to my ASP.NET MVC page on the first click of the button. My
problem is, any other clicks past the first it seems to run through the jquery code when clicking the button but it never makes it to the POST page. Any ideas why?
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function() {
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>
``` | The reason the grid isn't reloading is that you are calling the wrong method. The jqGrid method does approximately this:
1. Examine the table to see if it is already a grid; if so, exit.
2. Turn the table into a grid.
3. Populate the first page of data.
So the second time you call the method, it does nothing, as per step 1.
Instead, you should be calling `$("#list").trigger("reloadGrid")` on the second and all subsequent clicks.
Now, because of your mtype in the grid options, the grid is going to do a GET, not a POST. So if the POST is coming from the button itself (in other words, it is an input of type submit), you should return true to indicate that the submit should continue as usual. | Here is the solution :
```
<script type="text/javascript">
var firstClick = true;
$(document).ready(function() {
$('#btnSubmit').click(function() {
if (!firstClick) {
$("#list").trigger("reloadGrid");
}
firstClick = false;
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>
``` | jQuery button click refresh of jqGrid only firing once | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"jqgrid",
""
] |
I would like to cache some IO with the help of `ConcurrentHashMap`. The modification on the binary file should be reflected in cache as well. Since the cache is going to be used by multiple threads all IO operations are synchronized. Modifications of map go inside the same `synchronized` block. Which roughly looks like:
```
synchronized (file) {
file.deleteRecord(index)
map.remove(index);
}
```
and
```
synchronized(file) {
file.writeRecord(index, record);
map.put(index, record);
}
```
Both `map` and `file` are private and are not seen from outside the cache-class.
Is thread-safety preserved if cache reads, namely `map.get(index)`, go without the `synchronized` block?
As I mentioned earlier, `ConcurrentHashMap` is used as map implementation. | Yup. This is basically the point of `ConcurrentHashMap`. From [the documentation](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html):
> Retrieval operations (including get)
> generally do not block, so may overlap
> with update operations (including put
> and remove). Retrievals reflect the
> results of the most recently *completed*
> update operations holding upon their
> onset.
and from the [package documentation](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html):
> A concurrent collection is
> thread-safe, but not governed by a
> single exclusion lock. In the
> particular case of `ConcurrentHashMap`,
> it safely permits any number of
> concurrent reads as well as a tunable
> number of concurrent writes.
(Both of those documentation pages have much more detail, of course. They're worth reading carefully.) | Yes, thread safety is preserved down to the map references, thanks to the ConcurrentHashMap implementation.
The objects you store in the map are another story. | Synchronization of ConcurrentHashMap modifiers | [
"",
"java",
"concurrency",
"synchronization",
"concurrenthashmap",
""
] |
I'm writing a Login page in wicket by java and want to write it as general as possible so I need to pass to class a function which famous as Function Pointer in C++.
The class is:
```
class LoginForm extends Form
{
public LoginForm(String id,TextField username,TextField password,WebResponse webResponse)
{
super(id);
}
@Override
public void onSubmit()
{
String password = Login.this.getPassword();
String userId = Login.this.getUserId();
String role = authenticate(userId, password);
if (role != null)
{
if (Login.this.getSave())
{
utilities.CreateCookie("Username", userId, false, 1209600, (WebResponse) getRequestCycle().getResponse());
utilities.CreateCookie("Password", password, false, 1209600, (WebResponse) getRequestCycle().getResponse());
}
User loggedInUser = new User(userId, role);
WiaSession session = (WiaSession) getSession();
session.setUser(loggedInUser);
if (!continueToOriginalDestination())
{
setResponsePage(UserHome.class);
}
}
else
{
wrongUserPass.setVisible(true);
}
}
}
```
where authenticate is that function what should I do? | Just pass an Interface which defines the `authenticate` method.
```
void DoSomething(IAuthenticationProvider authProvider) {
// ...
authProvider.authenticate();
}
``` | You can use inner class | Function Pointer in Java | [
"",
"java",
"wicket",
""
] |
I have a SQL query which returns only one field - an ID of type INT.
And I have to use it as integer in C# code.
Which way is faster and uses less memory?
```
int id;
if(Int32.TryParse(command.ExecuteScalar().ToString(), out id))
{
// use id
}
```
or
```
int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
// use id.Value
}
```
or
```
int? id = command.ExecuteScalar() as int?;
if(id.HasValue)
{
// use id.Value
}
``` | The difference between the three performance wise is negligible. The bottleneck is moving the data from the DB to your app, not a trivial cast or method call.
I would go with:
```
int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
// use id.Value
}
```
It **fails earlier**, if one day people change the command to return a string or a date, at least it will crash and you will have a chance to fix it.
I would also just go with a simple `int` cast **IF** I always expected the command to return a single result.
Note, I usually prefer returning an out param than doing the execute scalar, execute scalar feels fragile (the convention that the first column in the first row is a return value does not sit right for me). | If you expect the command to return null, you should keep in mind that database null ([DBNull](http://msdn.microsoft.com/en-us/library/system.dbnull.aspx)) is not the same as .NET null. So, conversion of DBNull to int? would fail.
I'd suggest the following:
```
object result = command.ExecuteScalar();
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
``` | Int32.TryParse() or (int?)command.ExecuteScalar() | [
"",
"c#",
".net",
"ado.net",
"tryparse",
"executescalar",
""
] |
I'm in the middle of refactoring some code on my current project, and I'd like some input on if any design pattern exists for the following scenario.
I have a class which executes some logic and returns an object containing the results of said logic; Let's call this the Result object. The state information contained in the Result object is constructed based on a more complex object, the Intermediary object.
Now the code which populates the Result object from the Intermediary object already exists, but since I'm refactoring I want to make this cleaner. I was thinking of creating a separate class, maybe called ResultBuilder, which has a static execute method which takes Intermediary as input and spits out Result as output.
Is there a design pattern which is equivalent to the "ResultBuilder" class? Is there a better way of going about constructing a Result object from an Intermediary object? | I believe you want the Factory pattern. | Why can't a `Result` have a constructor that takes an `Intermediary` instance? | Design Pattern for building an object from a more complex object | [
"",
"java",
"design-patterns",
"refactoring",
""
] |
Much of my time spent developing C++ applications is wasted implementing class definitions. By that I mean the prototyping of classes then creating their respective implementations.
For example:
```
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const X& x, const Y& Y);
~Foo ();
void PerformXYZ (int Count);
};
#endif
```
And now I'll have to copy and paste, then add the repetitive Foo:: onto each function.
```
Foo::Foo (const X& x, const Y& Y)
{
}
Foo::~Foo ()
{
}
void Foo::PerformXYZ (int Count)
{
}
```
For now I copy the function declarations over to their respective \*.cpp files, remove empty lines, then replace ';' with "\n{\n\n}\n". However, I still have to specify the namespace for each function.
Are there tools in Eclipse, Vim or any other IDE/editor that take this burden off a developer? | In Visual Studio there are tools to add functions and variable. Tools automates the process in question. But I never use them :)
In the [Visual Assist X](http://www.wholetomato.com/products/featureRefactoring.asp) there is the [feature](http://www.wholetomato.com/products/features/createImplementation.asp) that helps to add implementation for methods. It is the best solution. | In Visual Studio 2008, you can add a class (it will generate a .h and .cpp file for you) using Project->Add Class... option. But it is very primitive and writes only constructor and destructors. After adding the class, you can go to class view and use 'Add method' menu option to add methods to the class. | C++ Auto Class Implementation in Editor | [
"",
"c++",
"editor",
""
] |
My Leopard system has dtrace built in. I also have Java 6 installed, using the Apple-provided installer:
```
$ java -version
java version "1.6.0_13"
Java(TM) SE Runtime Environment (build 1.6.0_13-b03-211)
Java HotSpot(TM) 64-Bit Server VM (build 11.3-b02-83, mixed mode)
```
Nevertheless, dtrace shows no hotspot probes when listing probes:
```
$ sudo dtrace -l | grep spot
$
```
Can anybody tell me how to enable dtrace probes for Java (supposedly they ship with Java 6) in Leopard? | " Hmm, interesting. I am running the same configurations but for me the probes do not show up. What command line did you use? Also "sudo dtrace -l | grep spot" ? "
* Just one cross check. You should have a running java application at the time when you issue "sudo dtrace -l | grep spot". Only then the probes will be listed. | I'm running Snow Leopard with Java 1.6, and I can see the hotspot probes:
...
```
43223 hotspot_jni3644 libclient.dylib jni_AllocObject AllocObject-entry
43224 hotspot_jni3644 libclient.dylib jni_AllocObject AllocObject-return
43225 hotspot_jni3644 libclient.dylib jni_AttachCurrentThread AttachCurrentThread-entry
43226 hotspot_jni3644 libclient.dylib jni_AttachCurrentThread AttachCurrentThread-return
43227 hotspot_jni3644 libclient.dylib jni_AttachCurrentThreadAsDaemon AttachCurrentThreadAsDaemon-entry
43228 hotspot_jni3644 libclient.dylib jni_AttachCurrentThreadAsDaemon AttachCurrentThreadAsDaemon-return
43229 hotspot_jni3644 libclient.dylib jni_CallBooleanMethod CallBooleanMethod-entry
43230 hotspot_jni3644 libclient.dylib jni_CallBooleanMethod CallBooleanMethod-return
```
... | How to use hotspot probes in dtrace on Mac OS X Leopard? | [
"",
"java",
"macos",
"osx-leopard",
"dtrace",
""
] |
While cyclomatic complexity is a worthwhile metric, I tend to find it to be a poor tool for identifying difficult to maintain code. In particular, I tend to find it just highlights certain types of code (e.g. parsers) and misses difficult recursion, threading and coupling problems as well as many of the anti-patterns that have been defined.
What other tools are available to identify problematic Java code ?
Note, we already use PMD and FindBugs which I believe are great for method level problem identification. | My experience is that the most important metrics when looking at code maintainability are:
* Cyclomatic Complexity, to identify large chunks of code that are probably hard to understand/modify.
* Nesting depth, to find similar spots (a high nesting depth is automatically high CC, but not necessarily the other way around, so scoring on both is important to look at).
* Fan in/out, to get a better view of the relationships between methods/classes and the actual importance of individual methods.
When examining code that was written by others, it is often useful to include dynamic techniques. Simply run common usage scenarios through a profiler/code coverage tool to discover:
* Code that is actually executed a lot (the profiler is great for this, just ignore the timing info and look at the hit counts instead).
* Code coverage is great to find (almost) dead code. To prevent you from investing time in refactoring code that is rarely executed anyway.
The usual suspects such as any profiler, code coverage and metrics tool will usually help you with getting the data required to make these assessments. | [Google Testability Explorer](http://code.google.com/p/testability-explorer/) checks for example for singletons and other static things which are bad smells in design. [Metrics](http://metrics.sourceforge.net/) is an Eclipse plugin that measures almost every code metric known to mankind. I used and can easily recommend both. | Code complexity analysis tools beyond cyclomatic complexity | [
"",
"java",
"complexity-theory",
""
] |
I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my `request.session['user']`.
Of course I can put a user object in the context every time I render a page and then switch on `{% if user %}`, but that seems to break DRY idea - I would have to add user to every context in every view.
How can I extract a fragment like that and make it more common? | Use [template inheritance](http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance) to derive all of your templates from a common base that suitably uses the common parts of the context, and make all your contexts with a factory function that ensures the insertion in them of those common parts. | Are you trying to make certain areas of your site only accessible when logged on? Or certain areas of a particular page?
If you want to block off access to a whole URL you can use the @login\_required decorator in your functions in your view to block certain access. Also, you can use includes to keep the common parts of your site that require user login in a separate html that gets included, that way you're only writing your if statements once. | Rendering common session information in every view | [
"",
"python",
"django",
"session",
"templates",
""
] |
I'm using the encode() method from the sun.misc.BASE64Encoder package. How do I suppress the compiler warnings that it generates?
> sun.misc.BASE64Encoder is Sun proprietary API and may be removed in
And as a followup, why don't I see this warning in Eclipse? | You could switch to a different Base64 implementation, e.g., <http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html> which is part of the Apache commons packages, which you might already have included in your classpath, or <http://iharder.sourceforge.net/current/java/base64/> which you could just take the implementation and stick in your source tree if you don't want another Jar on the path. | There is a totally undocumented way to suppress the sun proprietary API warnings!
Add `-XDignore.symbol.file` to the `javac` command line.
I found this at <https://bugs.java.com/bugdatabase/view_bug?bug_id=6476630> (scroll all the way to the very last comment). We all need to think kind thoughts about "xfournet" who added that last comment! | How can I suppress java compiler warnings about Sun proprietary API | [
"",
"java",
"eclipse",
"api",
"base64",
"sun",
""
] |
1.Hi, I have a internal use only file upload script that uploads the files to a directory. When I upload something from my computer with a spcace in the name i.e example 1.zip it uploads with a space in the name thus killing the link in a email. Is it possible to make apache remove the space when its uploaded or make it a underscore?
The second problem I am having is how would I parse this to make the link an email link with the url of the file as the body of the email amd the email addy anything?
```
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $_FILES["file"]["name"];
``` | You just need to [`urlencode()`](http://php.net/manual/en/function.urlencode.php) your file name and everything is fine:
```
echo "Link: http://example.org/" . urlencode($_FILES["file"]["name"]);
```
But if you want to remove the spaces for another reason, you can use [`str_replace()`](http://php.net/manual/en/function.str-replace.php):
```
$replaced_name = str_replace(' ', '_', $_FILES["file"]["name"]);
rename($uploaddir . '/' . $_FILES['file']['name'], $uploaddir . '/' . $replaced_name);
# You should urlencode() it nonetheless:
echo "Link: http://example.org/" . urlencode($replaced_name);
``` | As a side note : with the code you are using, what is happening if two files with the same name are uploaded ? If you don't do a check (like "*is there a file that already has that name in `$uploaddir` ?*") the second file will replace the first one.
That might not be something you want... is it ?
If not, to solve that (potential) problem, one solution is to always rename uploaded files, with names **you** control. *(A simple counter would probably to the trick)*
Another thing is : `$_FILES["file"]["name"]` is sent by the client, and, as such, can probably be forged to contains whatever someone would want. If it contains something like "`../../index.php`" *(or something like this - you get the idea)*, this could allow someone to put any file they want on your server.
To prevent this from happening, you shoud be sure the file name/path used as destination of `move_uploaded_file` does not contain anything "dangerous". A solution could be to use [`basename`](http://php.net/basename). (see, for instance, example #2 on [POST method uploads](http://php.net/manual/en/features.file-upload.post-method.php))
You might also want to check the mimetype of the uploaded file, so you don't get executables, for instance -- and you should make sure files uploaded are not executable by the webserver. | Remove spaces in file names apache | [
"",
"php",
"apache",
"upload",
""
] |
I want to upcast object array to different array of different object type like below
object[] objects; // assuming that it is non-empty
CLassA[] newObjects = objects as ClassA[]; // assuming that object to ClassA is valid upcasting
is there any way other than upcasting each element individually? | ```
using System.Linq;
newObjects = objects.Select(eachObject => (ClassA)eachObject).ToArray();
``` | As [this post](http://msmvps.com/blogs/jon_skeet/archive/2009/07/09/want-generic-variance-in-c-3-or-even-c-2-no-problem.aspx) suggests, you may be able to do the following trick (untested):
```
newObjects = (ClassA[])(object)objects;
```
Note that in C# 4.0 you won't need to cast, you will be able to directly assign `newObjects = objects`. | how to upcast object array to another type of object array in C#? | [
"",
"c#",
"arrays",
"object",
"casting",
""
] |
I have been reading around but I have not come across a solution to my problem
I am currently working with a Business Object that will hold all my data and we need to convert this object to and from XML.
My object holds a list of Actions (List...), but there are 2 action types (for now).
I have to action types SimpleAction and CompositeAction, and they both inherit from IAction allowing them to both be held in the Actions list.
Now you can probably see the problem as Interfaces cannot be serialized as they hold no data.
How, with maybe some sample code, do I write a Class or Serializer that gets that object type and performs then serializes object with the correct type?
Some code:
```
[XmlArray("Actions")]
public List<IAction> Actions { get; set; }
public interface IAction
{
int ID { get; set; }
ParameterCollection Parameters { get; set; }
List<SectionEntity> Validation { get; set; }
TestResultEntity Result { get; set; }
string Exception { get; set; }
}
[XmlType("A")]
public class SimpleActionEntity : IAction
{
#region IAction Members
[XmlAttribute("ID")]
public int ID { get; set; }
[XmlIgnore]
public ParameterCollection Parameters { get; set; }
[XmlIgnore]
public List<SectionEntity> Validation { get; set; }
[XmlIgnore]
public TestResultEntity Result { get; set; }
[XmlElement("Exception")]
public string Exception { get; set; }
#endregion
}
```
Any help would be greatly appreciated. :) | Ok I have created a solution that I feels does what I want pretty well.
What I did is rather than holding
```
[XmlArray("Actions")]
public List<IAction> Actions { get; set; }
```
I decided to create an ActionsCollection class that handled the List BUT also allowed me to use IXMLSerializable to override the ReadXml and WriteXML methods so that I could handle the way the list is Serialized and Deserialized.
```
[XmlElement("Actions")]
public ActionCollection Actions { get; set; }
public class ActionCollection: CollectionBase, IXmlSerializable
{
#region IList Members
...
#endregion
#region ICollection Members
...
#endregion
#region IEnumerable Members
...
#endregion
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
//TODO
}
public void WriteXml(System.Xml.XmlWriter writer)
{
foreach (IAction oAction in List)
{
XmlSerializer s = new XmlSerializer(oAction.GetType());
s.Serialize(writer, oAction);
}
}
#endregion
}
``` | You can use XmlArrayItemAttribute, As we discussed it's no good to create a list of IAction so it's good to create base class
```
public interface IAction {}
public abstract class ActionBase : IAction {}
public class SimpleAction : ActionBase {}
public class ComplexAction : ActionBase {}
[XmlArray("Actions")]
[XmlArrayItem(typeof(SimpleAction)),XmlArrayItem(typeof(ComplexAction))]
public List<ActionBase> Actions { get; set; }
```
In fact you also can control Element names in the xml file like this:
```
[XmlArray("Actions")]
[XmlArrayItem(typeof(SimpleAction),ElementName = "A")]
[XmlArrayItem(typeof(ComplexAction),ElementName = "B")]
public List<ActionBase> Actions { get; set; }
``` | Serializing a List hold an interface to XML | [
"",
"c#",
"xml",
"serialization",
""
] |
I made a control that inherits directly from ErrorProvider. I thought that applying it the ToolboxBitmap attribute would be enough to get my control to have the same icon on the toolbox as the original control has, but it doesn't. It's strange, as if I add the control to the form, it will appear just as it should, but it doesn't change the toolbox's icon. What am I missing here? I already restarted visual studio and it keeps this behavior.
```
[ToolboxBitmap(typeof(ErrorProvider))]
public class ErrorProviderEx : ErrorProvider {
...
}
``` | In Visual Studio 2008, the icon specified by `ToolBoxBitmap` is not added to the toolbox for any of the components in the current solution for performance reasons. The standard 'gear' icon is used. If you manually add your assembly through the Toolbox...Add Items...dialog, the custom icon will display which is the behavior you are experiencing. Moreover, when you drag ErrorProviderEx to a form, the icon you specified will be used, which again is the behavior you noted in a comment.
Note, in your case, you are using `typeof(ErrorProvider)` so you will not have the normal problems of using a custom bitmap.
(This behavior may also been true for Visual Studio 2005. Visual Studio 2003 spoiled us by displaying the icon.) (I personally do not like this new behavior. I am willing to wait an extra second or two for the IDE to retrieve the icon for all controls and components in the solution. I wonder if there is a registry hack to show the icons.) | Is it in the same project? Or a dll you are referencing?
You only get proper icons when referncing a fixed dll. Try building a control dll and referencing it. | Having my userControl have its own icon on the toolbox | [
"",
"c#",
".net",
"vb.net",
"winforms",
"controls",
""
] |
I have a question about singletons that I think I know the answer to...but every time the scenario pops-up I kinda second guess myself a little so I would like to know the concrete answer.
Say I have two classes setup as so...
```
public class ClassA
{
private static ClassA _classA;
public static ClassA Instance { get { return _classA ?? LoadClassA(); } }
private ClassA(){}
public static ClassA LoadClassA()
{
_classA = new ClassA();
return _classA;
}
private ClassB _classB = new ClassB();
public ClassB ClassB { get { return _classB; } set { _classB = value; } }
}
public class ClassB
{
}
```
My question is simple.
I'm wondering if the \_classB field is treated as static as well if I access the singleton for ClassA? Even though I didn't declare \_classB as a static member.
I've always basically just guessed that \_classB it is treated as static (one memory location) but I would like to know for sure. Am I wrong? Is a new object created for \_classB every time you access it from singleton ClassA...even though there is only one ClassA in memory? Or is it because I newed up \_classB on the declaration that causes there to be only one instance of it?
Thanks in advance,
-Matt | When you create a singleton, you're creating a single static instance of a non-static type.
In this case, your type (Class A) contains a reference to another type (Class B). The static instance will hold a single reference to a single instance of a Class B object. Technically, it is not "static", but since it's rooted to a static object (the class A instance), it will behave like a static variable. You will always have one and only one Class B object (pointed to by your Class A instance). You will never create more than one Class B instance **from within Class A.**
There is nothing, however, preventing a second Class B instance to be generated elsewhere - this would be a different instance. | \_classB is an instance (not static) member of ClassA. Each instance of ClassA will have one instance of \_classB (given the field initializer you've written). So, if you're using the Singleton pattern to access ClassA, and thus always have (at most) one instance of ClassA loaded, you'll always have (at most) one instance of ClassB loaded by way of ClassA.
Now, since ClassB has a public default constructor, something else far away might be creating instances on its own. If that's a concern, consider making ClassB class private. Also, since ClassA has a public default constructor, nothing's stopping folks from creating as many instances as they want. You might make the no-arg constructor private:
```
private ClassA() {}
``` | Question about non-static members of a singleton (C#) | [
"",
"c#",
"design-patterns",
"static",
"singleton",
""
] |
I'm trying to load an `XmlReader` into an `XDocument` for easier manipulation. The XML is well formed and valid (I double checked). When I try and load it into the `XDocument`, I get an `InvalidOperationException`
> The XmlReader state should be EndOfFile after this operation.
the code to load this is
```
public void ReadXml(System.Xml.XmlReader reader)
{
var doc = XDocument.Load(reader);
}
```
I've included a sample of the XML that causes the problem. I can serialize and deserialize this class without a problem, but not load it. Any ideas?
```
<?xml version="1.0" encoding="utf-8"?>
<ForestView xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Forest>
<TreeNodeView>
<Level>Master</Level>
<ID>39476b1f-e2f8-4d76-b82e-a5166899ad43</ID>
<Name>Black Mesa</Name>
<ServerIPAddress>127.0.0.1</ServerIPAddress>
<ServerPortNumber>8000</ServerPortNumber>
<ClientIPAddress>NA</ClientIPAddress>
<ClientPortNumber>4000</ClientPortNumber>
<Nodes>
<Level>Server</Level>
<NodeID>062c3e03-235d-4d7d-9b60-c6228c9cc89e</NodeID>
<Name />
<ServerIPAddress>127.0.0.1</ServerIPAddress>
<ServerPortNumber>5000</ServerPortNumber>
<ClientIPAddress>127.0.0.1</ClientIPAddress>
<ClientPortNumber>4000</ClientPortNumber>
</Nodes>
<Nodes>
<Level>Intermediate</Level>
<NodeID>9bafdc9e-771e-42cf-8f03-e7e75a67a6d1</NodeID>
<Name>Jen</Name>
<ServerIPAddress>127.0.0.1</ServerIPAddress>
<ServerPortNumber>8001</ServerPortNumber>
<ClientIPAddress>127.0.0.1</ClientIPAddress>
<ClientPortNumber>8000</ClientPortNumber>
<Nodes>
<Level>Terminal</Level>
<NodeID>72509141-0ab8-45c1-8042-30afb233b4a8</NodeID>
<Name>Mary</Name>
<ServerIPAddress>127.0.0.1</ServerIPAddress>
<ServerPortNumber>0</ServerPortNumber>
<ClientIPAddress>127.0.0.1</ClientIPAddress>
<ClientPortNumber>8001</ClientPortNumber>
</Nodes>
</Nodes>
</TreeNodeView>
</Forest>
</ForestView>
``` | This error implies that there is extra data after the reader has loaded what it thinks is an XML document. Please verify that your XML file contains no data after the final closing element and that the `XmlReader` is initialized to read from the root element or start of the file, and nothing else. | Quite late answer, in case somebody is having the same issue.
You can fix it by using `ReadSubtree()` on the reader, like:
```
public void ReadXml(System.Xml.XmlReader reader)
{
var doc = XDocument.Load(reader.ReadSubtree());
}
``` | Can't load XmlReader into XDocument | [
"",
"c#",
"linq-to-xml",
""
] |
Hey I've made a rating system in php and mysql and now I want to select a top 5,
I've made something but if a user adds a rating (with the max) it's nr 1 ranking.
How do you guys do it in php and mysql ?
the table looks like this:
-- id
-- mid
-- uid
-- rating
The rating is a number from 1 to 5
Thanks in advance! | As [@chaos](https://stackoverflow.com/questions/1155664/calculating-a-top-5-in-php-and-mysql/1155676#1155676) points out, this is the idea:
```
SELECT `mid`, SUM(`rating`) AS `total`
FROM `rating`
GROUP BY `mid`
ORDER BY `total` DESC
LIMIT 5
```
However, to ensure that not articles with very few ratings get into the top-5 you can add a threshold, allowing only articles with more than X ratings will show up in the result, perhaps giving a more accurate picture of the top 5:
```
SELECT `mid`, SUM(`rating`) AS `total`, COUNT(1) AS `nrRatings`
FROM `rating`
GROUP BY `mid`
HAVING nrRatings > 5 // This is the threshold. Only articles with more than
// 5 ratings will be considered
ORDER BY `total` DESC
LIMIT 5
``` | ```
SELECT `mid`, SUM(`rating`) AS `total`
FROM `rating`
GROUP BY `mid`
ORDER BY `total` DESC
LIMIT 5
``` | calculating a top 5 in php and mysql | [
"",
"php",
"mysql",
"rating",
""
] |
I've written a resolver so I can have a very primitive DI framework. In the framework I allow for a dependency resolver to specify what default types to load if nothing is specified or registered.
However, the way I do the default loading has got me wondering. I'm not sure I'm doing it the best way it could be done.
Example:
```
T LoadDefaultForType<T>()
{
T _result = default(T);
if (typeof(T) == typeof(ISomeThing)
{
result = new SomeThing();
}
... more of the same
else
{
throw new NotSupportException("Give me something I can work with!");
}
return _result;
}
```
**Update**
The use of this would be to get the default object for a given interface in the event that a module or assembly has not configured the interface with a concrete type.
So for instance:
```
IoC.Resolve<ISomeThing>();
```
would need to return back to me a SomeThing object if nothing else has been registered to ISomeThing. The LoadDefaultForType in this case is kind of a last ditch effort to use a default (in this case whatever my domain model is).
The Resolve might shed some light on this as well:
```
T Resolve<T>()
{
T _result = default(T);
if (ContainedObjects.ContainsKey(typeof(T))
_result = (T)ContainedObjects[typeof(T)];
else
_result = LoadDefaultForType<T>();
return _result;
}
```
Any thoughts? Is there a better way to load default types given that I'm trying to allow for a Convention Over Configuration approach? | A few of suggestions:
You could create an attribute that can be used to mark the default implementation type of a particular interface. When you attempt to resolve the type, you could search for this attribute on T and use reflection to dynamically instantiate the type.
Alternatively, you could use reflection to search the available (loaded) assemblies or a concrete type that implements the interface. This can be a slow and expensive processes, so it would only make sense if the default case is rare.
Finally, if you're comfortable with naming conventions, you could search for a class that has the same name as the interface but without the leading "I". Not the best approach, but certainly one that can be made to work in a pinch. | ```
public T LoadDefaultForType<T>()
where T : new()
{
T _result = new T();
return _result;
}
```
the code above would be a better way, but im not sure what it is your're trying todo, more information would help give u a better way of doing whatever it is you're trying to achieve.
I suggest taking a look at [Unity](http://unity.codeplex.com/) for dynamically loading types, ie. Dependency injection | What is the best way to resolve an object? | [
"",
"c#",
"dependency-injection",
""
] |
How do I do this?
My code is something like this:
```
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
var number = '10';
alert('' + [number] + '');
}
```
The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call? | By using `var` when setting number = '10', you are declaring `number` as a local variable each time. Try this:
```
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
number = '10';
alert('' + [number] + '');
}
``` | Remove the `var` in front of `number` in your function. You are creating a local variable by
```
var number = 10;
```
You just need
```
number = 10;
``` | Using a global variable in JavaScript | [
"",
"javascript",
"variables",
"global-variables",
""
] |
Is `\n` the universal newline character sequence in JavaScript for all platforms? If not, how do I determine the character for the current environment?
I'm not asking about the HTML newline element (`<BR/>`). I'm asking about the newline character sequence used within JavaScript strings. | I've just tested a few browsers using this silly bit of JavaScript:
```
function log_newline(msg, test_value) {
if (!test_value) {
test_value = document.getElementById('test').value;
}
console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')
+ ' ' + (test_value.match(/\n/) ? 'LF' : ''));
}
log_newline('HTML source');
log_newline('JS string', "foo\nbar");
log_newline('JS template literal', `bar
baz`);
```
```
<textarea id="test" name="test">
</textarea>
```
IE8 and Opera 9 on Windows use `\r\n`. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use `\n`. They can all handle `\n` just fine when setting the value, though IE and Opera will convert that back to `\r\n` again internally. There's a SitePoint article with some more details called [Line endings in Javascript](http://www.sitepoint.com/line-endings-in-javascript/).
Note also that this is independent of the actual line endings in the HTML file itself (both `\n` and `\r\n` give the same results).
When submitting a form, all browsers canonicalize newlines to `%0D%0A` in URL encoding. To see that, load e.g. `data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form>` and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
```
lines = foo.value.split(/\r\n|\r|\n/g);
``` | Yes, it is universal.
Although `'\n'` is the universal *newline* characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters (`'\r'`). | What is the JavaScript string newline character? | [
"",
"javascript",
"newline",
""
] |
I am trying to sort an associative array which has multiple vales per entry.
For example
```
[0] => stdClass Object ( [type] => node [sid] => 158 [score] => 0.059600525242489 )
[1] => stdClass Object ( [type] => node [sid] => 247 [score] => 0.059600525242489 )
```
I want the array sorted by 'score' (highest score is first index)
How would I do this? | Use the [`usort` function](http://docs.php.net/usort) with this comparison function:
```
function cmpByScore($a, $b) {
if ($a['score'] == $b['score']) {
return 0;
}
return $a['score'] > $b['score'] ? 1 : -1;
}
usort($array, 'cmpByScore');
``` | If you have PHP 5.3, you can use closures to make this a little more dynamic and pretty in a simple way:
```
function sortby(&$array, $key)
{
usort($array, function($a, $b) {
return ($a[$key] - $b[$key]);
});
}
```
Also note that using the minus in the sort function, as suggested by both tj111 and me, will horribly break if you're also planning to sort strings. In that case, Gumbo's approach is the fail-safe way. | PHP Sorting | [
"",
"php",
"sorting",
""
] |
I'm trying to do something to track down the problem, but there's not much I can do until paintContents, and everything there looks good through my debugger, but I'll double check to make sure I didn't miss anything. At the very least, I would like to know how to silently handle these (such as catching them and being able to output a meaningful error message, since once it's thrown, the GUI stutters and freezes for a bit).
```
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at sun.java2d.pipe.DuctusShapeRenderer.renderPath(Unknown Source)
at sun.java2d.pipe.DuctusShapeRenderer.draw(Unknown Source)
at sun.java2d.pipe.PixelToParallelogramConverter.draw(Unknown Source)
at sun.java2d.pipe.PixelToParallelogramConverter.draw(Unknown Source)
at sun.java2d.SunGraphics2D.draw(Unknown Source)
SNIP - MY CALL TO PAINT THE LAYER
at com.jhlabs.map.layer.Layer.paintContents(Layer.java:70)
at com.jhlabs.map.layer.Layer.paint(Layer.java:59)
at com.jhlabs.map.layer.Layer.paintLayers(Layer.java:76)
at com.jhlabs.map.layer.Layer.paintContents(Layer.java:68)
at com.jhlabs.map.layer.Layer.paint(Layer.java:59)
at com.jhlabs.Globe.paint(Globe.java:305)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
n Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
```
The following source code is from the [Java Map Projection Library](http://www.jhlabs.com/java/maps/proj/).
Layer.paintContents:
```
public void paintContents(MapGraphics g) {
if (g != null) {
paintLayers(g);
paintFeatures(g);
paintLayer(g);
}
}
```
Layer.paint:
```
public void paint(MapGraphics g) {
if (isVisible()) {
Graphics2D g2d = g.getGraphics2D();
AffineTransform saveTransform = g2d.getTransform();
Composite saveComposite = g2d.getComposite();
Projection saveProjection = g.getProjection();
Style saveStyle = g.getStyle();
if (composite != null)
g2d.setComposite(composite);
if (transform != null)
g2d.transform(transform);
if (style != null)
g.setStyle(style);
if (projection != null)
g.setProjection(projection);
paintContents(g);
g.setStyle(saveStyle);
g.setProjection(saveProjection);
g2d.setComposite(saveComposite);
g2d.setTransform(saveTransform);
}
}
```
Layer.paintLayers:
```
public void paintLayers(MapGraphics g) {
for (Iterator<Layer> it = getLayersIterator(); it.hasNext();) {
Layer l = (Layer) it.next();
l.paint(g);
}
}
```
Globe.paint:
```
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Turn on antialiasing - otherwise it looks horrible
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Put the origin at bottom left
g2.translate(0, getHeight());
g2.scale(1, -1);
// Put the globe in the middle
g2.translate(getWidth() / 2, getHeight() / 2);
Point2D.Float p = new Point2D.Float(1, 0);
transform.deltaTransform(p, p);
float rscale = 1.0f / (float) Math.sqrt(p.x * p.x + p.y * p.y);
g2.setStroke(new BasicStroke(rscale * 0.5f));
MapGraphics mg = MapGraphics.getGraphics(g2, new Rectangle(getSize()));
seaLayer.setVisible(showSea);
tissotLayer.setVisible(showTissot);
worldLayer.setVisible(showWorld);
graticuleLayer.setVisible(showGraticule);
map.paint(mg);
if (showNight) {
Color c = new Color(0, 0, 0, 0.5f);
GeneralPath gc = new GeneralPath();
ProjectionPainter.smallCircle(45, 5, 87, 180, gc, true);
gc.closePath();
ProjectionPainter pp = ProjectionPainter.getProjectionPainter(projection);
pp.drawPath(g2, gc, null, c);
}
}
``` | I see in your stack trace a blanked out region defined by the line:
```
SNIP - MY CALL TO PAINT THE LAYER
```
That code calls `SunGraphics2D.draw(Shape)`. I dont see that call in the code that you have edited in. However, it looks as though the `Shape` that you are passing into `SunGraphics2D.draw()` is null. | It means that while handling an event (looks like a repaint in this case) a NullPointerException was thrown. That means you tried to call a method on an object, and it turned out to be null.
Something on line 70 in the paintContents() method of the com.jhlabs.map.layer.Layer class has a null reference. | What causes a NullPointerException in the AWT-EventQueue-0 thread | [
"",
"java",
"drawing",
"awt",
"nullpointerexception",
""
] |
I have a method that accepts a parameter **obj** of type System.Object
Now I want to check if the actual type of obj is:
* A collection type (IEnumerable).
* Anything else.
The first way I thought of is:
```
if (obj is IEnumerable)
// obj is a collection
```
But System.String implements IEnumerable, and **I don't want to treat string as a collection**.
The second way I thought is testing for ICollection instead of IEnumerable, since IEnumerable is more of a potential collection than an actual one. This would leave out string, but also ICollection-Of-T because it does not inherit ICollection (IEnumerable-Of-T is the only generic collection abstraction that's backwards compatible - it inherits IEnumerable).
So I guess the best way is:
```
if (obj is string)
// not a collection
else if (obj is IEnumerable)
// collection
else
// not a collection
```
Is there a better way? | I think you're over complicating this a bit. If you really want to use IEnumerable but exclude System.String, why not just do that directly in code?
```
public static bool IsCollection(object obj) {
return obj is IEnumerable && !(obj is String);
}
``` | If you really only want to test:
```
bool isCollection = obj.GetType().GetInterfaces()
.Any(iface => iface.GetGenericTypeDefinition() == typeof(ICollection<>))
```
But frankly, if you really only want to special-case `string` (why, by the way?), then just do so. If you test for `ICollection<>`, you will treat the result of a LINQ query as "non-collection", for example, for no good reason. | Best way to test if a Type is a collection | [
"",
"c#",
".net",
"ienumerable",
""
] |
I have an Axis (1.4) web service (running on Tomcat 6.0.20) that is working fine until I try to use any class from another project.
I have my web service project and another project containing business logic. I have added the business logic project as a project dependency/reference in my web service project.
```
package MyProject.services;
import BusinessLogic.Core.TestClass;
public class MyServiceImpl implements MyProject.services.MyServiceImpl_PortType {
public java.lang.String getServerStatus() throws java.rmi.RemoteException {
//BusinessLogic.Core.TestClass core = new BusinessLogic.Core.TestClass();
return "This is working fine!";
}
}
```
When I invoke the method above, everything works fine. However, if I uncomment the line in getServerStatus(), I get a NoClassDefFoundException.
The code is ofcourse compiling fine and as far as I can see i have added all dependencies.
The TestClass has only a constructor that prints "Hello" and has no other dependencies.
I'm relatively new to java web services so it is probably just a stupid mistake I have made. Do you have any ideàs? | You say you have them in different projects. If this means WAR-files/folders inside Tomcat, then your problem could be that one web application cannot see any other web application directly (including classpath).
If not, then edit your question to be very specific about what you see and what you expect. | You haven't said how you're building and deploying this. Is TestClass in a jar file somewhere? If so, where is the jar file in the deployed system, and how are your web service classes deployed? | Java Axis web service project dependency not found | [
"",
"java",
"web-services",
"tomcat",
"axis",
""
] |
I had encountered a problem while using **Loki::Singleton**, **Loki::SmartPtr**, and **std::vector** under VC express 2008. Following is my source.
```
#include <iostream>
#include <vector>
#include <loki/Singleton.h>
#include <loki/SmartPtr.h>
class Foo {
public:
std::vector<Loki::SmartPtr<Foo>> children ;
void add() {
Loki::SmartPtr<Foo> f = new Foo ;
children.push_back(f) ;
}
Foo () {
}
~Foo () {
}
} ;
typedef Loki::SingletonHolder<Foo> SingletonFoo ;
int main ()
{
std::cout << "Start" << std::endl ;
SingletonFoo::Instance().add() ;
std::cout << "End" << std::endl ;
}
```
Compiling and linking has no problem, but after the program finished, an error pops:
```
Windows has triggered a breakpoint in test.exe.
This may be due to a corruption of the heap, which indicates a bug in test.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while test.exe has focus.
The output window may have more diagnostic information.
```
It *seems* some memory are deleted twice, I am quite not sure. Is that a bug of VC or I miss used Loki?
Thanks in advance. | As you're using VC, you should be able to run your code in debug mode, step by stp (F10,F11) to see where it breaks.
Anyway, looking at the [Loki singleton code](http://loki-lib.sourceforge.net/html/a00670.html), it seems that the error comes from the assert in SingletonHolder::DestroySingleton() :
```
SingletonHolder<T, CreationPolicy, L, M, X>::DestroySingleton()
00837 {
00838 assert(!destroyed_); // there, but it's a wild guess
00839 CreationPolicy<T>::Destroy(pInstance_);
00840 pInstance_ = 0;
00841 destroyed_ = true;
00842 }
```
That function seems to be called by the LifetimePolicy (here DefaultLifetime) as this code suggests :
```
00800 template
00801 <
00802 class T,
00803 template <class> class CreationPolicy,
00804 template <class> class LifetimePolicy,
00805 template <class, class> class ThreadingModel,
00806 class MutexPolicy
00807 >
00808 void SingletonHolder<T, CreationPolicy,
00809 LifetimePolicy, ThreadingModel, MutexPolicy>::MakeInstance()
00810 {
00811 typename ThreadingModel<SingletonHolder,MutexPolicy>::Lock guard;
00812 (void)guard;
00813
00814 if (!pInstance_)
00815 {
00816 if (destroyed_)
00817 {
00818 destroyed_ = false;
00819 LifetimePolicy<T>::OnDeadReference();
00820 }
00821 pInstance_ = CreationPolicy<T>::Create();
00822 LifetimePolicy<T>::ScheduleDestruction(pInstance_, // here
00823 &DestroySingleton);
00824 }
00825 }
```
I'm not sure why it is called twice, but I guess the pointer to the singleton is first destroyed (the pointer, not the instance) on the SingletonHolder instance destruction and then the LifetimePolicy try to call it's DestroySingleton() function...
But I might be wrong, you'll have to check that. | IMR, you can't use certain smart pointers in stl containers, and this is the exact problem that occurs. If memory serves, it has to do with how the stl containers copy the values not conforming to how smart pointers expect to be used. | Strange memory problem of Loki::Singleton, Loki::SmartPtr, and std::vector | [
"",
"c++",
"c++-loki",
""
] |
```
bool IsTypeAGenericList(Type listType)
{
typeof(IList<>).IsAssignableFrom(listType.GetGenericTypeDefinition())
}
```
returns false when given `typeof(List<int>)`.
I assume this is because the two type parameters can be different, correct? | Actually, this works:
```
public static bool IsGenericList(Type type)
{
if (!type.IsGenericType)
return false;
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length != 1)
return false;
var listType = typeof (IList<>).MakeGenericType(genericArguments);
return listType.IsAssignableFrom(type);
}
``` | This really has to do with open constructed types.
When you say:
```
class List<T> : IList<T>
```
You're actually saying: my class is called List, it has one type parameter called T, and it implements the interface that is constructed from IList<> using **the same T**. So the T in the definition part and the T in the "implements" part both refer to the same type parameter -- you declare it before the colon, then you immediately reference it after the colon.
It gets confusing because `IList<>`'s type parameter is also called T -- but that is a different type parameter entirely. So let's re-declare our concrete class like this:
```
class List<U> : IList<U>
```
This is completely equivalent to the above, only now we can say "U" when we refer to the type parameter of List, and T when we refer to the one from IList. They're different types.
Now it gets easier to see why the generic type definition `List<U>` (which is what you mean when you say `typeof(List<>)`) does not implement the generifc type definition `IList<T>` (which is what you mean when you say `typeof(IList<>)`), but rather it implements the open generic constructed type `IList<U>` (that is, IList constructed with List's own type paremeter).
So basically, generic type definitions never inherit or implement other generic type definitions -- they usually implement open constructed types using their own type parameters with other generic type definitions.
Ripper234's answer shows how to handle this particular case using Reflection, so I won't repeat it; I just wanted to clarify the relationship between those types, and I hope it came out at least somewhat intelligible. | Isn't a generic IList assignable from a generic List? | [
"",
"c#",
".net",
"generics",
"collections",
""
] |
While developing an application it's quite useful to be able to quickly login as different users, with different roles, to see how the application presents itself.
Typing usernames and entering password is no fun, and a waste of time. What I'd like to do is:
* add a page/panel with a list of available usernames;
* clicking on a username will generate an event for Spring security which allows it to recognize the user as authenticated, without entering passwords;
* after clicking the link I am authenticated as the specified user.
*N.B.*: Passwords are hashed and submitted in plain-text using forms, so encoding the passwords in the links is not an option.
*Obviously* this feature will only be present at development time.
How can I achieve this? | I have done it this way for an web application:
I have a configuration parameter in `context.xml` of the server (of course only in the development server). This parameter contains a coma seperated list of usernames and passwords.
The login page (jsp(x)) simply add a extra form and submit button for each username, password item form the context parameter. So if a user clicks on that button the normal login process with the predefined login data is trigged.
Server context.xml
```
...
<Context>
...
<Parameter name="quickLogin"
value="admin:passwd,user:otherPasswd"
override="false" />
</Context>
```
login.jspx
```
...
<!-- Login for debugging purposes -->
<c:forTokens items="${initParam.quickLogin}" delims="," var="loginPassword">
<c:set var="login" value="${fn:split(loginPassword, ':')[0]}" />
<c:set var="password" value="${fn:split(loginPassword, ':')[1]}" />
<form name="debugLogin" action="${form_url}" method="POST" >
<crsf:hiddenCrsfNonce/>
<input type="hidden" name='j_username' value="${fn:escapeXml(login)}" />
<input type="hidden" name='j_password' value="${fn:escapeXml(password)}" />
<input type="submit" value="${fn:escapeXml(login)} login" />
</form>
</c:forTokens>
...
``` | Use InMemoryDaoImpl for development mode. It is very easy to create users and passwords stored in memory:
```
<bean id="userDetailsService" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
admin=admin,ROLE_ADMIN,ROLE_USER
user1=user1,ROLE_USER
user2=user2,ROLE_USER
</value>
</property>
</bean>
```
In development mode inject this to your authentication provider. In production replace it with the proper DB or LDAP implementation. | Spring security pre-authentication for development mode | [
"",
"java",
"spring",
"spring-security",
""
] |
**This is a query that totals up every players game results from a game and displays the players who match the conditions.**
```
select *,
(kills / deaths) as killdeathratio,
(totgames - wins) as losses
from (select gp.name as name,
gp.gameid as gameid,
gp.colour as colour,
Avg(dp.courierkills) as courierkills,
Avg(dp.raxkills) as raxkills,
Avg(dp.towerkills) as towerkills,
Avg(dp.assists) as assists,
Avg(dp.creepdenies) as creepdenies,
Avg(dp.creepkills) as creepkills,
Avg(dp.neutralkills) as neutralkills,
Avg(dp.deaths) as deaths,
Avg(dp.kills) as kills,
sc.score as totalscore,
Count(* ) as totgames,
Sum(case
when ((dg.winner = 1 and dp.newcolour < 6) or
(dg.winner = 2 and dp.newcolour > 6))
then 1
else 0
end) as wins
from gameplayers as gp,
dotagames as dg,
games as ga,
dotaplayers as dp,
scores as sc
where dg.winner <> 0
and dp.gameid = gp.gameid
and dg.gameid = dp.gameid
and dp.gameid = ga.id
and gp.gameid = dg.gameid
and gp.colour = dp.colour
and sc.name = gp.name
group by gp.name
having totgames >= 30
) as h
order by totalscore desc
```
Now I'm not too sure what's the best way to go but what would in your opinion be to optimize this query?
I run a Q6600 @ 2.4ghz, 4gb of ram, 64-bit Linux Ubuntu 9.04 system and this query can take up to 6.7 seconds to run (I do have a huge database).
Also I would like to paginate the results as well and executing extra conditions on top of this query is far too slow....
I use django as a frontend so any methods that include using python +/- django methods would be great. MySQL, Apache2 tweaks are also welcome. And of course, I'm open to changing the query to make it run faster.
Thanks for reading my question; look forward to reading your answers!
**Edit: EXPLAIN QUERY RESULTS**
```
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 783 Using filesort
2 DERIVED sc ALL name,name_2 NULL NULL NULL 2099 Using temporary; Using filesort
2 DERIVED gp ref gameid,colour,name name 17 development.sc.name 2
2 DERIVED ga eq_ref PRIMARY,id,id_2 PRIMARY 4 development.gp.gameid 1 Using index
2 DERIVED dg ref gameid,winner gameid 4 development.ga.id 1 Using where
2 DERIVED dp ref gameid_2,colour gameid_2 4 development.ga.id 10 Using where
``` | First of all, the SQL is badly formatted. The most obvious error is the line splitting before each `AS` clause. Second obvious problem is using implicit joins instead of explicitly using `INNER JOIN ... ON ...`.
Now to answer the actual question.
Without knowing the data or the environment, the first thing I'd look at would be some of the MySQL server settings, such as `sort_buffer` and `key_buffer`. If you haven't changed any of these, go read up on them. The defaults are extremely conservative and can often be raised more than ten times their default, particularly on the large iron like you have.
Having reviewed that, I'd be running pieces of the query to see speed and what `EXPLAIN` says. The effect of indexing can be profound, but MySQL has a "fingers-and-toes" problem where it just can't use more than one per table. And `JOIN`s with filtering can need two. So it has to descend to a rowscan for the other check. But having said that, dicing up the query and trying different combinations will show you where it starts stumbling.
Now you will have an idea where a "tipping point" might be: this is where a small increase in some raw data size, like how much it needs to extract, will result in a big loss of performance as some internal structure gets too big. At this point, you will probably want to raise the temporary tables size. Beware that this kind of optimization is a bit of a black art. :-)
However, there is another approach: denormalization. In a simple implementation, regularly scheduled scripts will run this expensive query from time-to-time and poke the data into a separate table in a structure much closer to what you want to display. There are multiple variations of this approach. It can be possible to keep this up-to-date on-the-fly, either in the application, or using table triggers. At the other extreme, you could allow your application to run the expensive query occasionally, but cache the result for a little while. This is most effective if a lot of people will call it often: even 2 seconds cache on a request that is run 15 times a second will show a visible improvement.
You could find ways of producing the same data by running half-a-dozen queries that each return some of the data, and post-processing the data. You could also run version of your original query that returns more data (which is likely to be much faster because it does less filtering) and post-process that. I have found several times that five simpler, smaller queries can be much faster - an order of magnitude, sometimes two - than one big query that is trying to do it all. | No index will help you since you are scanning entire tables.
As your database grows the query will always get slower.
Consider accumulating the stats : after every game, insert the row for that game, and also increment counters in the player's row, Then you don't need to count() and sum() because the information is available. | What's the best way to optimize this MySQL query? | [
"",
"python",
"mysql",
"django",
"performance",
""
] |
How to check if the web page contains any string queries at the page load? | You can determine if there are any values in the QueryString by checking its count:
```
Request.QueryString.Count > 0;
```
That said if you are trying to prevent a page from erroring because you don't want to access a value that is not there I recommend wrapping query parms up in page properties and returning safe values from the property.
As an example
```
// setting this as protected makes it available in markup
protected string TaskName
{
get { return (string)Request.QueryString["VarName"] ?? String.Empty; }
}
``` | Check for
```
Request.QueryString["QueryStringName"]
```
if you know the particular name and it returns null if there isn't any querystring by that name
or if you want to check the count of querystrings then
```
Request.QueryString.Count
```
and check against 0. If greater than 0 then there is atleast 1 string appended. | QueryString checking | [
"",
"c#",
"asp.net",
""
] |
Which method provides the best performance when removing the time portion from a datetime field in SQL Server?
```
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
```
or
```
b) select cast(convert(char(11), getdate(), 113) as datetime)
```
The second method does send a few more bytes either way but that might not be as important as the speed of the conversion.
Both also appear to be very fast, but there might be a difference in speed when dealing with hundreds-of-thousands or more rows?
Also, is it possible that there are even better methods to get rid of the time portion of a datetime in SQL? | Strictly, method `a` is the least resource intensive:
```
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
```
Proven less CPU intensive for the same total duration a million rows by someone with way too much time on their hands: [Most efficient way in SQL Server to get a date from date+time?](https://stackoverflow.com/questions/133081/most-efficient-way-in-sql-server-to-get-date-from-datetime)
I saw a similar test elsewhere with similar results too.
I prefer the DATEADD/DATEDIFF because:
* varchar is subject to language/dateformat issues
Example: [Why is my CASE expression non-deterministic?](https://stackoverflow.com/q/3596663/27535)
* float relies on internal storage
* it extends to work out first day of month, tomorrow, etc by changing "0" base
**Edit, Oct 2011**
For SQL Server 2008+, you can CAST to `date` i.e. `CAST(getdate() AS date)`. Or just use `date` datatype so no `time` to remove.
**Edit, Jan 2012**
A worked example of how flexible this is: [Need to calculate by rounded time or date figure in sql server](https://stackoverflow.com/questions/8722022/need-to-calculate-by-rounded-time-or-date-figure-in-sql-server/8723311#8723311)
**Edit, May 2012**
Do not use this in WHERE clauses and the like without thinking: adding a function or CAST to a column invalidates index usage. See number 2 here [Common SQL Programming Mistakes](http://www.simple-talk.com/sql/t-sql-programming/ten-common-sql-programming-mistakes/)
Now, this does have an example of later SQL Server optimiser versions managing CAST to date correctly, but *generally* it will be a bad idea ...
**Edit, Sep 2018, for datetime2**
```
DECLARE @datetime2value datetime2 = '02180912 11:45' --this is deliberately within datetime2, year 0218
DECLARE @datetime2epoch datetime2 = '19000101'
select DATEADD(dd, DATEDIFF(dd, @datetime2epoch, @datetime2value), @datetime2epoch)
``` | In SQL Server 2008, you can use:
```
CONVERT(DATE, getdate(), 101)
``` | Best approach to remove time part of datetime in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
"date",
""
] |
I do some c++ programming related to mapping software and mathematical modeling.
Some programs take anywhere from one to five hours to perform and output a result; however, they only consume 50% of my core duo. I tried the code on another dual processor based machine with the same result.
Is there a way to force a program to use all available processer resources and memory?
Note: I'm using ubuntu and g++ | A thread can only run on one core at a time. If you want to use both cores, you need to find a way to do half the work in another thread.
Whether this is possible, and if so how to divide the work between threads, is completely dependent on the specific work you're doing.
To actually create a new thread, see the [Boost.Thread docs](http://www.boost.org/doc/libs/1_39_0/doc/html/thread.html), or the [pthreads docs](http://opengroup.org/onlinepubs/007908799/xsh/pthread.h.html), or the [Win32 API docs](http://msdn.microsoft.com/en-us/library/ms684841(VS.85).aspx).
[Edit: other people have suggested using libraries to handle the threads for you. The reason I didn't mention these is because I have no experience of them, not because I don't think they're a good idea. They probably are, but it all depends on your algorithm and your platform. Threads are almost universal, but beware that multithreaded programming is often difficult: you create a lot of problems for yourself.] | The quickest method would be to read up about openMP and use it to parallelise your program.
Compile with the command `g++ -fopenmp` provided that your g++ version is `>=4` | Force Program / Thread to use 100% of processor(s) resources | [
"",
"c++",
"multithreading",
""
] |
I'm trying to create a simple method to turn a name (first name, last name, middle initial) into a public URL-friendly ID (like Stackoverflow does with question titles). Now people could enter all kinds of crazy characters, umlauts etc., is there something in .NET I can use to normalize it to URL-acceptable/english characters or do I need to write my own method to get this done?
Thank you!
Edit: An example (e.g. via RegEx or other way) would be super helpful!!! :) | Sounds like what you're after is a [Slug Generator](http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-to.html)! | Simple method using [UrlEncode](http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx)
You obviously have to do something to deal with the collisions (prevent them on user creation being sensible but that means you are tied to this structure)
```
s => Regex.Replace(HttpUtility.UrlEncode(s), "%..", "")
```
This is relying on the output of UrlEncode always using two characters for the encoded form and that you are happy to have space convert to '+' | Generate Public "ID Text" (like Stackoverflow) | [
"",
"c#",
"asp.net",
"asp.net-mvc",
""
] |
We have the convention of versioning our builds as [major].[minor].[micro].[revision], e.g. 2.1.2.33546.
Our build-script automatically updates an AssemblyInfo.cs file containing
```
[assembly: AssemblyVersion("x.y.z.w")]
```
in order to embed the version-number in the assembly.
But our Subversion-repository just reached revision #65535, which broke our build.
It turns out that each number in the version-number has a maximum value of 65534 (probably due to a Windows-restriction).
Have you encountered this problem? Any good solutions/workarounds?
We like the scheme of embedding the revision-number and we obviously can't just reset our Subversion-server :-) | A bit more Background information:
[Why are build numbers limited to 65535?](https://learn.microsoft.com/en-us/archive/blogs/msbuild/why-are-build-numbers-limited-to-65535)
As this is unlikely to get changed, your options are:
* Take the Revision Modulo 65535, which means you are back to 1
* Use the Micro-Field in your version number to split the version number by dividing the revision by 1000. That means your version could be 1.0.65.535
* Do not store the SVN Revision in the AssemblyVersion, but instead in the [AssemblyInformationalVersion](https://stackoverflow.com/questions/64602/). That way your Application can still access it for display purposes, although you can't use Windows Explorer anymore to quickly check the SVN Revision
* Do not store the SVN Revision in the AssemblyVersion, but instead in the AssemblyProduct or AssemblyDescription fields. Again, that way your Application can still access it, but also Explorer will now show it in the Property Sheet. | One option might be to just use the `[AssemblyFileVersion]`; this still raises a warning, but it'll build, at least:
```
[assembly: AssemblyFileVersion("1.0.0.80000")]
``` | .NET: Large revision numbers in AssemblyVersionAttribute | [
"",
"c#",
".net",
"svn",
"version-control",
"assemblyversionattribute",
""
] |
I have a `select` form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the `disabled` attribute prevents the user from changing the value, but does not submit the value with the form.
The `readonly` attribute is only available for `input` and `textarea` fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
* Instead of disabling the `select`, disable all of the `option`s and use CSS to gray out the select so it looks like its disabled.
* Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form. | ```
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
```
Where `select_name` is the name that you would normally give the `<select>`.
Another option.
```
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
```
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the `hidden` input either before, or after the `<select>`.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key. | Disable the fields and then enable them before the form is submitted:
jQuery code:
```
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
``` | How to ensure a <select> form field is submitted when it is disabled? | [
"",
"javascript",
"html",
"css",
"forms",
"html-select",
""
] |
I plan on using GCC more (Linux and Windows) and I was wondering if there's an equivalent of the MSVC [debug heap](http://msdn.microsoft.com/en-us/library/974tc9t1%28VS.80%29.aspx) and the [STL checks](http://blogs.msdn.com/vcblog/archive/2007/02/26/stl-destructor-of-bugs.aspx) available for the GCC CRT and STL.
I already know about tools such as Valgrind, but I'm looking for something built in the libraries. | I'm not too familiar with the debug heap and STL checks, but when I have memory problems in GCC on linux I use an environment variable called MALLOC\_CHECK\_ (from malloc(3)):
> Recent versions of Linux libc (later than 5.4.23) and GNU libc (2.x) include a
> malloc implementation which is tunable via environment variables. When
> MALLOC\_CHECK\_ is set, a special (less efficient) implementation is used which is
> designed to be tolerant against simple errors, such as double calls of free()
> with the same argument, or overruns of a single byte (off-by-one bugs). Not all
> such errors can be protected against, however, and memory leaks can result. If
> MALLOC\_CHECK\_ is set to 0, any detected heap corruption is silently ignored; if
> set to 1, a diagnostic is printed on stderr; if set to 2, abort() is called
> immediately. This can be useful because otherwise a crash may happen much
> later, and the true cause for the problem is then very hard to track down.
There is also Electric Fence which can help catch buffer overruns aborting as soon as the overrun / underrun happens. See [libefence(3)](http://perens.com/FreeSoftware/ElectricFence/) for more information. | The STLport version of the standard library at <http://sourceforge.net/projects/stlport/> has a debug mode, which I used to use, and which is recommended by Scott Meyers in Effective STL. I haven't used it for several years now however, so I can't vouch for the current state.
There is also a thread about GCC STL debugging [here](http://osdir.com/ml/gcc.libstdc++.devel/2002-04/msg00209.html), but I once again I can't vouch for the info it gives. | Debug heap/STL debugging equivalent for GCC? | [
"",
"c++",
"debugging",
"gcc",
""
] |
Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. `*args`)
For example, `os.path.join` has a vararg signature:
```
os.path.join(first_component, *rest) -> str
```
Whereas `min` allows either:
```
min(iterable[, key=func]) -> val
min(a, b, c, ...[, key=func]) -> val
```
Whereas `any`/`all` only permit an iterable:
```
any(iterable) -> bool
``` | Consider using varargs when you expect your users to specify the list of arguments as code at the callsite or having a single value is the common case. When you expect your users to get the arguments from somewhere else, don't use varargs. When in doubt, err on the side of not using varargs.
Using your examples, the most common usecase for *os.path.join* is to have a path prefix and append a filename/relative path onto it, so the call usually looks like *os.path.join(prefix, some\_file)*. On the other hand, *any()* is usually used to process a list of data, when you know all the elements you don't use *any([a,b,c])*, you use *a or b or c*. | My rule of thumb is to use it when you might often switch between passing one and multiple parameters. Instead of having two functions (some GUI code for example):
```
def enable_tab(tab_name)
def enable_tabs(tabs_list)
```
or even worse, having just one function
```
def enable_tabs(tabs_list)
```
and using it as `enable_tabls(['tab1'])`, I tend to use just: `def enable_tabs(*tabs)`. Although, seeing something like `enable_tabs('tab1')` looks kind of wrong (because of the plural), I prefer it over the alternatives. | When should I use varargs in designing a Python API? | [
"",
"python",
"api",
"variadic-functions",
""
] |
I'm looking for a way to have `git-commit` wait for standard input. I'm coding this in `PHP`, as my `bash` skills are non-existant, so I thougth doing a regular
```
<?php
$input = trim(fgets(STDIN));
fscanf(STDIN, "%d\n", $line);
?>
```
would do the trick, and wait until I write stuff in to continue, but it just goes ahead and continues executing my PHP script anyways.
The idea behind this is that after I tag a release, git will push `HEAD` to the testing webserver, send a couple of tweets, and let me write in some details about the release in the CHANGELOG.
While I can achieve the writing to a file (using `exec('mate -w')`), I'd like it to hang on until I do a quick test on the server. This would enable me to rollback if I notice any errors (lazy, I know).
Thanks for any help! | Most git hooks either have something special fed to there stdin, or have stdin detached from the terminal. They are all designed to be run non-interactively, so I don't believe that a hook is suitable for what you want to do. You can, of course, manually talk to `/dev/tty` but I don't think that it's a very good idea.
I also don't believe that the 'pre-commit' hook is suitable to your task, surely not every commit that you make will be a release of some sort? A 'post-receive' hook on the testing webserver machine sounds more appropriate. | I need user input in my post-merge hook (written in PHP).
I solved it with this piece of code: `trim(exec('exec < /dev/tty && read input && echo $input'))`
Don't ask, it works ;) | Read from STDIN on a Git pre-commit Hook (with PHP) | [
"",
"php",
"git",
"stdin",
"hook",
""
] |
For an online project I'm working on, I am looking for a open source grammar checker. I have searched Google, with some good results (<http://www.link.cs.cmu.edu/link/>, etc), but I am wondering what all of you think about this topic.
I need this to be able to be used online, versus desktop based, but this is the only real specification I have. If it has a built-in spell checker, that would be a plus, but I can always use another project for that purpose.
Thanks for any help. | LanguageTool should fit the bill:
<http://www.languagetool.org/> | try polishmywriting.com (now afterthedeadline.com)
I think the developer's details are here: <http://news.ycombinator.com/user?id=raffi>
here's an ASK HN post from raffi: <http://news.ycombinator.com/item?id=286162>
UPDATE: you can get an API Key (i.e. for Wordpress): <http://www.afterthedeadline.com/download.slp?platform=Wordpress> | Open Source Grammar Checker | [
"",
"php",
"grammar",
""
] |
Edited........
sorry Sir I was referring this piece of code from Stephen Toub's article..
```
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
```
Can some one explain this to me in short...?? | In short this code initializes a key logger. The passed in parmeter, proc, is a callback function that will be called on every key press.
The using statement just ensures immediate calls to dispose() on the declared variables (curProcess and curModule) when they leave scope, thus properly releasing resources in a expedient manner rather than waiting for the garbage collector to release them which may take a while.
SetWindowsHookEx is a win32 api call that allows you to register a callback to be called when a specific OS level event occurs. In this case the first parameter, WH\_KEYBOARD\_LL, specifies that you would like to register for low level keyboard events. The second parameter is the callback (a Delegate in .Net) that will be called. The third parameter is a windows handle (a pointer managed by the OS) to the module where the callback is located, in this case the main .exe for the process. Note that a process has multiple modules (exe's or dll's) loaded at any given time. The last parameter is the thread id that you would like to monitor; because 0 is passed in, the callback will be called for any key events for any window opened on the OS.
More info [here about SetWindowsHookEx](http://www.pinvoke.net/default.aspx/user32/SetWindowsHookEx.html) | `GetModuleHandle()` is a Windows API which in simple word returns you the handle of the loaded DLL or EXE.
You can see the detailed description of this API at [this link](http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx)
**Straight From MSDN:**
*The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. Therefore, use care when passing the handle to the FreeLibrary function, because doing so can cause a DLL module to be unmapped prematurely.*
*This function must be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used. For example, a thread retrieves a module handle, but before it uses the handle, a second thread frees the module. If the system loads another module, it could reuse the module handle that was recently freed. Therefore, first thread would have a handle to a module different than the one intended.* | What does GetModuleHandle() do in this code? | [
"",
"c#",
"winapi",
""
] |
The only advantage I can see to do:
```
var s = new ClassA();
```
over
```
ClassA s = new ClassA();
```
Is that later if you decide you want ClassB, you only have to change the RHS of the declaration.
I guess if you are enumerating through a collection you can also just to 'var' and then figure out the type later.
Is that it?? Is there some other huge benefit my feeble mind does not see? | It's mostly syntactic sugar. It's really your preference. Unless when using anonymous types, then using var is required. I prefer implicit typing wherever possible though, it really shines with LINQ.
I find it redundant to type out a type twice.
```
List<string> Foo = new List<string>();
```
When I can easily just type var when it's obvious what the type is.
```
var Foo = new List<string>();
``` | `var` is useful for anonymous types, which do not have names for you to use.
```
var point = new {X = 10, Y = 10};
```
This will create an anonymous type with properties X and Y. It's primarily used to support LINQ though. Suppose you have:
```
class Person
{
public String Name {get; set;}
public Int32 Age {get; set;}
public String Address {get; set;}
// Many other fields
}
List<Person> people; // Some list of people
```
Now suppose I want to select only the names and years until age 18 of those people who are under the age of 18:
```
var minors = from person in people where person.Age < 18 select new {Name = person.Name, YearsLeft = 18 - person.Age};
```
Now `minors` contains a `List` of some anonymous type. We can iterate those people with:
```
foreach (var minor in minors)
{
Console.WriteLine("{0} is {1} years away from age 18!", minor.Name, minor.YearsLeft);
}
```
None of this would otherwise be possible; we would need to select the whole Person object and then calculate YearsLeft in our loop, which isn't what we want. | What are the benefits of implicit typing in C# 3.0 >+ | [
"",
"c#",
".net",
"implicit-typing",
""
] |
I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following [this post](https://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis) I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.
However, when I trying to open the <http://hostname/hg/hgwebdir.cgi> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:
1. Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.
2. Created “Hello World” in the same dir and checked that it works fine.
3. Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.
4. Tried to apply two different patches from [Mercurial mailing list](http://www.nabble.com/Mercurial-f24354.html). Since they both are old I haven't success with it.
5. INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.
6. Tried to add 'Content-type: text/html' to the script.
One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped! | Finally I got that "no headers" error returned on any python script error, so I checked script with console interpreter and fixed errors in my config file. And of course I should ask this question at ServerFault instead of StackOverflow - the lack of sleep did the job :) | Some more things that I needed to fix:
* Where the various HOWTOs say to use `c:\whatever\Python26\python.exe -u "%s" "%s"` instead use `c:\whatever\Python26\python.exe -u -O -B "%s" "%s"` -O causes it to also look for .pyo files (not just .py or .pyc, which at least in my version weren't present). -B causes it to not attempt to compile .py files that it finds into .pyo files (which fails due to lacking write permissions)
* I'd installed Python 2.7. Mercurial 1.6.2's .pyo files were compiled with Python 2.6. This resulted in a magic number error. Uninstalling 2.7 and installing 2.6.5 fixed this. (If you're reading this at some point in the future, this point may no longer be relevant - check the name of the DLL in Mercurial's directory, or TortoiseHg's directory, depending on where you took library.zip from)
* hgwebdir.cgi is now just hgweb.cgi - webdir was integrated into it | Hosting Mercurial with IIS 6 | [
"",
"python",
"iis-6",
"mercurial",
""
] |
I have a tightly coupled javascript, where in there are series of if-else checks and multiple ajax calls are made. The ajax calls are nested type. My problem is I am in a deep nested ajax callable function and I want to get out from there gracefully.
The snippet of the code is .
```
function showSubscriptionLightBox() {
$.get("/ajax/get_subscription_lightbox_content.php?feed_id=" + feedid, function(data) {
//Work on the data we receive... and check whether user is logged in.
if(userLoggedIn) {
//Make one more ajax call
$.get("/ajax/is_user_subscribed.php?feed_id=" + feedid, function(data) {
//Work on data again.... and check if user is subscribed.
if(userSubscribed) {
//Then there is popup which comes up, a part of same page and it has a button name "task".
document.getElementById('task').onclick = function() {
if(document.getElementById('email_mode').checked) {
$.ajax({
url : "ajax/is_user_email_verified.php?user_id="+userID,
success : function(data) {
if(!data)
return;
var response;
response = eval("response = " + data);
if(!response)
return;
if(response['email_status'] == 0) {
//Exit from here
}}}
```
......
other part of code..
I want to exit gracefully from javascript, when the response['email\_status'] == 0
Please tell me, how to do this??
I tried the return statement, but it took me to the enclosing function and not outside the script.
Thanks,
Amit | For what it is worth, here is some code from one of my applications. It syncs records using JSONP and AJAX. It first gets an array of object ids from a remote server. It then fetches the record for the object id at the zero index from the host server. Then it sends the record it receives to the remote server. At that point, it continues the process by starting the process with an incremented index into the array of ids. It terminates when the index reaches the end of the array.
```
(function( $ ) {
$.getJSON( 'http://remote.com/admin/record_ids.js?callback=?', function( data ) {
var set_record = function( index ) {
if ( index < data.length ) {
$.get( 'record_get.json', { contact_id: data[ index ] }, function( data ) {
$.getJSON( 'http://remote.com/admin/record_save.js?callback=?', data, function() {
set_record( index + 1 );
});
}, 'json');
}
};
set_record( 0 );
});
})( jQuery );
```
As you can see, when you want to get out gracefully, you just don't call. I can't imagine why you can't just return to stop your code. | I know that with Prototype you could do this with try/catch blocks. You could throw an object from within one of the inner functions and it will travel up the call stack for other functions to intercept. | How to come out from nested ajax | [
"",
"javascript",
"jquery",
""
] |
I'm looking into extending some code that handles automatic opening and reading of Excel files. Ultimately this process needs to be able to run on a server so there is a strict requirement of no dialogs/user interactions required.
Currently this is all working fine for normal files, but now I need to be able to extend this functionality to access files on remote machines such as SharePoint/WebDAV systems.
The problem I've got at the moment in my little test application, is that as soon as I call the Open on an Excel Workbook I get a prompt asking me for my windows credentials. Now I can provide them, or click cancel (I'm assuming this defaults to current user credentials) and the file opens without problem.
What I need to do however, is find a way to access this file without the prompt...
Does anyone have any ideas on how to do this? | In the end I have used the C# webclient class. This can download from a sharepoint site with default, or custom user credentials. | If you are working with Excel 2007 files then you don't need to use automation to open and read the files.
Excel 2007 (xlsx) files use the OpenXML file format. That is, they are basically just a set of XML documents wrapped up as a ZIP file. You can use the .NET Framework's Packaging API and the OpenXML SDK to create, read, and modify these documents.
Here are some resources:
Welcome to the Open XML Format SDK 2.0
<http://msdn.microsoft.com/en-us/library/bb448854(office.14).aspx>
OpenXML Developer
<http://openxmldeveloper.org/default.aspx>
Reading Data from SpreadsheetML
<http://blogs.msdn.com/brian_jones/archive/2008/11/10/reading-data-from-spreadsheetml.aspx> | Opening Excel Workbooks with default Credentials on Sharepoint server | [
"",
"c#",
"sharepoint",
"excel",
""
] |
What's the best way to programmatically cause a Windows XP (or above) machine to wake up at a specific time. (Ideally a lot like how Media Center can start up automatically to record a particular TV program)
I've got a Windows service (written in C#) and I'd like this service to be able to cause the machine it is hosted on to start up at predetermined times.
Are there any BIOS settings or prerequisites (eg. ACPI) that need to be configured for this to work correctly?
This machine would be using dialup or 3G wireless modem, so unfortunately it can't rely on Wake on LAN. | You can use [waitable timers](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687008%28v=vs.85%29.aspx) to wake from a suspend or hibernate state. From what I can find, it is not possible to programmatically wake from normal shut down mode (soft off/S5), in that case, you need to specify a WakeOnRTC alarm in BIOS. To use waitable timers from C#, you need [pInvoke](http://msdn.microsoft.com/en-us/magazine/cc164123.aspx). The import declarations are:
```
public delegate void TimerCompleteDelegate();
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr pArgToCompletionRoutine, bool fResume);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CancelWaitableTimer(IntPtr hTimer);
```
You can use those functions in the following way:
```
public static IntPtr SetWakeAt(DateTime dt)
{
TimerCompleteDelegate timerComplete = null;
// read the manual for SetWaitableTimer to understand how this number is interpreted.
long interval = dt.ToFileTimeUtc();
IntPtr handle = CreateWaitableTimer(IntPtr.Zero, true, "WaitableTimer");
SetWaitableTimer(handle, ref interval, 0, timerComplete, IntPtr.Zero, true);
return handle;
}
```
You can then cancel the waitable timer with `CancelWaitableTimer`, using the returned handle as an argument.
Your program can hibernate and sleep using pInvoke:
```
[DllImport("powrprof.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent);
public static bool Hibernate()
{
return SetSuspendState(true, false, false);
}
public static bool Sleep()
{
return SetSuspendState(false, false, false);
}
```
Your system may not allow programs to let the computer enter hibernation. You can call the following method to allow hibernation:
```
public static bool EnableHibernate()
{
Process p = new Process();
p.StartInfo.FileName = "powercfg.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.Arguments = "/hibernate on"; // this might be different in other locales
return p.Start();
}
``` | The task scheduler program in Win7, taskschd.msc (and I beleive XP as well) can be set to wake the system on different triggers. Those triggers can be schedule, time, event, etc.
In at least Win7, you need to set "Allow Wake Timers" to 'Enabled' for this to work. This setting is found under...
--> Control Panel\Hardware and Sound\Power Options
click - "Edit Plan Settings"
click - "Change advanced power setting"
expand - "Sleep"
Expand - "Allow Wake timers" | Schedule machine to wake up | [
"",
"c#",
"windows-services",
"acpi",
""
] |
I have a pipeline-based application that analyzes text in **different** languages (say, English and Chinese). My **goal** is to have a system that can work in both languages, in a **transparent** way. **NOTE**: This question is long because it has many simple code snippets.
The pipeline is composed of three components (let's call them A, B, and C), and I've created them in the following way so that the components are not tightly coupled:
```
public class Pipeline {
private A componentA;
private B componentB;
private C componentC;
// I really just need the language attribute of Locale,
// but I use it because it's useful to load language specific ResourceBundles.
public Pipeline(Locale locale) {
componentA = new A();
componentB = new B();
componentC = new C();
}
public Output runPipeline(Input) {
Language lang = LanguageIdentifier.identify(Input);
//
ResultOfA resultA = componentA.doSomething(Input);
ResultOfB resultB = componentB.doSomethingElse(resultA); // uses result of A
return componentC.doFinal(resultA, resultB); // uses result of A and B
}
}
```
Now, every component of the pipeline has something inside which is language specific. For example, in order to analyze Chinese text, I need one lib, and for analyzing English text, I need another different lib.
Moreover, some tasks can be done in one language and cannot be done in the other. One solution to this problem is to make every pipeline component abstract (to implement some common methods), and then have a concrete language-specific implementation. Exemplifying with component A, I'd have the following:
```
public abstract class A {
private CommonClass x; // common to all languages
private AnotherCommonClass y; // common to all languages
abstract SomeTemporaryResult getTemp(input); // language specific
abstract AnotherTemporaryResult getAnotherTemp(input); // language specific
public ResultOfA doSomething(input) {
// template method
SomeTemporaryResult t = getTemp(input); // language specific
AnotherTemporaryResult tt = getAnotherTemp(input); // language specific
return ResultOfA(t, tt, x.get(), y.get());
}
}
public class EnglishA extends A {
private EnglishSpecificClass something;
// implementation of the abstract methods ...
}
```
In addition, since each pipeline component is very heavy and I need to reuse them, I thought of creating a **factory** that caches up the component for further use, using a map that uses the language as the key, like so (the other components would work in the same manner):
```
public Enum AFactory {
SINGLETON;
private Map<String, A> cache; // this map will only have one or two keys, is there anything more efficient that I can use, instead of HashMap?
public A getA(Locale locale) {
// lookup by locale.language, and insert if it doesn't exist, et cetera
return cache.get(locale.getLanguage());
}
}
```
So, my **question** is: What do you think of this design? How can it be **improved**? I need the "transparency" because the language can be changed dynamically, based on the text that it's being analyzed. As you can see from the `runPipeline` method, I first identify the language of the Input, and then, based on this, I need to change the pipeline components to the identified language. So, instead of invoking the components directly, maybe I should get them from the factory, like so:
```
public Output runPipeline(Input) {
Language lang = LanguageIdentifier.identify(Input);
ResultOfA resultA = AFactory.getA(lang).doSomething(Input);
ResultOfB resultB = BFactory.getB(lang).doSomethingElse(resultA);
return CFactory.getC(lang).doFinal(resultA, resultB);
}
```
Thank you for reading this far. I very much appreciate every suggestion that you can make on this question. | The factory idea is good, as is the idea, if feasible, to encapsulate the A, B, & C components into single classes for each language. One thing that I would urge you to consider is to use `Interface` inheritance instead of `Class` inheritance. You could then incorporate an engine that would do the `runPipeline` process for you. This is similar to the [Builder/Director pattern](http://en.wikipedia.org/wiki/Builder_pattern). The steps in this process would be as follows:
1. get input
2. use factory method to get correct interface (english/chinese)
3. pass interface into your engine
4. runPipeline and get result
On the `extends` vs `implements` topic, [Allen Holub goes a bit over the top](http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html) to explain the preference for `Interfaces`.
---
Follow up to you comments:
My interpretation of the application of the Builder pattern here would be that you have a `Factory` that would return a `PipelineBuilder`. The `PipelineBuilder` in my design is one that encompases A, B, & C, but you could have separate builders for each if you like. This builder then is given to your `PipelineEngine` which uses the `Builder` to generate your results.
As this makes use of a Factory to provide the Builders, your idea above for a Factory remains in tact, replete with its caching mechanism.
With regard to your choice of `abstract` extension, you do have the choice of giving your `PipelineEngine` ownership of the heavy objects. However, if you do go the `abstract` way, note that the shared fields that you have declared are `private` and therefore would not be available to your subclasses. | I like the basic design. If the classes are simple enough, I might consider consolidating the A/B/C factories into a single class, as it seems there could be some sharing in behavior at that level. I'm assuming that these are really more complex than they appear, though, and that's why that is undesirable.
The basic approach of using Factories to reduce coupling between components is sound, imo. | Architecture/Design of a pipeline-based system. How to improve this code? | [
"",
"java",
"design-patterns",
"oop",
"architecture",
""
] |
Does anyone know of a way to programmatically read the list of References in a VS2008 csproj file? MSBuild does not appear to support this functionality. I'm trying to read the nodes by loading the csproj file into an XmlDocument but, the XPath search does not return any nodes. I'm using the following code:
```
System.Xml.XmlDocument projDefinition = new System.Xml.XmlDocument();
projDefinition.Load(fullProjectPath);
System.Xml.XPath.XPathNavigator navigator = projDefinition.CreateNavigator();
System.Xml.XPath.XPathNodeIterator iterator = navigator.Select(@"/Project/ItemGroup");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
}
```
If I can get the list of ItemGroups I can determine whether it contains Reference information or not. | The XPath should be `/Project/ItemGroup/Reference`, and you have forgot the namespace. I'd just use XLINQ - dealing with namespaces in `XPathNavigator` is rather messy. So:
```
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(fullProjectPath);
IEnumerable<string> references = projDefinition
.Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Reference")
.Select(refElem => refElem.Value);
foreach (string reference in references)
{
Console.WriteLine(reference);
}
``` | Building on @Pavel Minaev's answer, this is what worked for me (notice the added .Attributes line to read the Include attribute)
```
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(@"D:\SomeProject.csproj");
IEnumerable<string> references = projDefinition
.Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Reference")
.Attributes("Include") // This is where the reference is mentioned
.Select(refElem => refElem.Value);
foreach (string reference in references)
{
Console.WriteLine(reference);
}
``` | Reading the list of References from csproj files | [
"",
"c#",
"xpath",
"reference",
".net-3.5",
"csproj",
""
] |
Given this code:
```
int x = 20000;
int y = 20000;
int z = 40000;
// Why is it printing WTF? Isn't 40,000 > 32,767?
if ((x + y) == z) Console.WriteLine("WTF?");
```
And knowing an int can hold −32,768 to +32,767. Why doesn't this cause an overflow? | In C#, the [`int`](http://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx) type is mapped to the [`Int32`](http://msdn.microsoft.com/en-us/library/system.int32.aspx) type, which is always 32-bits, signed.
Even if you use [`short`](http://msdn.microsoft.com/en-us/library/ybs77ex4.aspx), it still won't overflow because `short` + `short` returns an [`int`](http://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx) by default. If you cast this `int` to `short` - `(short)(x + y)` - you'll get an overflowed value. You won't get an exception though. You can use [`checked`](http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx) behavior to get an exception:
```
using System;
namespace TestOverflow
{
class Program
{
static void Main(string[] args)
{
short x = 20000;
short y = 20000;
short z;
Console.WriteLine("Overflowing with default behavior...");
z = (short)(x + y);
Console.WriteLine("Okay! Value is {0}. Press any key to overflow " +
"with 'checked' keyword.", z);
Console.ReadKey(true);
z = checked((short)(x + y));
}
}
}
```
You can find information about [`checked`](http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx) (and [`unchecked`](http://msdn.microsoft.com/en-us/library/a569z7k8.aspx)) on MSDN. It basically boils down to performance, because checking for overflow is a little bit slower than ignoring it (and that's why the default behavior is usually `unchecked`, but I bet that in some compilers/configurations you'll get an exception on the first `z` assignment.) | <http://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx>
Type: int
Range: -2,147,483,648 to 2,147,483,647 | Why doesn't this overflow? | [
"",
"c#",
".net",
"visual-studio",
"int",
"integer-overflow",
""
] |
My questions is: Is there a good solution to use regular expression in GWT?
I'm not satisfied with the use of String.split(regex) for example. GWT translates the Code to JS and then uses the regex as a JS regex. But I cannot use something like the Java Matcher or Java Pattern. But I would need these for group matching.
Is there any possibility or library?
I tried Jakarta Regexp, but I had other problems because GWT doesn't emulate all methods of the Java SDK this library uses.
I want to be able to use something like this on the client side:
```
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
if (matchFound) {
// Get all groups for this match
for (int i=0; i<=matcher.groupCount(); i++) {
String groupStr = matcher.group(i);
System.out.println(groupStr);
}
}
``` | The same code using RegExp could be:
```
// Compile and use regular expression
RegExp regExp = RegExp.compile(patternStr);
MatchResult matcher = regExp.exec(inputStr);
boolean matchFound = matcher != null; // equivalent to regExp.test(inputStr);
if (matchFound) {
// Get all groups for this match
for (int i = 0; i < matcher.getGroupCount(); i++) {
String groupStr = matcher.getGroup(i);
System.out.println(groupStr);
}
}
``` | GWT 2.1 now has a [`RegExp`](http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/regexp/shared/RegExp.html) class that might solve your problem: | Regular Expressions and GWT | [
"",
"java",
"regex",
"gwt",
""
] |
I would like to be able to perform a ping and traceroute from within Python without having to execute the corresponding shell commands so I'd prefer a native python solution. | Running interpreters as root is often frowned upon on security grounds (and of course you DO need to have root permission to access the "raw" socked as needed by the ICMP specs of ping and traceroute!), but if you have no problems with that it's not hard -- e.g., [this post](http://mail.python.org/pipermail/python-list/2005-December/355365.html)(dead?) [or this post](https://mail.python.org/pipermail/python-list/2005-December/308693.html) give a workable ping, and Jeremy Hylton's old [page](http://www.python.org/%7Ejeremy/python.html) has still-usable underlying code for ICMP (both ping and traceroute) though it's written for very old Python versions and needs a litte facelift to shine with modern ones -- but, the concepts ARE all there, in both the URLs I gave you! | If you don't mind using an external module and not using UDP or TCP, [scapy](http://www.secdev.org/projects/scapy/) is an easy solution:
```
from scapy.all import *
target = ["192.168.1.254"]
result, unans = traceroute(target,l4=UDP(sport=RandShort())/DNS(qd=DNSQR(qname="www.google.com")))
```
Or you can use the tcp version
```
from scapy.all import *
target = ["192.168.1.254"]
result, unans = traceroute(target,maxttl=32)
```
Please note you will have to run scapy as root in order to be able to perform these tasks or you will get:
```
socket.error: [Errno 1] Operation not permitted
``` | How can I perform a ping or traceroute using native python? | [
"",
"python",
"ping",
"traceroute",
""
] |
Is there a way to perform the following in a non-recursive fashion:
```
my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
``` | ```
stack = [(my_list, -1)]
while stack:
item, level = stack.pop()
if isinstance(item, list):
for i in reversed(item):
stack.append((i, level+1))
else:
print "\t" * level, item
``` | ```
def print_list(the_list, indent_level=0):
stack = [iter(the_list)]
while stack:
try:
item = stack[-1].next()
except StopIteration:
stack.pop()
indent_level -= 1
continue
if isinstance(item, list):
indent_level += 1
stack.append(iter(item))
else:
print "\t" * indent_level, item
``` | Non-recursive means of printing a list in Python | [
"",
"python",
"recursion",
""
] |
I have a question, how can i make a result set making only list of values. For example i have such values : `('1','2','3')`
And i want to make a sql that returns such table:
```
1
2
3
```
Thanks.
[Edit]
Sorry for wrong question.
Actually list not containing integers, but it contains strings.
I am currently need like ('aa','bb,'cc').
[/Edit] | The best way I've found is using XML.
```
SELECT items.extract('/l/text()').getStringVal() item
FROM TABLE(xmlSequence(
EXTRACT(XMLType(''||
REPLACE('aa,bb,cc',',','')||'')
,'/all/l'))) items;
```
Wish I could take credit but alas : <http://pbarut.blogspot.com/2006/10/binding-list-variable.html>.
Basically what it does is convert the list to an xmldocument then parse it back out. | If you want to write a SQL statement which will take a comma separate list and generate an arbitrary number of actually rows the only real way would be to use a table function, which calls a PL/SQL function which splits the input string and returns the elements as separate rows.
[Check out this link](http://www.databasejournal.com/features/oracle/article.php/2222781/Returning-Rows-Through-a-Table-Function-in-Oracle.htm) for an intro to table-functions.
Alternatively, if you can construct the SQL statement programmatically in your client you can do:
```
SELECT 'aa' FROM DUAL
UNION
SELECT 'bb' FROM DUAL
UNION
SELECT 'cc' FROM DUAL
``` | How to make result set from ('1','2','3')? | [
"",
"sql",
"oracle",
""
] |
I have an ASP.NET application where in my APP\_Code folder I have a class. In that I have the following code to read the content of an XML file which is in my root folder:
```
XmlDocument xmlSiteConfig = new XmlDocument();
xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("../myConfig.xml"));
```
My Root folder is having several folders with nested inner folders for some. From the first level of folders when I call the piece of code in the Appcode class, I am able to load the XML file correctly since the path is correct. Now if I call the same piece of code from an inner folder, I am getting an error. If I change the code to the below it will work fine
```
xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("../../myConfig.xml"));
```
How can I solve this? I don't want to change the file path for various calls to this code.With what piece of code I can solve the issue so that the program will load the XML file irrespective of the calling position. | If it's in the root folder, use this:
```
Server.MapPath("~/myConfig.xml")
```
This will work from any directory. | Prefix your path string with a tilde (~) - this represents the root of the website:
```
xmlSiteConfig.Load(System.Web.HttpContext.Current.Server.MapPath("~/myConfig.xml"));
``` | ASP.NET Server.Mappath problem from inner folders | [
"",
"c#",
"asp.net",
""
] |
Our company has been for a while looking at a file format to hold a large amount of lab sensor data. Each time they run the instrumentation, it generates a file, which we consume and store in a database for trending, etc. A hierarchical format is preferred as it allows us to "group" data. This is a intermediate file format before we place the data into a database. Due to our development environment, this is our priority list:
1) .Net compliant. The API will be used in web services and a client application. We do not have any control over the customer's environment, so a pure.Net solution is best.
2) Speed of reads. Our reads are random, not sequential. The faster the better. If we were not a C# development shop I would say speed is #1.
3) File Size. If the file itself is large, a good compression ratio (86% and higher) is desired.
4) Memory footprint of the reads. Due to the volume of data, we cannot simply read it. each sensor has a time/value pair. This can generate will over 4 million pairs. This has eliminated XML for us.
We have currently looked at [HDF5](http://www.hdfgroup.org/) and found the API is horribly lacking in the .NET arena, cannot do web services, but has size/speed we are looking for. I have looked also into [JSON](http://json.codeplex.com/) and it looked promising but I haven't tried reading a piece of the data back. I have searched the web and not found a lot of file formats that do what we need. Any help is appreciated. | You need a b-tree database, such as:
Sql Server Compact
Also look at SQLite
<http://sqlite.phxsoftware.com/>
CTree is more of an ISAM, if you can dispense with the SQL part
google for ctree
Sorry, I'd link more, SO isn't letting me bc this is a new acct | I think you might be better off storing this information in a table in your database, if you are using SQL Server, a VARBINARY should do the job.
Your table can be hierarchal by including a [Parent] field that can be null for top level nodes.
If you index your lookup value (id of file), random access should be quick. If you are needing compression, you can try using the GZip classes to format your raw byte[] before sticking it in the database.
Using a database for this information gives you the ability to:
1) Run crazy queries, joins, etc.
2) You can index multiple columns for faster lookup of by different key values
3) .Net for sure has multiple APIs
4) Compression can be added if it doesn't affect speed too badly
5) Backing up the data should be a cinch
Does this advice help you out? | hierarchical .Net file format? | [
"",
"c#",
"filesystems",
"hierarchical-data",
"hdf5",
""
] |
The ISO 1998 c++ standard specifies that not explicitly using a return statement in the main is equivalent to use `return 0`.
But what if an implementation has a different standard "no error" code, for example `-1`?
Why not use the standard macro `EXIT_SUCCESS` that would be replaced either by `0` or `-1` or any other value depending on the implementation?
C++ seems to force the semantic of the program, which is not the role of a language which should only describe how the program behaves. Moreover the situation is different for the "error" return value: only `EXIT_FAILURE` is a standard "error" termination flag, with no explicit value, like "1" for example.
What are the reasons of these choices? | Returning zero from `main()` does essentially the same as what you're asking. Returning zero from `main()` does not have to return zero to the host environment.
From the C90/C99/C++98 standard document:
> If the value of status is zero or `EXIT_SUCCESS`, an implementation-defined form of the status successful termination is returned. | Actually, `return 0` won't necessarily return 0! I'm quoting the C standard here, because it's what I know best.
About `return` in `main()`:
> 5.1.2.2.3 Program termination
>
> If the return type of the main function is a type compatible with `int`, a return from the initial call to the `main` function is equivalent to calling the `exit` function with the value returned by the `main` function as its argument;
About `exit()`:
> 7.20.4.3 The exit function
> Synopsis
>
> ```
> #include <stdlib.h>
> void exit(int status);
> ```
>
> [...]
> Finally, control is returned to the host environment. If the value of `status` is zero or
> `EXIT_SUCCESS`, an implementation-defined form of the status *successful termination* is
> returned. | Why default return value of main is 0 and not EXIT_SUCCESS? | [
"",
"c++",
"return",
"standards",
"program-entry-point",
""
] |
I'm looking for a fast way to setup a method of returning a bitmask based on a number. Basically, 4 one bits need to be emitted pre number input. Here's a good idea of what I mean:
foo(1); // returns 0x000F
foo(2); // returns 0x00FF
foo(3); // returns 0x0FFF
foo(4); // returns 0xFFFF
I could just use a big switch statement, but I don't know how wide the input type is in advance. (This is a template function)
Here was the first thing I tried:
```
template <typename T> T foo(unsigned short length)
{
T result = 0xF;
for (unsigned short idx = length; idx > 0; idx--)
{
result = (result << 4 | 0xF);
}
return result;
}
```
but it spends a lot of time doing maintenence on the for loop. Any clever ways of doing this I've not thought of?
Billy3 | How about something like:
```
template <typename T> T foo(unsigned short length)
{
return (T(1) << (length * 4)) - 1;
}
``` | Just create an array that maps each number to the appropriate bitmask.
e.g. map[1] = 0x00F etc.
This will be the fastest. | Fast Bitwise Question in C++ | [
"",
"c++",
"bit-manipulation",
""
] |
> **Possible Duplicate:**
> [How can I find the method that called the current method?](https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method)
Hi,
how can i determine the caller of a method from within the method? Eg:
```
SomeNamespace.SomeClass.SomeMethod() {
OtherClass();
}
OtherClass() {
// Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod
}
```
Thanks | These articles should be of help:
1. <http://iridescence.no/post/GettingtheCurrentStackTrace.aspx>
2. <http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx>
Basically the code looks like this:
```
StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();
message = String.Format("{0}.{1} : {2}",
method.DeclaringType.FullName, method.Name, message);
Console.WriteLine(message);
``` | You need to use the [StackTrace](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe(VS.71).aspx) class
Snippet from the MSDN
```
// skip the current frame, load source information if available
StackTrace st = new StackTrace(new StackFrame(1, true))
Console.WriteLine(" Stack trace built with next level frame: {0}",
st.ToString());
``` | C# Method Caller | [
"",
"c#",
".net",
""
] |
I am very experienced in working with open-source technologies like PHP, MySQL, Apache and others. I feel like home working with them and the code comes to me with little effort.
I recently started playing with the ASP.NET technology (I know it doesn't compare to PHP, or does it?) and everything seems very easy, but still I don't feel like home.
I still can't decide what road to take and with what should I experiment next.
Some of my friends work in small companies with open-source technologies and say that they are in heaven and this is the way to go. On the other hand some of my relatives work in corporate environments and say that they are in heaven and don't want to hear about open-source (although they were very happy with open-source before the corporate period).
I am very confused, I would like you guys to tell me if you had similar experiences and what you did? It would mean a great deal to me. | It may sound trite but do what you enjoy.
There are plenty of PHP and ASP.NET jobs around and even if there was a massive difference, I'm not sure that should even be a factor unless you liked both equally.
It is true that ASP.NET is probably more popular in more "corporate" environments ("enterprise development" is the usual term) so factor in what type of companies and what kind of work you'd like to be doing. | PHP being interpretted, It generally is. PHP being slower than .NET..Nope.
Not when compared to improperly programmed aspx, and VBScript. If you are talking about validated and reduxed html=+>C# OOP,ASPX used properly. It could be faster than another app,depending on the bottlenecks.
You have to Piece PHP frameworks together, to get them just right. PHP can be slaughterd, and still can produce a nasty bit of html Rendering.
APC,PHAR,PHARLANGER are compilers for PHP. Any C based language can pretty much be compiled before deploying.
When in .NET, you have to be careful of the basics.Like HTML,CSS,JS,AJAX,Functions,Interfaces,Class,Objects,etc.
This goes without saying, if you know enough about Unix.. IIS/PowerShell is very easy to port to.
I use Windows MSSQL/IIS/MS SERVER2008RC2 just about 70% of the time. I run into C#,C++,ASPX,PHP,Perl,Curl,Asmx,ASPX,.ini,.htaccess/.htpassword(.htprotect)
This is one of those senarios that you can try to prove 1 technology over another..
In the end, the technology suitable for the project; ALWAYS DEPENDS on the PROJECT....
Hope this clears up some of the Hogwash about Cagey programmers that haven't the sense/experience to look at the big Picture (what really matters)
Just My 2 bits.
Rob AKA Graphicalinsight | .NET or PHP, Corporate or Open-Source? | [
"",
"php",
"asp.net",
"open-source",
""
] |
I am programming with Visual Studio 2008 and making a web application using .NET Framework 3.5 with C#. All DAL linked with an powerfull entity framework wrapper (similar to the one that VS.net 2010 would use.) I'm having a textbox used for a search on first and lastname. The problem i'm having is that i'm using AJAX Control Toolkit 2.0 which provides an Auto complete extender but, by using a WebServices (asmx). Is there any other way to use the auto complete without using a webservice?
Regards,
Simon
P.s.: Sorry for my english, i do my best :)! | Yes, you can mark a method in a codebehind file as a webmethod:
```
public partial class Products : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string[] GetTerms(string prefix)
{
// Put your logic here
}
}
```
See [ASP.NET AJAX callbacks to Web Methods in ASPX pages](https://web.archive.org/web/20200803212711/http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx).
Also, if you use NET 3.5 you can use the later Toolkit which incorporates [the ComboBox](https://dotnet.microsoft.com/en-us/apps/aspnet), which is essentially a databound auto-complete control. | You don't need to implement a separate web-service in order to provide a textbox with auto-complete functionality, however, you *do* need to provide the autocomplete extender with a valid *web method* that it can use to call upon to retrieve the list of matching entries.
The key properties for the AutoComplete functionality of the AutoComplete Extender control are the ServiceMethod and ServicePath properties. The ServiceMethod specifies the name of the *web method* that is called by the AJAX framework to retrieve the matching items for your autocomplete dropdown, and the ServicePath property specifies the full path and filename for the file that will contain the ServiceMethod properties' method. Note that the ServicePath property is, however, optional.
If you omit the ServicePath property, the AJAX framework will attempt to find the ServiceMethod web method in the code within your actual web page upon which the textbox and autocomplete extender are sited. This is usually in a "code-behind" file.
From the [AutoComplete Sample](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx) page:
> * ServiceMethod - The web service method to be called. The signature of
> this method must match the following:
>
> [System.Web.Services.WebMethod]
> [System.Web.Script.Services.ScriptMethod]
> public string[] GetCompletionList(string prefixText, int count)
> { ... }
>
> Note that you can replace
> "GetCompletionList" with a name of
> your choice, but the return type and
> parameter name and type must exactly
> match, including case.
>
> * ServicePath - The path to the web service that the extender will pull the word\sentence completions from.
> **If this is not provided, the service method should be a page method.** | Textbox with autocomplete | [
"",
"c#",
"asp.net",
"entity-framework",
"autocomplete",
"ajaxcontroltoolkit",
""
] |
Due to the well-known issues with calling virtual methods from inside constructors and destructors, I commonly end up with classes that need a final-setup method to be called just after their constructor, and a pre-teardown method to be called just before their destructor, like this:
```
MyObject * obj = new MyObject;
obj->Initialize(); // virtual method call, required after ctor for (obj) to run properly
[...]
obj->AboutToDelete(); // virtual method call, required before dtor for (obj) to clean up properly
delete obj;
```
This works, but it carries with it the risk that the caller will forget to call either or both of those methods at the appropriate times.
So the question is: Is there any way in C++ to get those methods to be called automatically, so the caller doesn't have to remember to do call them? (I'm guessing there isn't, but I thought I'd ask anyway just in case there is some clever way to do it) | The main problem with adding post-constructors to C++ is that nobody has yet established how to deal with post-post-constructors, post-post-post-constructors, etc.
The underlying theory is that objects have invariants. This invariant is established by the constructor. Once it has been established, methods of that class can be called. With the introduction of designs that would require post-constructors, you are introducing situations in which class invariants do not become established once the constructor has run. Therefore, it would be equally unsafe to allow calls to virtual functions from post-constructors, and you immediately lose the one apparent benefit they seemed to have.
As your example shows (probably without you realizing), they're not needed:
```
MyObject * obj = new MyObject;
obj->Initialize(); // virtual method call, required after ctor for (obj) to run properly
obj->AboutToDelete(); // virtual method call, required before dtor for (obj) to clean up properly
delete obj;
```
Let's show *why* these methods are not needed. These two calls can invoke virtual functions from `MyObject` or one of its bases. However, `MyObject::MyObject()` can safely call those functions too. There is nothing that happens after `MyObject::MyObject()` returns which would make `obj->Initialize()` safe. So either `obj->Initialize()` is wrong or its call can be moved to `MyObject::MyObject()`. The same logic applies in reverse to `obj->AboutToDelete()`. The most derived destructor will run first and it can still call all virtual functions, including `AboutToDelete()`. | While there is no automated way, you could force the users hand by denying users access to the destructor on that type and declaring a special delete method. In this method you could do the virtual calls you'd like. Creation can take a similar approach which a static factory method.
```
class MyObject {
...
public:
static MyObject* Create() {
MyObject* pObject = new MyObject();
pObject->Initialize();
return pObject;
}
Delete() {
this->AboutToDelete();
delete this;
}
private:
MyObject() { ... }
virtual ~MyObject() { ... }
};
```
Now it is not possible to call "delete obj;" unless the call site has access to MyObject private members. | Is there any automated way to implement post-constructor and pre-destructor virtual method calls? | [
"",
"c++",
"methods",
"virtual-destructor",
""
] |
How to improve the performance of an ASP.NET application? Which are are the fields I should take care? The application includes DB connections and Image Parsing etc. | The book [Improving .NET Application Performance and Scalability](http://msdn.microsoft.com/en-us/library/ms998530.aspx) has a chapter on [Improving ASP.NET Performance](http://msdn.microsoft.com/en-us/library/ms998549.aspx), that might be worth reading. The full book is online at MSDN, and is also available as a [PDF download](http://www.microsoft.com/downloads/details.aspx?FamilyId=8A2E454D-F30E-4E72-B531-75384A0F1C47&displaylang=en). | [10 Tips for Writing High-Performance Web Applications](http://msdn.microsoft.com/en-us/magazine/cc163854.aspx)
[20 Tips to Improve ASP.net Application Performance](http://www.realsoftwaredevelopment.com/20-tips-to-improve-aspnet-application-performance/)
Bye | Improve the performance of an ASP.NET application | [
"",
"c#",
"asp.net",
"performance",
""
] |
[This question](https://stackoverflow.com/questions/733652/select-a-random-sample-of-results-from-an-oracle-query "This question") answers the question on how to select a random sample from oracle which is exactly what I need. I do not understand however the difference between that solution
```
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
dbms_random.value
)
WHERE rownum <= 1000
```
and something like
```
select * from mytable where rownum<=1000 order by dbms_random.value
```
When I query using the first method, it takes a long time (still hasn't finished) but when I query using the 2nd method, it's very quick but the results don't seem to be random.
Appreciate and advice/direction y'all can provide.
Thanks!
JC | Oracle selects the rows based on the criteria **before** any sorting takes place. Therefore, your second query can be read as:
1. Select the first 1000 rows from `mytable`
2. Sort these 1000 rows by random value
Therefore, you will always be getting the same 1000 rows, just in a random order. The first query forces Oracle to sort **all** rows randomly first:
1. Sort all rows by random value
2. Select the first 1000 of these randomly ordered rows | In `Oracle`, `ORDER BY` is evaluated after `ROWNUM`.
This query:
```
SELECT id, ROWNUM
FROM (
SELECT NULL AS id
FROM dual
UNION ALL
SELECT 1 AS id
FROM dual
)
ORDER BY
id
```
will retrieve the following:
```
id rownum
---- ------
1 2
NULL 1
```
Your first query first orders values by random, the selects the first thousand records, which takes long.
The second query first selects `1000` records, then sorts them in random order, which is of course faster but the results are not random. | Difference between two queries when selecting a random sample from oracle | [
"",
"sql",
"oracle",
"random",
""
] |
Below is my code I am trying to get to work but I really have very little knowledge of array and `foreach`. So it doesn't work correctly
I need to show a `dropdown` select form to the browser with the contents of the array
I also need to have the item selected if it is == to $mycountry
Lastly, I would like to show the USA and UK at the top of my list
Can anyone tell me how I can do al this
```
<?PHP
$countries = array(
"217" => "Turkenistan",
"218" => "Turks and Caicos Islands",
"219" => "Tuvalu",
"220" => "Uganda",
"221" => "Ukraine",
"222" => "United Arab Emirates",
"223" => "United Kingdom (Great Britain)",
"224" => "United States");
$mycountry = 224;
?>
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" />
<?php
$countryCounter = 1;
$amtOfCountries = count($countries);
//foreach ($country as $id => $c) {
for( $_top=0; $_top < $amtOfCountries; $_top++ ){
if ($countryCounter == $amtOfCountries) {
echo "<option value=\"$countries[0]\" SELECTED>$countries[1]</option>";
} else {
echo "<option value=\"$countries[0]\">$countries[1]</option>";
$countryCounter++;
}
}
?>
</select>
``` | ```
foreach ($countries as $key => $country) {
$selected = ""
if ($key == $mycountry) $selected = ' selected="selected" ';
print '<option value=' . $key . $selected . '>' . $country . '</option>';
}
```
Basically, for every element within the array, you are breaking it into its key and its value (ie $countreis[key] = value). Once you get your head around arrays (and they can be very confusing) it will make coding a million times easier.
(For some reason the syntax highlighting / formatting is not working in my code...) | I'm going to guess you are looking for:
```
foreach($countries as $id => $country) {
echo '<option value="$id"' . ($mycountry==$id?'selected="selected"':'') . '>' . $country . '</option>';
}
```
As for making sure that the U.S. and U.K. are on top, make sure that those 2 are on top of your array (that would be the very easiest). | php array and foreach? | [
"",
"php",
"arrays",
"loops",
"for-loop",
""
] |
The title pretty much says it all.
If I have something like (from PHP site examples):
```
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies></movies>
XML;
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');
$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');
$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');
echo("<pre>".htmlspecialchars($sxe->asXML())."</pre>");
die();
```
I end up outputing a long string like so:
```
<?xml version="1.0" standalone="yes"?>
<movies type="documentary"><movie><title>PHP2: More Parser Stories</title><plot>This is all about the people who make it work.</plot><characters><character><name>Mr. Parser</name><actor>John Doe</actor></character></characters><rating type="stars">5</rating></movie></movies>
```
This is fine for a program consumer, but for debugging/human tasks, does anyone know how to get this into a nice indented format? | There's a variety of solutions in the comments on the [PHP manual page for SimpleXMLElement](http://php.net/manual/en/function.simplexml-element-asXML.php). Not very efficient, but certainly terse, is a solution by Anonymous
```
$dom = dom_import_simplexml($simpleXml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();
```
The PHP manual page comments are often good sources for common needs, as long as you filter out the patently wrong stuff first. | The above didn't work for me, I found this worked:
```
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
``` | Format output of $SimpleXML->asXML(); | [
"",
"php",
"xml",
"formatting",
"simplexml",
""
] |
I have a collection class with an Equals method that I want to pass in a method to do equality checking between each item. Furthermore, I want to allow the delegate type to operate on superclasses of T as well as T itself:
```
public delegate bool EqualityComparer<T>(T x, T y);
public class Collection<T>
{
//...
public bool Equals<U>(Collection<T> other, EqualityComparer<U> eq) where T : U
{
// code using eq delegate to test equality between
// members of this and other collection
}
}
```
Unfortunately, the compiler borks over this ('Collection.Equals()' does not define type parameter 'T'). Is there any way of specifying this type of constraint/operation? | No, I'm afraid you can't specify a constraint like that. (I've wanted it too on occasion.)
You *could* write a static generic method with two type parameters in a non-generic class though:
```
public delegate bool EqualityComparer<T>(T x, T y);
public class Collection
{
public static Equals<T, U>(Collection<T> first,
Collection<T> second,
EqualityComparer<U> comparer) where T : U
{
}
}
```
and you could even make that call an instance method on the generic class if you like:
```
// Implementing the static method:
return first.Equals(second, new EqualityComparer<T>(comparer));
```
where the collection's instance method would just be:
```
public bool Equals(Collection<T> other, EqualityComparer<T> eq)
{
// ...
}
```
This uses the contravariance available for *creating* delegates from C# 2 onwards. | As Jon said you cannot reference the T within the constrain in that way since it is declared at the class level.
If you can write the method without access to the private state of the collection (or with their being internal) then you can rewrite like so:
```
public class Collection<T>
{
...
}
public static class CollectionExtentions
{
public static bool Equals<T,U>(
this Collection<T> first,
Collection<T> other,
EqualityComparer<U> eq) where T : U
{
... // legal to use eq here on the T values with collections
}
}
```
Incidentally I suggest you use `Func<T,T,bool>` rather than your own named delegate | Can I specify a 'supertype' relation in C# generic constraints? | [
"",
"c#",
"generics",
"delegates",
"constraints",
""
] |
I have a large project which was originally written in C#1.1 and is now targeting C#2.0. There are several classes which have methods which take an ArrayList parameter I would like to start to move these to accept `List<T>` as a parameter, but this can't be done all at one time, so I need to accept both parameters.
My main reason for the migration is so that `List<>` objects will be accepted as parameters, but I would also like to take advantage of type safety.
Have considered
1) Creating overloads and duplicating the code.
This has the advantage of allowing me to mark the old style code as obsolete, but obviously duplicating code is bad.
2) Changing the parameter to IEnumerable :
This has the advantage of working with both old and new code, but is not type-safe as it will accept `List<T1>` where it should be `List<T2>`
3) Re-writing the methods to take a `List<T>` parameter and writing a thin wrapper which takes an ArrayList parameter and copies the items to a new `List<T>` and then calls the main method. This also has the advantage of allowing me to mark the old style code as obsolete. It will have a slight performance/GC hit.
4) Creating three overloads. One private method which take IEnumerable and two public wrapper methods (one for ArrayList and one for `List<T>`) which just call the private method.
This also has the advantage of allowing me to mark the old style code as obsolete. Not sure whether it has any dis-advantages other than having three methods.
I am leaning towards 4, but am I overlooking anything? | Definitely use a variant of #2, where you shoot for `IEnumerable<T>` rather than `List<T>`. For those that need more than `IEnumerable<T>`, your goal should be `IList<T>`.
For those methods that can migrate to `IEnumerable<T>`, you can move them to just IEnumerable for the short term, and in this way avoid needing to maintain two copies of the method. Then, after most of your ArrayLists are gone you can complete the move to `IEnumerable<T>` with very little effort. | I would create a complete suite of `IEnumerable<t>` (or perhaps `IList<t>` if you need manipulation rather than enumeration capabilities) parameter methods and make those your default methods that do all of the work. For compatibility with your ArrayList contract, you could then have your original ArrayList methods translate themselves into `IEnumerable<t>` and call the `IEnumerable` methods.
Basically shift the work to your more type-safe option and create a facade for your old contract. | Migrating parameters from ArrayList to List<T> | [
"",
"c#",
"generics",
".net-2.0",
""
] |
I am using [this](http://www.codeproject.com/KB/files/directorychangewatcher.aspx) implementation of ReadDirectoryChangesW to monitor changes to the desktop. My program plans to run some small program when a file is created on the desktop.
Now the problem I am running into is when I create a new shortcut via the right click context menu ReadDirectoryChangesW gets a notification saying the file has been created, but right after it gets another notification saying the file has been deleted. I have been running into this problem since Windows Vista.
Anyone have any idea what could be wrong? Is there another function I should be using to monitor directory changes specific to Vista and 7?
Thanks,
Krishna | I managed to resolve this issue. I still don't know why I am getting all those strange ReadDirectyChangesW events but I got my end result so I am leaving this question be.
Thanks for all the help. | Have you defined any filters: you might be seeing the shortcut being recreated (and not matching your filter).
Explorer tends to create things with a fixed name, and then rename them. So `ReadDirectoryChangesW` will see multiple changes.
Additional thoughts:
Note, the buffer with the change notification can contain multiple notifications, are all being read.
What does [Process Monitor](http://technet.microsoft.com/sysinternals/bb896645) show at the same time? | ReadDirectoryChangesW thinks shortcut is being deleted right after creation | [
"",
"c++",
"windows-vista",
"shortcut",
"readdirectorychangesw",
""
] |
I wrote a method which creates a copy of linked list.
Can you guys think of any method better than this?
```
public static Node Duplicate(Node n)
{
Stack<Node> s = new Stack<Node>();
while (n != null)
{
Node n2 = new Node();
n2.Data = n.Data;
s.Push(n2);
n = n.Next;
}
Node temp = null;
while (s.Count > 0)
{
Node n3 = s.Pop();
n3.Next = temp;
temp = n3;
}
return temp;
}
``` | You can do it in one pass, something like this:
```
public static Node Duplicate(Node n)
{
// handle the degenerate case of an empty list
if (n == null) {
return null;
}
// create the head node, keeping it for later return
Node first = new Node();
first.Data = n.Data;
// the 'temp' pointer points to the current "last" node in the new list
Node temp = first;
n = n.Next;
while (n != null)
{
Node n2 = new Node();
n2.Data = n.Data;
// modify the Next pointer of the last node to point to the new last node
temp.Next = n2;
temp = n2;
n = n.Next;
}
return first;
}
``` | @Greg, I took your code and made it even a bit shorter :)
```
public static Node Duplicate(Node n)
{
// Handle the degenerate case of an empty list
if (n == null) return null;
// Create the head node, keeping it for later return
Node first = new Node();
Node current = first;
do
{
// Copy the data of the Node
current.Data = n.Data;
current = (current.Next = new Node());
n = n.Next;
} while (n != null)
return first;
}
```
The Do-While construct is often forgotten, but fits well here.
A Node.Clone() method would be nice as well.
+1 to Greg for the nice example. | Duplicate a linked list | [
"",
"c#",
"linked-list",
""
] |
I'm trying to read a [BMP](http://en.wikipedia.org/wiki/BMP_file_format) file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I execute:
```
fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
```
I get:
> ValueError: invalid literal for int() with base 10: 'F#\x13'
What I want to do is reading those four bytes as an integer, but it seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly? | The `read` method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in `struct` module: <http://docs.python.org/library/struct.html>.
```
import struct
print(struct.unpack('i', fin.read(4)))
```
Note that `unpack` always returns a tuple, so `struct.unpack('i', fin.read(4))[0]` gives the integer value that you are after.
You should probably use the format string `'<i'` (< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order. | An alternative method which does not make use of 'struct.unpack()' would be to use [NumPy](http://en.wikipedia.org/wiki/NumPy):
```
import numpy as np
f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)
```
'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See [`numpy.fromfile`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html).
Personally prefer using NumPy to work with array/matrix data as it is a lot faster than using Python lists. | Reading integers from binary file in Python | [
"",
"python",
"file",
"binary",
"integer",
""
] |
I am having the strangest issue with a site i am developing. On the homepage i have a flash slide show which displays fine in IE. However it does not appear in Firefox but instead leaves a white space.
I am using SWFObject to display the flash. I knows its at least firing as the holding image is removed. However if i right click on the white area i get an HTML context menu not a flash menu which suggests its not even writing the flash object to the page let alone loading the flash SWF file.
If i save the source of the homepage to a static HTML and upload that to the server it works fine.
Could this be anything to do with the file encoding or http headers?
I've tried so many things like removing content, JS, CSS etc. The fact that a static version of the file works but the server driven ones does not is driving me mad.
The server is running Joomla CMS.
The code is:
```
<script type="text/javascript" src="/scripts/swfobject.js"></script>
<script type="text/javascript">swfobject.embedSWF("/flash/loader.swf", "flashContent", "960", "310", "9.0.0", "/flash/expressInstall.swf");</script>
```
HTML Code:
```
<div class="middle" id="flashContent">
<img class="panelBgImage" src="/images/main/Home.jpg" title="Home"/>
</div>
```
A temporary version of the site can be seen @ <http://slc.synterax.com/> (Available until 06/08/2009)
Thanks in advance
---
having the script in the head portion of the page certainly fixed it for me. However i have seen problems in the past with flash and firefox and swf. the only way i got around it was to reinstall flash :(
i take it works fine in the other browsers? | I've had a similar issue for the past day and a half, and I've found the answer. The swfobject.embedSWF should be in the HEAD portion of the document (I'm guessing that is not possible for Joomla). If you can't move it there, there is a [workaround here](http://groups.google.com/group/swfobject/browse_thread/thread/4f42a25b869e2430/ecae1a7351a9d4c4?lnk=raot). You can add this line of code:
```
swfobject.switchOffAutoHideShow();
```
just before your swfobject.embedSWF | Did you try the dynamic method?
<http://code.google.com/p/swfobject/wiki/documentation>
Also, what is firebug's NET panel telling you? does it show the request for the file? If so what is the server response? | Strange Firefox SWFObject display issue | [
"",
"javascript",
"flash",
"firefox",
"joomla",
"swfobject",
""
] |
We've turned on verbose GC logging to keep track of a known memory leak and got the following entries in the log:
```
...
3607872.687: [GC 471630K->390767K(462208K), 0.0325540 secs]
3607873.213: [GC-- 458095K->462181K(462208K), 0.2757790 secs]
3607873.488: [Full GC 462181K->382186K(462208K), 1.5346420 secs]
...
```
I understand the first and third of those, but what does the "GC--" one mean? | I got these kind of lines in my gc output:
```
44871.602: [GC-- [PSYoungGen: 342848K->342848K(345600K)] 961401K->1041877K(1044672K), 0.1018780 secs] [Times: user=0.16 sys=0.00, real=0.11 secs]
```
I read Yishai's answer and it would make sense, but I wanted to see it for myself in the Java GC source code, when the JVM prints "--" in the GC log and why.
Because to my knowledge "Parallel Scavenge" of the Young Gen is a stop-the-world GC, so there **couldn't be any objects created parallel** to this GC. (see <https://blogs.oracle.com/jonthecollector/entry/our_collectors>)
You can find this in the jdk source code (see <http://hg.openjdk.java.net/jdk7/jdk7>)
g1CollectedHeap.cpp and psScavenge.cpp
```
jdk7-ee67ee3bd597/hotspot/src/share$ egrep -h -A2 -B5 -r '"\-\-"' *
# G1 Collector
if (evacuation_failed()) {
remove_self_forwarding_pointers();
if (PrintGCDetails) {
gclog_or_tty->print(" (to-space overflow)");
} else if (PrintGC) {
gclog_or_tty->print("--");
}
}
--
# Parallel Scavenge Collector
promotion_failure_occurred = promotion_failed();
if (promotion_failure_occurred) {
clean_up_failed_promotion();
if (PrintGC) {
gclog_or_tty->print("--");
}
}
```
# Reason for GC-- with the Parallel Scavenge Collector
The Young GC encountered a promotion failure (see <http://mail.openjdk.java.net/pipermail/hotspot-gc-use/2010-March/000567.html>):
> > A promotion failure is a scavenge that does not succeed because there is not enough space in the old gen to do all the needed promotions. The scavenge
> > is in essence unwound and then a full STW compaction of the entire heap is done.
'Not enough space' doesn't necessarily mean that there isn't enough space in old, but that the old space is heavily fragmented (see <http://blog.ragozin.info/2011/10/java-cg-hotspots-cms-and-heap.html>):
> > [...] it is impossible to find certain amount of continuous memory to promote particular large object, even though total number of free bytes is large enough.
These two JVM options could help you analyze your heap fragmentation (see <http://blog.ragozin.info/2011/10/java-cg-hotspots-cms-and-heap.html>):
```
-XX:+PrintPromotionFailure
-XX:PrintFLSStatistics=1
```
# Reason for GC-- with the G1 Collector
A evacuation failure with the G1 is when a Survivor Region hasn't enough space for the surviving objects from a Young Region.
I don't know if the G1 Collector responds to a evacuation failure with a Full GC or not. | I got the following from [here](http://java.sun.com/docs/hotspot/gc1.4.2/):
> The first two lines indicate you had
> two minor collections and one major
> one. The numbers before and after the
> arrow indicate the combined size of
> live objects before and after garbage
> collection, respectively. After minor
> collections the count includes objects
> that aren't necessarily alive but
> can't be reclaimed, either because
> they are directly alive, or because
> they are within or referenced from the
> tenured generation. The number in
> parenthesis s the total available
> space, not counting the space in the
> permanent generation, which is the
> total heap minus one The format for
> the major collection in the third line
> is similar. The flag
> -XX:+PrintGCDetails prints additional information about the collections. The
> additional information printed with
> this flag is liable to change with
> each version of the virtual machine.
> The additional output with the
> -XX:+PrintGCDetails flag in particular changes with the needs of the
> development of the Java Virtual
> Machine. of the survivor spaces. The
> minor collection took about a quarter
> of a second. | What does "GC--" mean in a java garbage collection log? | [
"",
"java",
"logging",
"garbage-collection",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.