Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I was wondering if there is a way to copy ALL my settings from ReSharper (including the StyleCop for ReSharper settings and the keyboard bindings I have set for ReSharper) from one PC to another? | Since the export option within Resharper is only for code styles, you'll need to be a bit craftier for *all* settings.
From [Peter Ritchie's blog](http://msmvps.com/blogs/peterritchie/archive/2008/05/19/resharper-4-0-eap-settings-and-installing-latest-build.aspx)...
> ...the settings are stored in
> "%userprofile%\application
> data\jetbrains\resharper\v4.0\vs9.0".
> There are a couple of xml files in
> there that store your settings.
> Before you upgrade to the latest
> build, just copy those to another
> directory.
>
> It's very likely that the format of
> these files has changed since the last
> build so copying the backups over the
> new version could possibly make
> Resharper to blow-up. So, use with
> caution.
I have Resharper 4.1 so instead of "...\v4.0\vs9.0" it's actually "...\v4.1\vs9.0" (obvious, I know, but worth mentioning).
I'm not sure about StyleCop settings, but this should work for most other settings (keyboard scheme, code completion settings, etc...). | There is a [R# settings manager](http://rsm.codeplex.com/) plugin for resharper that stores all of this I think, including stylecop settings | Transfer all ReSharper Settings between PCs | [
"",
"c#",
"visual-studio",
"resharper",
"stylecop",
""
] |
I expect the result of the third query below to contain id=732. It doesn't. Why is that?
```
mysql> SELECT id FROM match ORDER BY id DESC LIMIT 5 ;
+------------+
| id |
+------------+
| 732 |
| 730 |
| 655 |
| 458 |
| 456 |
+------------+
5 rows in set (0.00 sec)
mysql> SELECT id FROM email ORDER BY id DESC LIMIT 5 ;
+------------+
| id |
+------------+
| 731 |
| 727 |
| 725 |
| 724 |
| 723 |
+------------+
5 rows in set (0.00 sec)
mysql> SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email ) ;
Empty set (0.00 sec)
```
There are three NULL entries in table email.id, and no NULL entries in match.id.
The full table / queries can be seen at [<http://pastebin.ca/1462094>](http://pastebin.ca/1462094) | From [**documentation**](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html):
> To comply with the `SQL` standard, `IN` returns `NULL` not only if the expression on the left hand side is `NULL`, but also if no match is found in the list and one of the expressions in the list is `NULL`.
This is exactly your case.
Both `IN` and `NOT IN` return `NULL` which is not an acceptable condition for `WHERE` clause.
Rewrite your query as follows:
```
SELECT *
FROM match m
WHERE NOT EXISTS
(
SELECT 1
FROM email e
WHERE e.id = m.id
)
``` | ... or if you really want to use `NOT IN` you can use
```
SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)
``` | MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result | [
"",
"sql",
"mysql",
""
] |
In c++ Is it OK to include same namespace twice?
compiler wont give any error but still will it affect in anyway
Thanks,
**EDIT:**
I meant
```
using namespace std;
// . . STUFF
using namespace std;
``` | It depends what you mean by 'include'. Saying:
```
using namespace std;
...
using namespace std:
```
is OK. But saying:
```
namespace X {
...
namespace X {
```
would create a nested namespace called X::X, which is probably not what you wanted. | This usage is fine, if it's what your talking about:
**File: foo.h**
```
namespace tools
{
class Widget
{
...
};
}
```
**file: bar.h**
```
namespace tools
{
class Gizmo
{
...
};
}
``` | Using a namespace twice | [
"",
"c++",
"namespaces",
""
] |
Sorry guys, I've been running a mock asking questions on how to integrate wikipedia data into my application and frankly I don't think I've had any success on my end as I've been trying all the ideas and kinda giving up when I read a dead end or obstacle. I'll try to explain what exactly I am trying to do here.
I have a simple directory of locations like cities and countries. My application is a simple php based ajax based application with a search and browse facility. People sign up and associate themselves with a city and when a user browses cities - he/ she can see people and companies in that city i.e. whoever is a part of our system that is.
That part is kinda easily set up on its own and is working fine. The thing is that My search results would be in the format i.e. some one searches for lets say Beijing. It would return in a three tabbed interface box:
1. First Tab would have an infobox containig city information for Beijing
2. Seond would be a country tab holding an infobox of the country information from CHina
3. Third tab would have Listings of all contacts in Beijing.
The content for the first two tabs should come from Wikipedia.Now I'm totally lost with what would be the best way to get this done and furthermore once decide on a methodology then - how do I do it and make it such that its quite robust.
A couple of ideas good and bad as I have been able to digest so far are:
1. Run a curl request directly to wikipedia and parse the returning data everytime a search is made. There is no need to maintain a local copy in this case of the data on wikipedia. The other issue is that its wholly reliant on data from a remote third location and I doubt it is feasible to do a request everytime to wikipedia to retrieve basic information. Plus considering that data on wikipedia requires to be parsed at every request - thats gonna surmount to heavy server loads.. or am I speculating here.
2. Take a Download of the wikipedia dump and query that. Well I've downloaded the entire database but its gonna take forever to import all the tables from the xml dump. Plus consider the fact that I just want to extract a list of countries and cities and their info boxes - alot of the information in the dump is of no use to me.
3. Make my own local tables and create a cron[I'll explain why cron job here] script that would somehow parse all teh countries and cities pages on wikipedia and convert them to a format I can use in my tables. However honestly speaking I do not need all of the information in the infoboxes as is infact if I could just even get the basic markup of the infoboxes as is - that would be more than enough for me. Like:
Title of Country | Infobox Raw text
I can personally extract stuff like coordinates and other details if I want.
I even tried downloading third party datasets from infochiumps and dbpedia but the dataset from infochimps is incomplete and didn't contain all the information I wanted to display - plus with dbpedia I have absolutely no idea what to do with the csv file I downloaded of infoboxes and am afraid that it might also not be complete.
But that is just part of the issue here. I want a way to show the wikipedia information - I'll have all the links point to wikipedia as well as a nice info from wikipedia displayed properly all around BUT the issue is that I need a way that periodically I can update the information I have from wikipedia so atleast I don't have totally outdated data. Like well lets say a system that can check and if we have a new country or new location it can parse the information and somehow retrieve it. I'm relying on categories of countries and cities in wikipedia for this here but frankly all these ideas are on paper, partially coded and its a huge mess.
I'm programming in PHP and MySQL and my deadline is fast approaching - given the above situation and requirements what is the best and most practical method to follow and implement. I am totally open to ideas - practical examples if anyone has done something similar - I would love to hear :D | I'd suggest the following
* Query the city from wikipedia when it (the city) is created in your DB
* Parse the data, store a local copy with the timestamp of the last update
* on access, update the data if it is necessary. You can display the old one with a watermark saying it is ... days old and now updating. Then change to the freshly aquired one when the update is done. You've said you are using AJAX, so it won't be a problem
It would minimize the queryes to wikipedia and your service won't show empty pages even when wikipedia is unreachable. | A couple things I can think of:
1. Just display the wikipedia data in an iframe on your site.
2. Use Curl to get the html from wikipedia, then use a custom stylesheet to style it and/or hide the parts you don't want displayed.
Trying to actually parse the HTML and pull out the pieces you want is going to be a giant pain, and is most likely going to have to be custom for each city. Better off getting something simple working for now then going back and improving it later if you decide you really need to. | Wikipedia integration issue - need to finally sort this out 101 | [
"",
"php",
"mysql",
"wikipedia",
"data-mining",
""
] |
May I know how can I determine whether a component is found in JPanel?
```
boolean isThisComponentFoundInJPanel(Component c)
{
Component[] components = jPanel.getComponents();
for (Component component : components) {
if (c== component) {
return true;
}
}
return false;
}
```
Using loop is not efficient. Is there any better way? | ```
if (c.getParent() == jPanel)
```
Call recursively if you don't want immediate parent-child relationships (which is probably the case in a well-designed panel).
... although in a well-designed panel, it's very questionable why you'd need to know whether a component is contained in the panel. | you can use
```
jPanel.isAncestorOf(component)
```
for recursive search | A Fast Way to Determine Whether A Componet is Found In JPanel | [
"",
"java",
"swing",
""
] |
Note: A possible solution needs only work in Firefox 3.0, my app doesn't allow access from IE! =)
I have a link that, when clicked, will display a lightbox to the user:
```
<a href="#" onclick="show_lightbox();return false;">show lightbox</a>
```
My problem is that when the lightbox is displayed, the focus remains on the link. So if the user presses the up or down keys, they end up scrolling the main document, not the lightbox that is displayed!
I've tried to set the focus to the lightbox element using code like this
```
function focus_on_lightbox() {
document.getElementById('lightbox_content').focus();
}
```
This works fine if I type it in the firebug console, but will not work if I include it at the end of the onclick snippet. It appears as though I can't change the focus away from the link from code executed inside the onclick event?
---
-- Update 1
I've tried something like this before
```
<a href="#" onclick="show_lightbox();focus_on_lightbox();return false;">show lightbox</a>
```
and I've modified function to add some debugging output, as follows
```
function focus_on_lightbox() {
console.log('hihi');
console.log(document.activeElement);
document.getElementById('lightbox_content').focus();
console.log(document.activeElement);
}
```
The output is as follows
```
hihi
<a onclick="closePopup();lightbox('apartment_detail','11619');focus_on_lightbox();return false;" href="#">
<a onclick="closePopup();lightbox('apartment_detail','11619');focus_on_lightbox();return false;" href="#">
```
So the focus before I did anything was on the link and after I tried to change the focus it still remained on the link?
Not sure if it matters, but I use ajax to load the lightbox, as follows
```
new Ajax.Updater(lightbox_content_id, url, {asynchronous:true, evalScripts:true, onLoading:show_lightbox_loading(), onComplete:focus_on_lightbox() });
```
I tried to set the focus after the ajax complete, but also, no luck.
What am I missing?
---
I've been trying to make a solution work that was suggested below by trying to set the focus, seeing if I succeeded by checking document.activeElement, if not, wait 100 milliseconds and try again. If I use the following function, it will work
```
function focus_on_lightbox() {
var seconds_waited = 0
pause(100);
var current_focus = document.activeElement
while (document.getElementById(lightbox_content_id) != current_focus && seconds_waited < 2000)
{
document.getElementById(lightbox_content_id).focus();
console.log(document.activeElement);
pause(100);
current_focus = document.activeElement
seconds_waited += 100;
}
}
```
However, if I remove the firebug debugging statment console.log, the function stops working!! I have no idea why this would be the case?? Why would outputting a variable to the firebug console affect weather focus is moved to the element or not? Does the console.log statement affect focus? perhaps by bringing the focus to the console debugging window? | Here is the function that finally worked
```
function focus_on_lightbox(seconds) {
var seconds_waited
seconds_waited = seconds
document.getElementById(lightbox_content_id).focus();
seconds_waited += 100;
if (document.getElementById(lightbox_content_id) != document.activeElement && seconds_waited < 2000)
setTimeout("focus_on_lightbox(" + seconds_waited + ");", 100);
{
}
}
```
So why did console.log seem to affect setting the focus? Before I was using this function to pause between attempts of changing the focus.
```
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
```
This causes javascript to constantly be doing something and I think it wasn't giving the document time to render or update or something. The console.log seemed to break this lock and give the page a chance to change its focus.
When I changed approaches to using the timeout to pause between attempts, console.log was no longer needed!
Thanks bmoeskau for pointing me in the right direction. | I think your problem is calling your focus method after return false. your code should be like that :
```
<a href="#"
onclick="show_lightbox();focus_on_lightbox();return false;">
show lightbox
</a>
``` | Changing Javascript Focus in onClick event? | [
"",
"javascript",
"prototypejs",
"firebug",
"dom-events",
""
] |
I've tried to use the code Sun posted on their [Proxy usage page](http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html), and I tried to use the DebugProxy to print which method is invoked. The thing is, the object I'm creating a proxy for, needs to have an argument. If I try to create the proxy with an argument to the constructor, I receive the following error :
```
Exception in thread "main" java.lang.ClassCastException: $Proxy0 cannot be cast to myPackage.myClass
```
I created the proxy like this :
```
MyClass mc = (MyClass) DebugProxy.newInstance(new MyClass(props));
```
How can I create a proxy instance, and still call the right constructor ? | TheJDK-generated proxy is not of the same class type as the object you're proxying. Instead, it implements the same interfaces of the target object. You need to cast to one of those interface types.
If you look at the example on the page you linked to, it's casting to Foo, not FooImpl. | Does your class implement some interface you're trying to test? Proxy classes only implement methods from an interface. If you want to print before/after each method of a class (be it for metrics or debugging) I would suggesting using Aspect oriented programming (AOP). I've never done it myself, but I hear [AspectJ](http://www.eclipse.org/aspectj/) is what you want.
```
public interface SomeInterface {
public void someMethod();
}
public MyClass implements SomeInterface {
...
}
// DebugProxy doesn't return your class, but a class which implements all of the interfaces
// you class implements
SomeInterface mc = (SomeInterface ) DebugProxy.newInstance(new MyClass(props));
``` | How can I use a dynamic proxy on constructors that take arguments? | [
"",
"java",
"dynamic-proxy",
""
] |
Visual Studio is the defacto editor, but what are our other options that avoid a heavy UI while still integrating with a C# build chain?
Looking for options which preferably use `vi` or `vim` directly, and those which emulate some or all of the functionality of `vi` and/or `vim`. | I'm not connected with the company in any way, but I've heard very good things about [ViEmu](http://www.viemu.com/). If the price were a little lower, I'd get it myself, because I love the editing power of Vim. | Here is a [guide on Vim C# compiling](http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html).
---
In response to the comments -
It sounds like your goal is to have a fully functional IDE that works cross platform for C# development, not necessarily to use VIM. If that's the case, you can use [MonoDevelop](http://monodevelop.com/) on all platforms (including Windows, but that's a bit trickier), and since you're probably already using the mono compilers on your other platforms, this might be a nicer option. | How can I use VIM to do .Net Development | [
"",
"c#",
".net",
"vim",
"compilation",
""
] |
Assuming I have the superclass A, and the subclasses A1 and A2 which inherit from A, how could I get the subclass type of the variables in the code below?
```
A _a1 = new A1();
A _a2 = new A2();
// Need type of A1 and A2 given the variables _a1 and _a2.
```
Also, if I had another subclass A2\_1 which is a sublcass of A2, how do I get the lowest subclass type given code below?
```
A _a2_1 = new A2_1();
```
EDIT: Thanks for answers. What a boo boo. Over thinking the problem and didn't even try GetType(). =/ | `Console.WriteLine(_a1.GetType());`
GetType can return the run-time type of the variable irrespective of declaration type. | You could use the GetType() method:
```
Type type = _a1.GetType();
Type subtype = _a2_1.GetType();
``` | Finding out subclass type of an instance declared as a superclass | [
"",
"c#",
"oop",
"types",
""
] |
I have two loops running in my code, I want to use an element from an array as the key in a second array, but am unsure how to do this with Smarty.
"`$dateAndUserForEdit.$key.edit_id`" contains an integer (pulled from the db)
I want to use that value as the key in a second loop, which runs fine if I harcode in the integer:
```
{foreach from=$historyOfRepair.9 key=key item=i}
```
Pseudo code for the sort of thing I've been trying is:
```
{foreach from=$historyOfRepair.{$dateAndUserForEdit.$key.edit_id} key=key item=i}
```
But of course, this doesn't work! Can anybody help? | Something like next may work (cannot test currently):
```
{assign var=edit_id value=$dateAndUserForEdit.$key.edit_id}
{foreach from=$historyOfRepair.$edit_id key=key item=i}
``` | I don't know if this is trick was needed for old versions, but you can (as I believe for quite some time now) do this:
given that:
```
{$someArray.someKey=9}
{$otherArray.9=$someValue}
```
Equivalent:
```
{$otherArray[$someARray.$someKey]=$someValue}
``` | Using an array as the key to a second array in Smarty (PHP) | [
"",
"php",
"smarty",
""
] |
I'm developing a swing app which suits the MVC pattern and I'm wondering about the best place to store settings such as width/height, xml files location... Should those settings be avaiable also only through the Model? Should I use a global static class? A singleton?
Thanks in advance | I'd suggest [`java.util.prefs`](http://java.sun.com/javase/6/docs/api/java/util/prefs/package-summary.html)`.`[`Preferences`](http://java.sun.com/javase/6/docs/api/java/util/prefs/Preferences.html).
Then you don't have to invent anything. | I actually used the [Swing Application Framework](http://www.netbeans.org/kb/60/java/gui-saf.html) in NetBeans with great success here which deals with it in a way where you dont have to worry too much about design patterns :)
Before than I'd normally store the window properties in properties files and I had a separate config model/service that I injected where it was needed to retrieve the properties when re-creating windows.
I cannot see why it would need to be a Singleton. Probably an anti-pattern in this case. | What's the best way to store app settings? (MVC) | [
"",
"java",
"model-view-controller",
"swing",
"config",
""
] |
So I have a datagrid that I need to add custom sorting for and I also need to know the exact order of the sort.
I have read in order to do this I need to implement a custom icollectionview and bind it to the datagrid.
The problem I am having is that the documentation Microsoft gives on this interface is not that great. Does anyone know how to do this or have any good tutorials on how to implement this interface for silverlight? | I'm looking for the same, and found this article from [Colin Eberhardt](http://www.scottlogic.co.uk/blog/wpf/2009/04/binding-a-silverlight-datagrid-to-dynamic-data-via-idictionary/comment-page-1/). It shows how to implement sorting using an implementation of ICollectionView
If you figure out how to implement filtering, please let me know. | Silverlight 3 now supports and implementation of the ICollectionView, called [PagedCollectionView](http://timheuer.com/blog/archive/2009/04/08/grouping-in-silverlight-datagrid.aspx).
This provides sorting and grouping, but not filtering. | Silverlight and icollectionview | [
"",
"c#",
"asp.net",
"wpf",
"silverlight",
""
] |
How does one go about finding the month name in C#? I don't want to write a huge `switch` statement or `if` statement on the month `int`. In VB.Net you can use `MonthName()`, but what about C#? | You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
```
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
```
Hope this helps! | Use the "MMMM" format specifier:
```
string month = dateTime.ToString("MMMM");
``` | How to get the month name in C#? | [
"",
"c#",
"datetime",
""
] |
i have a CheckBoxList with a list of services that the user can execute... some of this services can't be executed with some of the others, some services can only be executed alone etc..
All this rules are stored in my database.
Is there anyway for me to disable/enable (make unclikable) checkboxlist items that can't be executed together, in the event of clicking(checking/unchecking) a service?
I just can't figure it out, Since I even don't know how to get the Id of the last clicked item.. | You will need to capture the event which fires when a button is selected; when you get the event for a specific button being selected, you can set the other buttons which it is exclusive to to be Disabled. | checkBox1.Visible = false;
if they can't see it, they can't click it. | Dynamically disable/enable checkboxlist items | [
"",
"c#",
".net",
"visual-studio-2008",
"checkbox",
""
] |
Given a SQL statement:
```
select id from myTable
where id = -1
```
How do I iterate through each of the results? I want to perform a specific operation for each result e.g (in pseudocode):
```
foreach (result from my statment)
{
delete all rows from myOtherTable that has a value of result;
}
```
How would I write a SQL statement to do this?
N.B. The reason I want to do this is because the table whose row I want to delete is being referenced by other tables. So I thought that if I delete the rows from all that tables that reference this particular row and then delete the row everything will be fine. | You don't need to iterate in SQL, you can write in one statement
```
DELETE FROM myOtherTable
WHERE myTableId IN (SELECT id FROM myTable WHERE id = -1)
```
**EDIT:**
After you complete the first delete you can then delete from the original table
```
DELETE FROM myTable WHERE id = -1
``` | The other answers are essentially correct. Good SQL code generally requires a different way of thinking than how procedural or object-oriented programmers are used to thinking. SQL is optimized to perform operations on sets of data. Your `DELETE FROM table2 WHERE ...` statement is sent to the back-end database, where the database knows how to most efficiently take that statement and perform the operation across the whole set of results at once.
One of the reasons for this is because many large-scale applications have a front-end (user interface), a server that accepts the user requests (e.g.: web server), and a back end database server. It would be in efficient for the SQL code being executed on the web server (where your SQL script may originate from) to have to make single requests to the back end to delete each item in the table in a loop. The messages sent from the web server to the database server would look something like this (pseudo-code messages):
```
web server -> Find all elements matching criteria -> database
web server <- (return of matching elements) <- database
web server -> Delete element[0] from myTable -> database
web server <- (delete result was ok) <- database
web server -> Delete element[1] from myTable -> database
web server <- (delete result was ok) <- database
....
```
Whereas, the SQL approach would produce messages back and forth that would look more like:
```
web server -> Find all elements matching criteria -> database
and delete them.
web server <- (delete result was ok) <- database
``` | How can I iterate through a list of rows returned from a select statement in SQL? | [
"",
"sql",
"database",
""
] |
I have the following scenario:
List 1 has 20 items of type TItem, List 2 has 5 items of the same type. List 1 already contains the items from List 2 but in a different state. I want to overwrite the 5 items in List 1 with the items from List 2.
I thought a join might work, but I want to overwrite the items in List 1, not join them together and have duplicates.
There is a unique key that can be used to find which items to overwrite in List 1 the key is of type int | You could use the built in Linq .Except() but it wants an IEqualityComparer so use [a fluid version](http://www.codeproject.com/KB/linq/Fluid_Linq_Except.aspx?display=PrintAll) of .Except() instead.
Assuming an object with an integer key as you indicated:
```
public class Item
{
public int Key { get; set; }
public int Value { get; set; }
public override string ToString()
{
return String.Format("{{{0}:{1}}}", Key, Value);
}
}
```
The original list of objects can be merged with the changed one as follows:
```
IEnumerable<Item> original = new[] { 1, 2, 3, 4, 5 }.Select(x => new Item
{
Key = x,
Value = x
});
IEnumerable<Item> changed = new[] { 2, 3, 5 }.Select(x => new Item
{
Key = x,
Value = x * x
});
IEnumerable<Item> result = original.Except(changed, x => x.Key).Concat(changed);
result.ForEach(Console.WriteLine);
```
output:
```
{1:1}
{4:4}
{2:4}
{3:9}
{5:25}
``` | LINQ isn't used to perform actual modifications to the underlying data sources; it's strictly a query language. You could, of course, do an outer join on `List2` from `List1` and select `List2`'s entity if it's not null and `List1`'s entity if it is, but that is going to give you an `IEnumerable<>` of the results; it won't actually modify the collection. You could do a `ToList()` on the result and assign it to `List1`, but that would change the reference; I don't know if that would affect the rest of your application.
Taking your question literally, in that you want to REPLACE the items in `List1` with those from `List2` if they exist, then you'll have to do that manually in a `for` loop over `List1`, checking for the existence of a corresponding entry in `List2` and replacing the `List1` entry by index with that from `List2`. | Overlay/Join two collections with Linq | [
"",
"c#",
"linq",
"collections",
""
] |
Currently have a DataTable, but wish to stream it to the user via a WebHandler. [FileHelpers](http://www.filehelpers.com/) has `CommonEngine.DataTableToCsv(dt, "file.csv")`. However it saves it to a file. How can I save it to a stream instead? I know how to do it when I know the columns in advanced or they don't change, but I want to generate the column headings straight from the data table.
If I know the columns I just create the class:
```
[DelimitedRecord(",")]
public class MailMergeFields
{
[FieldQuoted()]
public string FirstName;
[FieldQuoted()]
public string LastName;
}
```
Then use FileHelperEngine and add the records:
```
FileHelperEngine engine = new FileHelperEngine(typeof(MailMergeFields));
MailMergeFields[] merge = new MailMergeFields[dt.Rows.Count + 1];
// add headers
merge[0] = new MailMergeFields();
merge[0].FirstName = "FirstName";
merge[0].LastName = "LastName";
int i = 1;
// add records
foreach (DataRow dr in dt.Rows)
{
merge[i] = new MailMergeFields();
merge[i].FirstName = dr["Forename"];
merge[i].LastName = dr["Surname"];
i++;
}
```
Finally write to a stream:
```
TextWriter writer = new StringWriter();
engine.WriteStream(writer, merge);
context.Response.Write(writer.ToString());
```
Unfortunately as I don't know the columns before hand, I can't create the class before hand. | You can just write something quickly yourself:
```
public static class Extensions
{
public static string ToCSV(this DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
}
```
And to test:
```
public static void Main()
{
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add("John Doe", "45");
table.Rows.Add("Jane Doe", "35");
table.Rows.Add("Jack Doe", "27");
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(table.ToCSV());
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
}
```
EDIT: Re your comments:
It depends on how you want your csv formatted but generally if the text contains special characters, you want to enclose it in double quotes ie: "my,text". You can add checking in the code that creates the csv to check for special characters and encloses the text in double quotes if it is. As for the .NET 2.0 thing, just create it as a helper method in your class or remove the word this in the method declaration and call it like so : Extensions.ToCsv(table); | **Update 1**
I have modified it to use StreamWriter instead, add an option to check if you need column headers in your output.
```
public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
if (dtSource == null || writer == null) return false;
if (includeHeader)
{
string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", columnNames));
writer.Flush();
}
foreach (DataRow row in dtSource.Rows)
{
string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", fields));
writer.Flush();
}
return true;
}
```
As you can see, you can choose the output by initial StreamWriter, if you use
StreamWriter(Stream BaseStream), you can write csv into MemeryStream, FileStream, etc.
**Origin**
I have an easy datatable to csv function, it serves me well:
```
public static void DataTableToCsv(DataTable dt, string csvFile)
{
StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(csvFile, sb.ToString(), Encoding.Default);
}
``` | Convert DataTable to CSV stream | [
"",
"c#",
"csv",
"datatable",
""
] |
I want to be able to instantiate any object in my application with this kind of code:
```
SmartForm smartForm = SmartForm.Create("id = 23");
Customer customer = Customer.Create("id = 222");
```
I'm now debating what Create() should return if that object does not exist.
* if Create() returns an **empty object**, then this is kind of a "null pattern" and I can still pass that object around my application and call methods on it, which makes programming with this model convenient and easy
* if Create() returns **null**, then I need to check after every instantiation if the object equals null or not, which makes programming a bit more tedious but more explicit. A problem with this is that if you forget to check the null, your application could work for a long time without you knowing that you're not checking null, then break all of a sudden
* if Create() **throws an exception**, it is basically the same as returning null but makes programming even more tedious by making you create a try, next, finally block for each instantiation, but you could throw various types of exceptions (which you can't with the null solution) which could bubble up so that you could more explicitly handle the deep errors on your UI, so this I would think is the most robust solution although would produce try/catch code bloat
So it seems to be a **lightness/robustness trade off**. **Does anyone have any experience of making a decision along these lines** where you experienced advantages or disadvantages because of that decision?
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestFactory234.Models
{
public class SmartForm : Item
{
public string IdCode { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int LabelWidth { get; set; }
public SmartForm() { }
private SmartForm(string loadCode)
{
_loadCode = loadCode;
TryToInstantiateFromDatabase();
}
public static SmartForm Create(string loadCode)
{
SmartForm smartForm = new SmartForm(loadCode);
if (!smartForm.IsEmpty())
{
return smartForm;
}
else
{
return null;
}
}
}
}
``` | It depends - if it fails because something is definitely wrong, then an exception makes programming *easier* - you don't write a try/catch around each call, you just let the exception bubble up. Compare that with checking for a null/blank return value and *then* throwing an exception.
This sounds like the right time to use `ArgumentException`, IMO.
If you find yourself creating try/catch "bloat", have a look at why you really need to catch the exceptions rather than just letting them bubble up. | If it returns a blank object, then you'll proceed assuming it's valid - or have to do some kind of elaborate test to see if it's blank or not. If it returns null you'll always have to check for null (and maybe that's fine). I would prefer that it threw an exception - assuming that your code is designed so that this isn't supposed to happen. If this is a normal scenario, then null might be a better choice. | If .Create() can't instantiate, should it return empty object, null, or throw an exception? | [
"",
"c#",
"exception",
"instantiation",
""
] |
Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks! | You can print a carriage return `\r` to put the cursor back to the beginning of line.
Example:
```
public class ProgressDemo {
static void updateProgress(double progressPercentage) {
final int width = 50; // progress bar width in chars
System.out.print("\r[");
int i = 0;
for (; i <= (int)(progressPercentage*width); i++) {
System.out.print(".");
}
for (; i < width; i++) {
System.out.print(" ");
}
System.out.print("]");
}
public static void main(String[] args) {
try {
for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
updateProgress(progressPercentage);
Thread.sleep(20);
}
} catch (InterruptedException e) {}
}
}
``` | I use following code:
```
public static void main(String[] args) {
long total = 235;
long startTime = System.currentTimeMillis();
for (int i = 1; i <= total; i = i + 3) {
try {
Thread.sleep(50);
printProgress(startTime, total, i);
} catch (InterruptedException e) {
}
}
}
private static void printProgress(long startTime, long total, long current) {
long eta = current == 0 ? 0 :
(total - current) * (System.currentTimeMillis() - startTime) / current;
String etaHms = current == 0 ? "N/A" :
String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));
StringBuilder string = new StringBuilder(140);
int percent = (int) (current * 100 / total);
string
.append('\r')
.append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
.append(String.format(" %d%% [", percent))
.append(String.join("", Collections.nCopies(percent, "=")))
.append('>')
.append(String.join("", Collections.nCopies(100 - percent, " ")))
.append(']')
.append(String.join("", Collections.nCopies(current == 0 ? (int) (Math.log10(total)) : (int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
.append(String.format(" %d/%d, ETA: %s", current, total, etaHms));
System.out.print(string);
}
```
The result:
[](https://i.stack.imgur.com/RF1kC.gif) | Console based progress in Java | [
"",
"java",
"console",
"progress-bar",
"refresh",
""
] |
Our website is an AJAX website that makes no page requests after the initial start up of our website. Information is communicated with the server through XMLHttpRequests.
Our website allows users to work online and offline without a connection during a user session. When a connection is detected our website "synchronizes" with the server.
Our problem is that if the internet browser running our website crashes while the user has no internet connection the user cant begin working with our website until she/he gets an internet connection back.
Is it possible to have the browser cache the initial startup page (index.html) along with the other website resources and have the browser use the cached version of the startup page when there is no internet connection present? | (Google)[Gears](http://gears.google.com) is exactly about this. | Today: use a [service worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers).
---
The 2009 answer: Not with any technology built into common web browsers.
You can achieve this using (the defunct in 2020) [Google Gears](http://gears.google.com/), but that requires the user to install a plugin and grant permission to your website to use it. Google Docs and Wordpress are examples of web applications that use this. | Is it possible to cache a whole website including start html page and startup with no internet connection? | [
"",
"javascript",
"html",
"ajax",
"caching",
"offline",
""
] |
I have a query that counts the price of all items between two dates. Here is the select statement:
```
SELECT SUM(Price) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
```
You can assume all of the tables have been set up properly.
If I do a select between two dates and there are no items within that date range, the function returns NULL as the TotalPrice rather than 0.
How can I make sure that if no records are found, 0 gets returned rather than NULL? | Most database servers have a [COALESCE](http://msdn.microsoft.com/en-us/library/aa258244.aspx) function, which will return the first argument that is non-null, so the following should do what you want:
```
SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
```
Since there seems to be a lot of discussion about
> COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:
```
SELECT coalesce(SUM(column_id),0) AS TotalPrice
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)
```
Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0. | You can use [`ISNULL()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql?view=sql-server-ver15).
```
SELECT ISNULL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
```
That should do the trick. | How can I change NULL to 0 when getting a single value from a SQL function? | [
"",
"sql",
"t-sql",
"null",
"sum",
""
] |
In SQL Server, how can I achieve selecting many fields (without an agregation function) and apply the DISTINCT statement to only one particular field?
For instance: if I have a table where I store user actions, the pseudo-schema would be like this:
```
UserActions
------------
id,
User,
Action
insertDate
```
I want to get the latest actions for a given user without repeating the field 'Action'?
For instance, if the table contents are:
```
1, john, update, 01/01/09
2, john, update, 01/02/09
3, john, update, 01/03/09
4, john, delete, 01/04/09
5, john, insert, 01/05/09
6, john, delete, 01/06/09
```
I would like to get:
```
6, john, delete, 01/06/09
5, john, insert, 01/05/09
3, john, update, 01/03/09
```
Many thanks in advance. | The inner query should select the max id for each action for the user 'john', the outer query will select those records that match the collection of ids in the inner query so you should only get the last of each action for the specified user.
```
select id, user, action, insertDate
from userActions
where id in (select max(id)
from userActions
where user ='john'
group by action)
``` | Ignoring the OPs need for no aggregate functions (still not sure why...)
The issue I have with the given answer is :
1. It's not dynamic to allow for any other user - say 'mark'
2. it assumes that the max(id) for an action will match the latest action - the test data suggests that, but I wouldn't assume that as a rule.
so with those in mind a more dynamic query needs to be built
with 2 more rows added to the test data
```
7, john, update, 04/01/09
8, mark, insert, 01/02/09
```
the answer doesn't give what the OP wanted
Here's my first draft quickly - will tidy later
```
select
userActions.id,
userActions.[user],
userActions.Action,
userActions.insertDate
from
userActions
join
(
select
[user], action, max(insertdate) as maxinsertdate
from userActions
group by
[user], action
) aggsubquery
on userActions.[user] = aggsubquery.[user]
and userActions.action = aggsubquery.action
and userActions.insertdate = aggsubquery.maxinsertdate
```
Update....
2nd version uses the ID to get a distinct row where there may be more than one occurance of an action by a particular user, i.e. if the test data also had the following row
```
9, john, delete, 06/01/09
```
then you would need to decide between row id 6 and row id 9 as to which one to return. I arbitrarily chose to use max(id), as I guess the data is important and not the row id
```
select
max(userActions.id) as id,
userActions.[user],
userActions.Action,
userActions.insertDate
from
userActions
join
(
select
[user], action, max(insertdate) as maxinsertdate
from userActions
group by
[user], action
) aggsubquery
on userActions.[user] = aggsubquery.[user]
and userActions.action = aggsubquery.action
and userActions.insertdate = aggsubquery.maxinsertdate
group by
userActions.[user],
userActions.Action,
userActions.insertDate
``` | Select many fields applying DISTINCT to only one particular field | [
"",
"sql",
"sql-server",
""
] |
Is there anyway to control where you can move a form?
So if i move a form, it can only be moved on the vertical axis and when i try to move it horizontally, nothing happens.
I dont want a buggy implementation like locationchanged or move event and poping it back inline. I no there is a way using something like a WndProc override but after searching for a while, i couldnt find anything. Please help | You would most likely want to override WndProc and handle the WM\_MOVING message. [According to MSDN](http://msdn.microsoft.com/en-us/library/ms632632(VS.85).aspx):
> The WM\_MOVING message is sent to a
> window that the user is moving. By
> processing this message, an
> application can monitor the position
> of the drag rectangle and, if needed,
> change its position.
This would be a way to do it, however, you would obviously need to tweek it for your needs:
```
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace VerticalMovingForm
{
public partial class Form1 : Form
{
private const int WM_MOVING = 0x0216;
private readonly int positionX;
private readonly int positionR;
public Form1()
{
Left = 400;
Width = 500;
positionX = Left;
positionR = Left + Width;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOVING)
{
var r = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
r.Left = positionX;
r.Right = positionR;
Marshal.StructureToPtr(r, m.LParam, false);
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
}
``` | For example:
```
using System.Runtime.InteropServices;
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x216) // WM_MOVING = 0x216
{
Rectangle rect =
(Rectangle) Marshal.PtrToStructure(m.LParam, typeof (Rectangle));
if (rect.Left < 100)
{
// compensates for right side drift
rect.Width = rect.Width + (100 - rect.Left);
// force left side to 100
rect.X = 100;
Marshal.StructureToPtr(rect, m.LParam, true);
}
}
base.WndProc(ref m);
}
```
The above code sets a minimum lefthand position of 100.
There is no need to recreate the RECT structure, like driis did, the .NET native Rectangle works fine. However, you have to set the location via the X property, since Left is a Get only property. | C# Form Control Move | [
"",
"c#",
"user-interface",
"move",
"wndproc",
""
] |
How can I get the owner and group IDs of a directory using Python under Linux? | Use [`os.stat()`](http://docs.python.org/library/os.html#os.stat) to get the uid and gid of the file. Then, use [`pwd.getpwuid()`](http://docs.python.org/library/pwd.html#pwd.getpwuid) and [`grp.getgrgid()`](http://docs.python.org/library/grp.html#grp.getgrgid) to get the user and group names respectively.
```
import grp
import pwd
import os
stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid
user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group
``` | Since Python 3.4.4, the `Path` class of [`pathlib`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.owner) module provides a nice syntax for this:
```
from pathlib import Path
whatever = Path("relative/or/absolute/path/to_whatever")
if whatever.exists():
print("Owner: %s" % whatever.owner())
print("Group: %s" % whatever.group())
``` | How to get the owner and group of a folder with Python on a Linux machine? | [
"",
"python",
"linux",
"directory",
"owner",
""
] |
Okay,
Maybe this is by design of c# or maybe I am going about this the wrong way.
Please look at the code I have below. I made it where you can copy and paste it into a console app and run it to see what I am talking about.
```
using System;
namespace ConsoleTest
{
class Program
{
static void Main()
{
var o1 = new oObject
{
Name = "Before Method"
};
var o1b = new oObjectBad
{
Name = "Before Method"
};
Console.WriteLine("Object Bad 1 Before: " + o1b.Name);
oObjectBad o2b = GetNewObjectBad(o1b);
Console.WriteLine("Object Bad 1 After: " + o1b.Name);
Console.WriteLine("Object Bad 2 After: " + o2b.Name);
Console.WriteLine(string.Empty);
Console.WriteLine("Object 1 Before: " + o1.Name);
oObject o2 = GetNewObject(o1);
Console.WriteLine("Object 1 After: " + o1.Name);
Console.WriteLine("Object 2 After: " + o2.Name);
Console.ReadLine();
}
public static oObject GetNewObject(oObject o)
{
oObject newObject = new oObject(o);
newObject.Name = "Changed in Method";
return newObject;
}
public static oObjectBad GetNewObjectBad(oObjectBad o)
{
o.Name = "Changed in Method";
return o;
}
}
class oObject
{
public oObject()
{
}
public oObject(oObject o)
{
Name = o.Name;
}
public string Name { get; set; }
}
class oObjectBad
{
public string Name { get; set; }
}
}
```
Now, here is what I don't understand.
When I pass in an object to the method, and update the objects property "Name". It then updates the original object which is outside of the method.
The way around this was to create the other object (as shown in code) to make a clone of the object and then update the clone and then return the clone.
So the question is this:
Is there an easier way to pass in an object and update the properties of that object so i can have something like this without it updating the original object.
```
using System;
namespace ConsoleTest
{
class Program
{
static void Main()
{
var o1 = new oObject
{
Name = "Before Method"
};
Console.WriteLine("Object 1 Before: " + o1.Name);
oObject o2 = GetNewObjectBad(o1);
Console.WriteLine("Object 1 After: " + o1.Name);
Console.WriteLine("Object 2 (New Object) After: " + o2.Name);
Console.ReadLine();
}
public static oObject GetNewObjectBad(oObject o)
{
o.Name = "Changed in Method";
return o;
}
}
class oObject
{
public string Name { get; set; }
}
}
```
If this is confusing let me know and I will see if I can explain better.
EDIT:
The reason why I am doing this is I need to clone an object in the database and the cloned object will need to have a couple of properties changed. I will then be using the ID from the original object and the new object for other data processing.
Thanks! | I would spend some time researching pass by reference vs. pass by value and then look at why you need to change the name in the local context but not in the original. I have the suspicion you might have some design flaws. I would revisit the problem and see if you can develop a solution with a different approach. | In .NET all objects are reference types unless they descend from ValueType. Typically you would not want to modify instance variables of an object directly anyway. You have much more control if you make instance variables private and then add methods to manipulate the private data.
<http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx> List of decedents of ValueType. | Updating Object inside/outside Method | [
"",
"c#",
"object",
""
] |
I have inherited an ASP.net codebase and I have very limited ASP.net skills. I am struggling to understand why something works and also why it only works in IE.
The following code appears in a page :-
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="map.aspx.cs" Inherits="Romtrac.auth_map" Culture="auto" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>
<% = Resources.Resource.map %>
</title>
</head>
<body>
<form id="adminlw_map_form" action="<%=geturl()%>" method="post" >
<% = Resources.Resource.loading %>...
<textarea name="xml" id="xml" runat="server" style="display:none" cols="1" rows="1"></textarea>
</form>
<script language="javascript" type="text/javascript" >
//submit main form immediately
document.getElementById('adminlw_map_form').submit();
</script>
</body>
</html>
```
This code runs fine in ASP.net. The form is automatically submitted and the page returned is rendered correctly within an Iframe. My question is;
1) Does the javascript within the body just get executed when it is encountered? Is this good practice or should it be executed in response to an event?
2) Why does this not work in other browsers? | 1. Yes
2. The javascript is being executed before the browser has fully rendered the page. In this case, the form has not been rendered and is not accessible via the DOM.
The execution needs to happen after the DOM is fully loaded by the browser and can be implemented by encapsulating the call within a function and calling that function via the onload event of the body or by using a javascript library like jquery to hook into the load event of the page. | 1) Yes, No. jQuery does it best with it's $(document).ready() function, but you should wait for the page to finish loading before running Javascript.
2) Do #1 and you won't need to worry about this. However I'll leave the floor open to someone with a better answer. | Does Javascript in the html body execute when encountered? | [
"",
"asp.net",
"javascript",
"html",
""
] |
I have a program I ported from C to Java. Both apps use quicksort to order some partitioned data (genomic coordinates).
The Java version runs fast, but I'd like to get it closer to the C version. I am using the Sun JDK v6u14.
Obviously I can't get parity with the C application, but I'd like to learn what I can do to eke out as much performance as reasonably possible (within the limits of the environment).
What sorts of things can I do to test performance of different parts of the application, memory usage, etc.? What would I do, specifically?
Also, what tricks can I implement (in general) to change the properties and organization of my classes and variables, reducing memory usage and improving speed?
**EDIT** : I am using Eclipse and would obviously prefer free options for any third-party tools. Thanks! | do not try to outsmart the jvm.
in particular:
* don't try to avoid object creation
for the sake of performance
* use immutable objects where
applicable.
* use the scope of your objects
correctly, so that the GC can do its
job.
* use primitives where you mean
primitives (e.g. non-nullable int
compared to nullable Integer)
* use the built-in algorithms and data structures
* when handing concurrency use java.util.concurrent package.
* correctness over performance. first get it right, then measure, then measure with a profiler then optimize. | Obviously, profile profile profile. For Eclipse there's TPTP. Here's an article on the [TPTP plugin for Eclipse](http://www.eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html). Netbeans has its own [profiler](http://www.netbeans.org/features/java/profiler.html). [jvisualvm](https://visualvm.dev.java.net/) is nice as a standalone tool. (The entire dev.java.net server seems to be down at the moment, but it is very much an active project.)
The first thing to do is use the library sorting routine, [Collections.sort](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)); this will require your data objects to be [Comparable](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html). This might be fast enough and will definitely provide a good baseline.
General tips:
* Avoid locks you don't need (your JVM may have already optimized these away)
* Use [`StringBuilder`](http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html) (not [`StringBuffer`](http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html) because of that lock thing I just mentioned) instead of concatenating `String` objects
* Make anything you can `final`; if possible, make your classes completely immutable
* If you aren't changing the value of a variable in a loop, try hoisting it out and see if it makes a difference (the JVM may have already done this for you)
* Try to work on an [`ArrayList`](http://java.sun.com/javase/6/docs/api/java/util/class-use/ArrayList.html) (or even an array) so the memory you're accessing is contiguous instead of potentially fragmented the way it might be with a [`LinkedList`](http://java.sun.com/javase/6/docs/api/java/util/class-use/LinkedList.html)
* Quicksort can be parallelized; consider doing that (see [quicksort parallelization](http://en.wikipedia.org/wiki/Quicksort#Parallelizations))
* Reduce the visibility and live time of your data as much as possible (but don't contort your algorithm to do it unless profiling shows it is a big win) | Java performance tips | [
"",
"java",
"profiling",
"performance",
""
] |
I am setting up a web service and i'm unsure about the most efficient design..
The web service is going to be called to populate a remote website with a list of people and their associated information. So, in the database there will be a "Person" table, then other tables for nicknames, addresses, phone numbers, etc. There may be 50 "People" returned for the page.
I would think I'd want to keep the # of web service calls to a minimum.. So is the best way to just have one call, GetPeople(), which returns all People and their information in one xml? Or would I want to maybe have GetPeople() return just a list of People, then have a GetPeopleInfo() call for each person?
Thanks in advance | Will you have an opportinuty to talk a bit more with the folks using the web service? The best answer would be depend on a number of factors, including how they are using it.
The simplest soution would be to create one web service method GetPeople() that executes a query joining the Person table with the rest of the tables and returnes all of the data in one flat table. If the client is just going to display all this information in a single list/table this would be the best option all around.
If, on the other hand, the client is going to generate a list of people and then have a click through to get more detailed information on a separate detail page, they might want a GetPeople() method that just returns the names/ids and a GetPeopleInfo() that pulls back the detail. If this isn't going to cause a performance problem on your system, this should be relatively straight forward.
I would probably build both - create a GetPeople() method that brings back all the data {as long as there isn't so much data that transportation becomes and issue} and a GetPersonInfo() method that allows they to pull back details on a specific person. This offers your client the greatest flexibility with not too much additional effort on your part. | You need to think about how your service is going to be used.
Will the users require all of that information most/all of the time? If so then it's appropriate for GetAllPeoplesDetails() to return everything
If they're going to only rarely need all the info then GetPeople() should return just a list of People.
If you're not sure then you could provide both GetAllPeoplesDetails() and GetPeople() and let the end user make that decision | proper design of web service and associated queries | [
"",
"c#",
".net",
"wcf",
"service",
""
] |
I've got a LINQ 2 SQL generated class I'd like to expose through a webservice.
There are some internal properties I don't want to be available.
Normally I'd throw [XmlIgnore] in there but because the properties are in the generated half I can't do that.
I've been looking at using MetadataType following [this post](https://stackoverflow.com/questions/393687/how-can-i-add-my-attributes-to-code-generated-linq2sql-classes-properties/393690) which looks like it should allow me to define the property attributes in another class.
My code looks something like this:
```
[MetadataType(typeof(ProspectMetaData))]
public partial class Prospect : ApplicationBaseObject
{
}
public class ProspectMetaData
{
[XmlIgnore]
public object CreatedDateTime { get; set; }
[XmlIgnore]
public object AmendedDateTime { get; set; }
[XmlIgnore]
public object Timestamp { get; set; }
}
```
I'm referencing this through an ASP.NET Web Service from a Silverlight Project.
The issue is that the [XmlIgnore] attributes are being ignored, those properties are being sent through.
Does anyone have any insight into what might be going wrong here? and what might be the best way to do this? | AFAIK, `MetadataTypeAttribute` is not supported by `XmlSerializer` (although it would be nice - I've simply never checked). And as you say, you can't add member attributes in a partial class.
One option may be to make the generated properties non-public (`private`, `protected` or `internal`) - and name it something like `TimestampStorage` (etc) - then re-expose them (in the partial class) on the public API:
```
[XmlIgnore]
public object Timestamp {
get {return TimestampStorage; }
set {TimestampStorage = value; }
}
// and other properties
```
(since `XmlSerializer` only looks at the public API). The biggest problem here is that LINQ-to-SQL queries (`Where` etc) will only work against the generated columns (`TimestampStorage` etc). I've used this approach before with the member as `internal`, allowing my DAL class to use the `internal` property... but it is a bit of a fudge. | You can do this by passing your own XmlAttributeOverrides to the XmlSerializer, in the XmlAttributeOverrides you can change the XmlIgnore to true for the fields/properties you wish without touching the DBML generated code and it works like a charm, use the same overrides to deserialize as well...
[Refer this link](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx) for more information
```
// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs.XmlIgnore = true;
/* Setting XmlIgnore to true overrides the XmlIgnoreAttribute
applied to the following fields. Thus it will be serialized.*/
xOver.Add(typeof(Prospect), "CreatedDateTime", attrs);
xOver.Add(typeof(Prospect), "AmendedDateTime", attrs);
xOver.Add(typeof(Prospect), "Timestamp", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(Prospect), xOver);
TextWriter writer = new StreamWriter(outputFilePath);
xSer.Serialize(writer, object);
``` | Using XmlIgnore on generated partial classes | [
"",
"c#",
"silverlight",
"web-services",
"attributes",
"metadata",
""
] |
I have been assigned to add a forum into an in-house CMS we have been using for some time. The system has its own login/user system and an established user database. Ideally I'd be looking for the easiest forum software to convert to use with our system, but if necassary can rewrite and migrate the user databases to use the forums system.
Does anyone have any experience rolling forum software into their own systems, or recommend forum software that has a clean and concise code-base that is easy to work with? Any advice is appreciated at this point.
I have been browsing through the [forums section](http://php.opensourcecms.com/scripts/show.php?catid=5&cat=Forums) of [opensourcecms.com](http://opensourcecms.com) but the details available are limited. Also, this will be running on PHP5, so one that uses some of PHP5's features would be ideal. | I would recommend [punBB](http://punbb.informer.com/). It's super simple, with a focus on security. The tag line is 'Because less really is more'. | [phpBB](http://www.phpbb.com/) is amazing, its easy to integrate into nearly anything. | Easiest PHP forum to configure to work inside an existing CMS? | [
"",
"php",
"authentication",
"forum",
""
] |
I have a need for a "container" that acts like the following. It has 2 subcontainers, called A and B, and I need to be able to iterate over just A, just B, and A and B combined. I don't want to use extra space for redundant data, so I thought of making my own iterator to iterate over A and B combined. What is the easiest way to make your own iterator? Or, what is another way to do this?
**EDIT** Ultimately, I don't think it was good design. I have redesigned the entire class heirarchy. +1 for refactoring. However, I did solve this problem sufficiently. Here's an abbreviated version of what I did, for reference; it uses boost::filter\_iterator. Let T be the type in the container.
```
enum Flag
{
A_flag,
B_flag
};
class T_proxy
{
public:
T_proxy(const T& t, Flag f) : t_(t), flag_(f) {}
operator T() const {return t_;}
Flag flag() const {return flag_;}
class Compare
{
public:
Compare(Flag f) : matchFlag_(f) {}
operator() (const T_proxy& tp) {return tp.flag() == matchFlag_;}
private:
Flag matchFlag_;
};
private:
T t_;
Flag flag_;
};
class AB_list
{
public:
typedef T_proxy::Compare Compare;
typedef vector<T_proxy>::iterator iterator;
typedef boost::filter_iterator<Compare, iterator> sub_iterator;
void insert(const T& val, Flag f) {data_.insert(T_proxy(val, f));}
// other methods...
// whole sequence
iterator begin() {return data_.begin();}
iterator end() {return data_.end();}
// just A
sub_iterator begin_A() {return sub_iterator(Compare(A_flag), begin(), end());
sub_iterator end_A() {return sub_iterator(Compare(A_flag), end(), end());
// just B is basically the same
private:
vector<T_proxy> data_;
};
// usage
AB_list mylist;
mylist.insert(T(), A_flag);
for (AB_list::sub_iterator it = mylist.begin_A(); it != mylist.end_A(); ++it)
{
T temp = *it; // T_proxy is convertible to T
cout << temp;
}
``` | I will repost my answer to a similar question. I think this will do what you want.
Use a library like [Boost.MultiIndex](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/index.html) to do what you want. It scales well and there is a lot less boiler plate code if you want to add new indexes. It is also usually [more space and time efficient](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/performance.html)
```
typedef multi_index_container<
Container,
indexed_by<
sequenced<>, //gives you a list like interface
ordered_unique<Container, std::string, &Container::a_value>, //gives you a lookup by name like map
ordered_unique<Container, std::string, &Container::b_value> //gives you a lookup by name like map
>
> container;
```
If you are iterating over one index, you can switch to another index by using the iterator projection concept in the library. | Have one container which stores the value you are interested in together with a flag indicating whether it is in A or B. | Make a c++ iterator that traverses 2 containers | [
"",
"c++",
"iterator",
""
] |
I have user preference (colour, locale settings) on example.com that I would like to migrate to example2.com
I'm wondering if I can use AJAX or a hidden iFrame to pass the cookie information from example.com to example2.com which will then set another cookie with the same information on example2.com.
I know I could do this easily through the URL string and a redirect, but I would like to achieve this in the background if possible -- no redirects -- and needs to work on major browsers (IE6+, FF1.5+, Safari, Opera)
Point is this cookie information isn't secure so there's no risk there. | Setup a path on example.com that generates a javascript file containing the cookies passed in. Lets say it is example.com/get\_cookie.js
Then you can do an ajax call from example2.com to example.com/get\_cookie.js to get those cookies, and save them under example2.com.
Since it is cross-domain, you can't use XHR (XmlHttpRequest), instead you'll have append get\_cookie.js as a javascript node, and that javascript file will have to call a callback to pass you the data.
So get\_cookie.js would look somthing like:
```
return_data( 'here is my example.com cookie info' );
``` | It depends on the browser setup for starters, if the browser is configured to reject 3rd party cookies you're out of luck.
Assuming that you control example.com, and the cookie is not an HTTP only cookie you could add a script. The script would write out an img tag pointing to a script on example2.com, with document.cookies as the parameter. Within the script write out a 1x1 transparent gif and attach the cookie from example to the response, having parsed the parameter string to pull out the cookie name/value pairs. | duplicating cookies to another domain | [
"",
"javascript",
"iframe",
"cookies",
""
] |
I have a custom collection that I am adding a ValidateItem event to. This ValidateItem event will be called whenever an item is added to or updated in the custom collection.
I want to allow derived classes to be able to subscribe to the event and determine their own logic for whether or not an item is "valid" and potentially prohibit it being added to the collection if it is "invalid".
But I am trying to figure out how to let the caller to the event know what is going on and how to pass the information about what is going on back.
My custom eventargs inherit from CancelEventArgs so I have the ability to pass the Cancel bit back to the caller using that. But I have never seen any cases where error information (error codes, messages, etc) gets passed back in this manner, so I'm wondering if this might not be the best approach.
Should I just add any error data that I wish to pass back to my Custom eventargs class, are there good reasons for or against this? or are there other, better ways to accomplish this?
Here is my eventargs class:
```
public delegate void ItemValidationEventHandler(object sender, ItemValidationEventArgs e);
public class ItemValidationEventArgs : CancelEventArgs
{
public ItemValidationEventArgs(object item, ObjectAction state, EventArgs e)
{
Item = item;
State = state;
EventArgs = e;
}
public ItemValidationEventArgs(object item, ObjectAction state) : this(item, state, new EventArgs())
{
}
public ItemValidationEventArgs() : this(null, ObjectAction.None, new EventArgs())
{
}
// is there a better way to pass this info?
public string ErrorMessage {get; set;}
public int ErrorNumber {get;set;}
public object Item { get; private set; }
public ObjectAction State { get; private set; }
public EventArgs EventArgs { get; private set; }
}
```
UPDATE: I suppose another other option would be to use something like this:
```
virtual bool Validate(object item, ObjectAction action, out string errorMessage)
```
method in the derived classes. Though I tend to prefer avoiding out parameters...
If anyone has any ideas on the pros and cons of each approach I'd love to hear em!
Thanks,
Max | Using events for this is probably not the best design approach.
Since it is an inheriting class that would be overriding this behavior, the method should be marked as protected and virtual:
```
protected virtual bool Validate(object item);
```
I too do not like using `out` on parameters, so following your initial instincts to use `EventArgs`, you should probably create a class to encapsulate the results of your validation.
Example:
```
class ValidationResult
{
public string ResultMessage{get;set;}
public bool IsValid {get;set;}
}
```
Your method would then be:
```
protected virtual ValidationResult Validate(object item)
{
ValidationResult result = new ValidationResult();
// validate and set results values accordingly
return result;
}
```
The pros and cons of using this over events are that events are intended to be used when you want to publish an action or information to multiple subscribers. The subscribers are classes that you know nothing about. You do not care who they are or what they do. They should never really pass information back to the notifying class either. They should just process the event information given to them.
In your instance, your inherited class is your only subscriber. On top of that you want to be able pass useful information back to the parent class. Inheritance fits this desired behavior much better, and also allows you to easily implement different types of validation class. With events, you would have to keep typing code to attach event handlers over and over again (very ugly IMO). | I don't think what you are describing really fits the observer, observable pattern that you would normally see with events.
Since these are derived classes I would probably look to virtualizing the validation method of the objects and having the children provide a specific validation routine. | C# Custom EventArgs Question | [
"",
"c#",
"asp.net",
"events",
"eventargs",
""
] |
Lets say I inherit a class, that has several public properties and/or methods, however I do not want them to be public properties/methods of my class - in other words, I want to make those properties protected properties of my class.
Can this be achieved?
I hope I was clear enough, if not please let me know, will try to explain myself better.
**EDIT:**
Right, thank you all for answers however I don't think I was clear enough. What I am trying to accomplish is this:
I wrote a windows control that extends ListView control. ListView has a public collection Items, that can be modified. That's all fine, however I wrote new methods for adding items to listview because of the extra data I need.
It all works great so far, however the Items collection can still be modified by anything, which is a problem, because if an item is added by direct manipulation of Items collection not all data I need is gathered, thus causing an error.
Since we hope to reuse this control several times in different projects, we are afraid that sooner or later, the default way of adding items to Items collection will be used (just a matter of time really). We are just looking for a way to prevent that from happening, like throwing an exception when Items collection gets bigger, but the way it was intended.
I hope this all makes sense now. | Never say never. This is probably not the best idea but it seems to work for me. This hides items by re-implementing it in the subclass and then hiding it using attributes. I added in a "CustomExposedItems" property so you can see that the existing items are still accessible in the underlying ListView.
```
public partial class CustomListView : ListView
{
public CustomListView()
{
InitializeComponent();
}
public System.Windows.Forms.ListView.ListViewItemCollection CustomExposedItems
{
get
{
return base.Items;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Obsolete("Use the new custom way of adding items xyz")]
public new System.Windows.Forms.ListView.ListViewItemCollection Items
{
get { throw new NotSupportedException(); }
}
}
``` | Inheritance is all about saying "You can use this derived class in the same way as you can use the base class, and it provides specialized behaviour."
If you *can't* use the derived class in the same way as the base class, then you shouldn't be using inheritance: you're breaking [Liskov's Substitutability Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). In such a case, use composition instead of inheritance. (Personally I don't use class-to-class inheritance that much anyway, far preferring composition - I find there are relatively few cases where the specialization aspect really works without issues. When it *does* work it's great though!) | Limiting access to inherited properties C# | [
"",
"c#",
"inheritance",
""
] |
I use the term "double link" because I don't know what the actual phrase is, or if there is one, but assuming you have two headers, head1.h and head2.h, with these contents:
In head1.h:
```
#include"head2.h"
//do stuff
```
In head2.h:
```
#include"head1.h"
//do stuff
```
I visualise it as two mirrors placed opposite each other, as it's not really an infinite loop, but some other form of getting infinity into a finite computer (but I digress). The point is, is there any situation where it would be useful or necessary to use this concept, or a variation of this concept? (ie: I suppose goto could be used as an improv break). | That's a "cyclic include" and no, it's not a desirable thing to do. your goto wouldn't help, because gotos are part of the program execution, while the #includes are interpreted during the preprocessing phase of compiling.
The usual thing is to make your header files have a structure like
```
#ifndef FOO_H
#define FOO_H
... rest of the include file here
#endif
```
so they don't attempt to define the same stuff twice.
Should you try it, here's what happens:
> bash $ gcc crecursive.c In file
> included from bh.h:1,
>
> > ```
> > from ah.h:1,
> > from bh.h:1,
> > from ah.h:1,
> > ```
> >
> > *... many lines omitted*
> >
> > ```
> > from ah.h:1,
> > from crecursive.c:2: ah.h:1:16: error: #include nested too deeply
> > ```
> >
> > bash $ | Usually, headers have preprocessor statements to prevent precisely this kind of thing from causing an infinite recursion:
```
#ifndef MY_FILE_H
#define MY_FILE_H
//do stuff
#endif
```
Even with that protection, mutual includes are usually a bad idea. | Is there any situation in which it would be useful or necessary to "double link" header files? (C++) | [
"",
"c++",
"include",
"header",
"infinity",
""
] |
I wanted to create a list of options for testing purposes. At first, I did this:
```
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
```
Then, I refactored the code as follows:
```
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
```
Is there a better way to do this? | Actually, probably the "best" way to initialize the `ArrayList` is the method you wrote, as it does not need to create a new `List` in any way:
```
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
```
The catch is that there is quite a bit of typing required to refer to that `list` instance.
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):
```
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
```
However, I'm not too fond of that method because what you end up with is a subclass of `ArrayList` which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
What would have been nice was if the [Collection Literals proposal](http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html) for [Project Coin](http://openjdk.java.net/projects/coin) was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):
```
List<String> list = ["A", "B", "C"];
```
Unfortunately it won't help you here, as it will initialize an immutable `List` rather than an `ArrayList`, and furthermore, it's not available yet, if it ever will be. | It would be simpler if you were to just declare it as a `List` - does it have to be an ArrayList?
```
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
```
Or if you have only one element:
```
List<String> places = Collections.singletonList("Buenos Aires");
```
This would mean that `places` is **immutable** (trying to change it will cause an `UnsupportedOperationException` exception to be thrown).
To make a mutable list that is a concrete `ArrayList` you can create an `ArrayList` from the immutable list:
```
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
```
And import the correct package:
```
import java.util.Arrays;
``` | Initialization of an ArrayList in one line | [
"",
"java",
"collections",
"arraylist",
"initialization",
""
] |
I am making a simple program in visual c# 2005 that looks up a stock symbol on Yahoo! Finance, downloads the historical data, and then plots the price history for the specified ticker symbol.
I know the exact URL that I need to acquire the data, and if the user inputs an existing ticker symbol (or at least one with data on Yahoo! Finance) it works perfectly fine. However, I have a run-time error if the user makes up a ticker symbol, as the program tries to pull data from a non-existent web page.
I am using the WebClient class, and using the DownloadString function. I looked through all the other member functions of the WebClient class, but didn't see anything I could use to test a URL.
How can I do this? | You could issue a ["HEAD"](https://www.rfc-editor.org/rfc/rfc9110.html#name-head) request rather than a "GET"?
So to test a URL without the cost of downloading the content:
```
// using MyClient from linked post
using(var client = new MyClient()) {
client.HeadOnly = true;
// fine, no content downloaded
string s1 = client.DownloadString("http://google.com");
// throws 404
string s2 = client.DownloadString("http://google.com/silly");
}
```
You would `try`/`catch` around the `DownloadString` to check for errors; no error? It exists...
---
With C# 2.0 (VS2005):
```
private bool headOnly;
public bool HeadOnly {
get {return headOnly;}
set {headOnly = value;}
}
```
and
```
using(WebClient client = new MyClient())
{
// code as before
}
``` | Here is another implementation of this solution:
```
using System.Net;
///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
response.Close();
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
```
From: <http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/> | C# How can I check if a URL exists/is valid? | [
"",
"c#",
".net",
"url-validation",
""
] |
I often run into a situation where I want to subscribe to an event, but I want to use a lambda to do so:
```
public class Observable
{
public event EventHandler SomethingHappened;
public void DoSomething()
{
// Do Something...
OnSomethingHappened();
}
}
// Somewhere else, I hook the event
observable.SomethingHappened += (sender, args) => Console.WriteLine("Something Happened");
```
The problem I run into is that I don't know how to unhook the event. Since the lambda creates an anonymous delegate under the hood, I have nothing to call `-=` on.
Now, I could just create a method:
```
private void SomethingHappened(object sender, EventArgs args)
{
Console.WriteLine("Something Happened");
}
```
And then I can hook/unhook all I want:
```
observable.SomethingHappened += SomethingHappened;
observable.SomethingHappened -= SomethingHappened;
```
But I'd really, really, really like to use my lambda instead. In a more complicated example, lambdas come in really handy here.
I am pretty sure that I am out of luck... but I was wondering if anyone out there has figured out a way to do this? | Unforutantely there is not a great way to do this. You are really stuck with one of two options
* Use a method as you described
* Assign the lambda to a variable and use the variable to add / remove the event | This question was already asked
* [How to unsubscribe from an event which uses a lambda expression?](https://stackoverflow.com/questions/805829/how-to-unsubscribe-from-an-event-which-uses-a-lambda-expression)
* [Unsubscribe anonymous method in C#](https://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c)
The answer is: put your lambda in a variable.
```
EventHandler handler = (sender, args) => Console.WriteLine("Something Happened");
observable.SomethingHappened += handler;
observable.SomethingHappened -= handler;
``` | UnHooking Events with Lambdas in C# | [
"",
"c#",
"events",
"lambda",
""
] |
I usually see this when looking at Win32 gui code. My assumption is that it is a standard bitwise or, but I also occasionaly see it in C#, and it seems like there would be a better (well higher level) way to do the same thing there. Anyway, here's an example:
```
MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
```
Thanks,
Seamus | The | is a bitwise OR. MB\_OK and MB\_ICONEXCLAMATION are defined constants which are a power of 2 (such as 32 or 128), so that the bitwise OR can combine them (128 | 32 would be 160, which has two bits set). This is normal when the bits are used as flags. | Its for bitmasking. Lets use this incredibly trivally example. You have a binary value for colors, with the following values.
100 = BLUE
010 = RED
001 = GREEN
When you say SomeFunction ( BLUE | RED | GREEN ); you are infact passing the value 111, which can then be decoded to mean BLUE and RED and GREEN.
Google Bitwise operators for more details. | What does the | operator mean in a function call? [C++] | [
"",
"c++",
"winapi",
""
] |
I have to use a macro multiple times inside a function and the macro that needs to be used depends on a number I pass into the function.
e.g.
```
function(int number) {
switch(number) {
case 0: doStuff(MACRO0); break;
case 1: doStuff(MACRO1); break;
}
}
```
The problem is: I have a lot stuff to do per switch statement with the same macro.
Is there are more elegant solution then having all that stuff in the switch statement? Like passing the macro itself to the function? I have read about eval() like methods in C++ but they just don't feel right to me. Another way could be do determine into what the macro expands but I haven't found any info on this.
Oh, it's openGL actually. | I would use a function object
```
struct Method1 {
void operator()() { ... }
};
template<typename Method>
void function(Method m) {
...
m();
...
}
int main() {
function(Method1());
}
``` | This very much depends on what `MACRO1` expands to. If it's a constant you can just call the function outside of the `switch` or do multiple fall-through cases. If it depends on the local context then you will have to evaluate it every time. | Macro use depending on integer | [
"",
"c++",
"opengl",
"macros",
""
] |
I would like to be able to **programmatically change the outputted path to a Drupal node without using the PathAuto module**. We currently process a large volume of content (thousands of articles per day) that get added on the back-end. Rather than use PathAuto to generate path aliases, I would like to have Drupal output the default link but append a partial title for better SEO.
**An example of this would be:**
/node/123
**would be changed to**
/node/123/This-is-the-article-title (this path currently will work for the existing node)
I understand how to do this on a theme-basis, by modifying the theme/view templates, but I would like to do it so that anytime the link to the node is displayed anywhere, it adds the title plug.
In addition, I would like to limit it to a certain content type (e.g., 'article').
I am using **Drupal 5.x** and I would **prefer not to use PathAuto** (I don't want to store hundreds of thousands of path aliases if not necessary)
**I am looking for a solution that does not use PathAuto** | Drupal has an internal mechanism for mapping from "/node/1234/" to "/blogs/look-at-what-my-cat-just-did". It's part of the core system, and used almost everywhere, on every request, without you even having to ask. It's fast enough you'll almost never notice it happening - there's plenty of other things in drupal that are -far- slower.
If you're concerned about how URLs are being displayed on the front-end - you should be using the url() function (and filters that do the same with node content) to handle look-ups going the other way.
Where Pathauto comes in is that, when you create or edit content, it will generate a number of entries in Drupal's url\_alias table (based on whatever pathauto rules you've created). This is a one-time cost. Unless you're generating content at an astronomical rate - there is a negligible cost associated with doing this.
You're already paying the cost of looking up URL aliases by simply using Drupal. Without hacking core, you can't really avoid it. Storing "hundreds of thousands of path aliases" in the database isn't that big of a deal - if you break that down into the actual storage requirements, you're only looking at a handful of megabytes. Since the table's well indexed, look-ups will be virtually instantaneous. This is core functionality & happens regardless of Pathauto even being on your system.
Unless you have some very odd requirements for the types of URLs you want to map your nodes to, anything you do will simply be recreating a subset of Pathauto's existing functionality (and likely introducing a bunch of new bugs). | you can set your custom path alias for each node type without using path auto module:
1. install rules module if you already didn't.
2. create a rule with "before saving content of type 'your type'" event
3. add a php action and then create your custom path and do the following:
4. $node->path['alias'] = your custom path alias
5. hit save and it's done
if you do not want to use rules module, you can use hook\_node\_presave instead in your custom module | How do I Programmatically Output Custom Paths for Drupal Node Links (w/o PathAuto)? | [
"",
"php",
"drupal",
""
] |
I'm working with a Maven (jar) Project in Netbeans (Windows), which creates Checkstyle reports with the Maven Checkstyle plugin.
No matter what I do, I always get the message: `File does not end with a newline` for Java class files.
What can I do/configure in either Netbeans or Checkstyle to get rid of the message ?
Versions of used software:
* WinXP SP3
* Netbeans 6.7 RC1 (happens with 6.5 too)
* Maven 2.0.9
* Maven Checkstyle Plugin 2.2
* Java 1.6 (Update 14) | Put a newline at the end of the file
or
configure CheckStyle not to care.
```
<module name="Checker">
<!-- stuff deleted -->
<module name="NewlineAtEndOfFile">
<property name="severity" value="ignore" />
</module>
```
---
You also have to tell the Maven Checkstyle plugin to use your checkstyle config file.
```
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>${basedir}/yourCheckstyle.xml</configLocation>
</configuration>
</plugin>
``` | In my case that was a problem with improper configuration of that checker. By default it uses system default convention of line endings. I was working on windows and the project was using unix-style line endings. I don't think ignoring the warning is the best strategy, so what I've done is:
```
<module name="Checker">
<module name="NewlineAtEndOfFile">
<property name="lineSeparator" value="lf" />
</module>
</module>
``` | How to get rid of Checkstyle message 'File does not end with a newline.' | [
"",
"java",
"windows",
"maven-2",
"netbeans",
"checkstyle",
""
] |
I have this right now:
```
$(document).click(function(e) { alert('clicked'); });
```
In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.
Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.
Is there a way to detect *only* left clicks besides looking at e.button, which is browser-dependent?
Thanks | Try
```
$(document).click(function(e) {
// Check for left button
if (e.button == 0) {
alert('clicked');
}
});
```
However, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)
Further reading here: [jQuery Gotcha](http://www.barneyb.com/barneyblog/2009/04/09/jquery-live-click-gotcha/)
**EDIT**: missed the bit where you asked not to use `e.button`. Sorry!
However, the example [here](http://barneyb.com/r/jquery_live_button.cfm) returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? The other answer is that older versions of IE return a different value, which would be a pain. Unfortunately I only have IE 7/8 here to test against. | You could simply register for a "contextmenu" event like this:
```
$(document).bind("contextmenu",function(e){
return false;
});
```
Taken from: <http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks> | How to detect left click anywhere on the document using jQuery? | [
"",
"javascript",
"jquery",
""
] |
I have some code i'm revewing, which is used to convert some text into an `MD5 Hash`. Works great. It's used to create an `MD5Hhash` for a *gravatar avatar*. Here it is :-
```
static MD5CryptoServiceProvider md5CryptoServiceProvider = null;
public static string ToMD5Hash(this string value)
{
//creating only when needed
if (md5CryptoServiceProvider == null)
{
md5CryptoServiceProvider = new MD5CryptoServiceProvider();
}
byte[] newdata = Encoding.Default.GetBytes(value);
byte[] encrypted = md5CryptoServiceProvider.ComputeHash(newdata);
return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
}
```
Notice how we create a `MD5CryptoServiceProvider` the first time this method is called? (lets not worry about race-conditions here, for simplicity).
I was wondering, is it more computationally expensive if i change the lines that are used to create the provider, to this...
```
using(var md5CryptoServiceProvider = new MD5CryptoServiceProvider())
{
... snip snip snip ....
}
```
Now, how is this method used/consumed? Well, imagine it's the home page of StackOverflow -> for each post, generate an md5 hash of the user, so we can generate their gravatar url. So the view could call this method a few dozen times.
Without trying to waste too much time stressing over [premature optimzation](http://www.codinghorror.com/blog/archives/000061.html), etc ... which would be better? | I'd be more interested in the thread-safefy... MSDN doesn't (unless I missed it) say that `MD5CryptoServiceProvider` is thread-safe, so IMO the best option is to have one per call...
It doesn't matter how quickly you can get the wrong answer ;-p
What you probably *don't* want to do (to fix the thread-safety issue) is have a static instance and `lock` around it... that'll serialize all your crypto code, when it could run in parallel on different requests. | Test it and time it. The first is more performant, but it is probably not significant.
```
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
Stopwatch timer=new Stopwatch();
int iterations = 100000;
timer.Start();
for (int i = 0; i < iterations; i++)
{
string s = "test" + i;
string t=s.ToMd5Hash0();
}
timer.Stop();
Console.WriteLine(timer.ElapsedTicks);
timer.Reset();
timer.Start();
for (int i = 0; i < iterations; i++)
{
string s = "test" + i;
string t = s.ToMd5Hash1();
}
timer.Stop();
Console.WriteLine(timer.ElapsedTicks);
Console.ReadKey();
}
}
public static class Md5Factory
{
private static MD5CryptoServiceProvider md5CryptoServiceProvider;
public static string ToMd5Hash0(this string value)
{
if (md5CryptoServiceProvider == null)
{
md5CryptoServiceProvider = new MD5CryptoServiceProvider();
}
byte[] newData = Encoding.Default.GetBytes(value);
byte[] encrypted = md5CryptoServiceProvider.ComputeHash(newData);
return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
}
public static string ToMd5Hash1(this string value)
{
using (var provider = new MD5CryptoServiceProvider())
{
byte[] newData = Encoding.Default.GetBytes(value);
byte[] encrypted = provider.ComputeHash(newData);
return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
}
}
}
}
``` | Which piece of code is more performant? | [
"",
"c#",
".net",
"optimization",
"premature-optimization",
""
] |
Here is the SELECT statement:
```
SELECT ROUND(ISNULL(SUM(Price),0),2) As TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
```
Any ideas of why it's not rounding to two decimal places? | instead of `ROUND(ISNULL(SUM(Price),0),2)` you could try `CAST(ISNULL(SUM(PRICE),0) AS DECIMAL (4,2))` | What datatype is Price?
[ROUND in BOL](http://msdn.microsoft.com/en-us/library/ms175003.aspx)
```
SELECT ROUND(123.4545, 2); -- = 123.4500
GO
SELECT ROUND(123.45, -2); -- = 100,00
GO
```
The underlying datatype stays the same: you merely round but leave trailing zeros.
For 2 decimal place *output*, you'd need to CAST to decimal(x, 2) | SQL Round function not working, any ideas? | [
"",
"sql",
"sql-server",
"rounding",
""
] |
I have a Javascript bookmarklet that, when clicked on, redirects the user to a new webpage and supplies the URL of the old webpage as a parameter in the query string.
I'm running into a problem when the original webpage has a double hyphen in the URL (ex. `page--1--of--3.html`). Stupid, I know - I can't control the original page The javascript `escape` function I'm using does not escape the hyphen, and IIS 6 gives a file not found error if asked to serve `resource.aspx?original=page--1--of--3.html`
Is there an alternative javascript escape function I can use? What is the best way to solve this problem? Does anybody know why IIS chokes on `resource.aspx?original=page--1` and not `page-1`? | Can you expand the escape function with some custom logic to encode the hypen's manually?
```
resource.aspx?original=page%2d%2d1%2d%2dof%2d%2d3.html
```
Something like this:
```
function customEscape(url) {
url = escape(url);
url = url.replace(/-/g, '%2d');
return url;
}
location.href = customEscape("resource.axd?original=test--page.html");
```
**Update, for a bookmarklet:**
```
<a href="javascript:location.href=escape('resource.axd?original=test--page.html').replace(/-/g, '%2d')">Link</a>
``` | "escape" and "unescape" are deprecated precisely because it doesn't encode all the relevant characters. **DO NOT USE ESCAPE OR UNESCAPE**. use "encodeURIComponent" and "decodeURIComponent" instead. Supported in all but the oldest most decrepit browsers. It's really a huge shame this knowledge isn't much more common.
(see also encodeURI and decodeURI)
edit: err just tested, but this doesn't really cover the double hyphens still. Sorry. | Escaping double hyphens in Javascript? | [
"",
"javascript",
"iis",
"url",
""
] |
In particular, I need a way to represent a curve/spline that passes through a set of known 3D points, and a way of finding other points on the curve/spline, by subdivision/interpolation.
For example, if I have a set of points P0 to PN, I want to find 100 points between P0 and P1 that are on a spline that passes through P0 and P1.
I see that Java3D's KBRotPosScaleSplinePathInterpolator performs such a calculation, but it is tied to that API's scenegraph model and I do not see how to return the values I need. | There's no built-in library that I'm aware of. [Source](http://www.mail-archive.com/java3d-interest@java.sun.com/msg13136.html) | You're looking for something like a [Catmull Rom spline](https://stackoverflow.com/questions/107598/point-sequence-interpolation/134203#134203). The reality is that the math just isn't [all that hard to deal with](http://www.mvps.org/directx/articles/catmull/) (some vector-matrix multiplications). My recommendation is that you just implement the spline that you really need in code.
[Quoting from that article](http://www.mvps.org/directx/articles/catmull/):
> The points that define a spline are
> known as "Control Points". One of the
> features of the Catmull-Rom spline is
> that the specified curve will pass
> through all of the control points -
> this is not true of all types of
> splines.
>
> 
>
> To calculate a point on the curve, two
> points on either side of the desired
> point are required, as shown on the
> left. The point is specified by a
> value t that signifies the portion of
> the distance between the two nearest
> control points.
You should be aware, though, that the Catmull-Rom spline can lead to little loops at the control points if they are too close together when they need to take a tight turn.
Looking at the image above, imagine that p1 and p3 were right next to each other, below p2 (basically compressing the right hand side of the picture). It's likely that a Catmull-Rom spline would come down from p0, pass through p1 as it does now, go up the right side of p2 and pass through it from right to left, coming down the left hand side and passing left to right through p3.
This is a consequence of the construction of the spline.
*It's sort of like working with fairly stiff flexible pipe (like I have under my sink). In order to get a longish piece to connect to points that are close together, I have to add a loop.* | Is there a Java library with 3D spline functions? | [
"",
"java",
"math",
"3d",
""
] |
I need a wizard which second page content depends on the first page's selection. The first page asks the user the "kind" of filter he wants to create and the second one asks the user to create one filter instance of the selected "kind".
JFace's wizards pages contents (createControl(...) method) are all created when the wizard is open and not when a given page is displayed (this allow JFace to know the wizard size I guess ??).
Because of this, I have to create my second page content BEFORE the wizard is opened BUT I can't since the second page's content depends on the first page selection.
For now the cleaner solution I found consists in creating all (seconds) pages before the wizard is open (with their content) and override the getNextPage() method in the first page's implementation.
The main drawback of that solution is that it can be be expensive when there are many second pages to create.
What do you think about that solution ? How do you manage your wizard's pages ? Is there any cleaner solution I missed ? | The approach is right if you are several other pages which are
* completely different one with another
* depends on the previous choices made in a previous page
Then you can [add the next page dynamically](http://dev.eclipse.org/newslists/news.eclipse.platform/msg59794.html) (also as [described here](http://dev.eclipse.org/mhonarc/newsLists/news.eclipse.platform.rcp/msg29949.html))
But if you have just a next page with a dynamic content, you should be able to create that content in the [`onEnterPage()` method](http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg09659.html)
```
public void createControl(Composite parent)
{
//
// create the composite to hold the widgets
//
this.composite = new Composite(parent, SWT.NONE);
//
// create the desired layout for this wizard page
//
GridLayout layout = new GridLayout();
layout.numColumns = 4;
this.composite.setLayout(layout);
// set the composite as the control for this page
setControl(this.composite);
}
void onEnterPage()
{
final MacroModel model = ((MacroWizard) getWizard()).model;
String selectedKey = model.selectedKey;
String[] attrs = (String[]) model.macroMap.get(selectedKey);
for (int i = 0; i < attrs.length; i++)
{
String attr = attrs[i];
Label label = new Label(this.composite, SWT.NONE);
label.setText(attr + ":");
new Text(this.composite, SWT.NONE);
}
pack();
}
```
As shown in the eclipse corner article [Creating JFace Wizards](http://www.eclipse.org/articles/article.php?file=Article-JFaceWizards/index.html):
We can change the order of the wizard pages by overwriting the getNextPage method of any wizard page.Before leaving the page, we save in the model the values chosen by the user. In our example, depending on the choice of travel the user will next see either the page with flights or the page for travelling by car.
```
public IWizardPage getNextPage(){
saveDataToModel();
if (planeButton.getSelection()) {
PlanePage page = ((HolidayWizard)getWizard()).planePage;
page.onEnterPage();
return page;
}
// Returns the next page depending on the selected button
if (carButton.getSelection()) {
return ((HolidayWizard)getWizard()).carPage;
}
return null;
}
```
We **define a method to do this initialization for the `PlanePage`, `onEnterPage()` and we invoke this method when moving to the `PlanePage`, that is in the `getNextPage()` method for the first page**. | If you want to start a new wizard based on your selection on the first page, you can use the JFace base class [org.eclipse.jface.wizard.WizardSelectionPage](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/wizard/WizardSelectionPage.html "org.eclipse.jface.wizard.WizardSelectionPage").
The example below shows a list of available wizards defined by an extension point.
When you press *Next*, the selected wizard is started.
```
public class ModelSetupWizardSelectionPage extends WizardSelectionPage {
private ComboViewer providerViewer;
private IConfigurationElement selectedProvider;
public ModelSetupWizardSelectionPage(String pageName) {
super(pageName);
}
private class WizardNode implements IWizardNode {
private IWizard wizard = null;
private IConfigurationElement configurationElement;
public WizardNode(IConfigurationElement c) {
this.configurationElement = c;
}
@Override
public void dispose() {
}
@Override
public Point getExtent() {
return new Point(-1, -1);
}
@Override
public IWizard getWizard() {
if (wizard == null) {
try {
wizard = (IWizard) configurationElement
.createExecutableExtension("wizardClass");
} catch (CoreException e) {
}
}
return wizard;
}
@Override
public boolean isContentCreated() {
// TODO Auto-generated method stub
return wizard != null;
}
}
@Override
public void createControl(Composite parent) {
setTitle("Select model provider");
Composite main = new Composite(parent, SWT.NONE);
GridLayout gd = new GridLayout(2, false);
main.setLayout(gd);
new Label(main, SWT.NONE).setText("Model provider");
Combo providerList = new Combo(main, SWT.NONE);
providerViewer = new ComboViewer(providerList);
providerViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof IConfigurationElement) {
IConfigurationElement c = (IConfigurationElement) element;
String result = c.getAttribute("name");
if (result == null || result.length() == 0) {
result = c.getAttribute("class");
}
return result;
}
return super.getText(element);
}
});
providerViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty()
&& selection instanceof IStructuredSelection) {
Object o = ((IStructuredSelection) selection)
.getFirstElement();
if (o instanceof IConfigurationElement) {
selectedProvider = (IConfigurationElement) o;
setMessage(selectedProvider.getAttribute("description"));
setSelectedNode(new WizardNode(selectedProvider));
}
}
}
});
providerViewer.setContentProvider(new ArrayContentProvider());
List<IConfigurationElement> providers = new ArrayList<IConfigurationElement>();
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry
.getExtensionPoint(<your extension point namespace>,<extension point name>);
if (extensionPoint != null) {
IExtension extensions[] = extensionPoint.getExtensions();
for (IExtension extension : extensions) {
IConfigurationElement configurationElements[] = extension
.getConfigurationElements();
for (IConfigurationElement c : configurationElements) {
providers.add(c);
}
}
}
providerViewer.setInput(providers);
setControl(main);
}
```
The corresponding wizard class looks like this:
```
public class ModelSetupWizard extends Wizard {
private ModelSetupWizardSelectionPage wizardSelectionPage;
public ModelSetupWizard() {
setForcePreviousAndNextButtons(true);
}
@Override
public boolean performFinish() {
// Do what you have to do to finish the wizard
return true;
}
@Override
public void addPages() {
wizardSelectionPage = new ModelSetupWizardSelectionPage("Select a wizard");
addPage(wizardSelectionPage);
}
}
``` | Eclipse JFace's Wizards | [
"",
"java",
"eclipse",
"jface",
""
] |
This is my function:
```
private IEnumerable<string> SeachItem(int[] ItemIds)
{
using (var reader = File.OpenText(Application.StartupPath + @"\temp\A_A.tmp"))
{
var myLine = from line in ReadLines(reader)
where line.Length > 1
let id = int.Parse(line.Split('\t')[1])
where ItemIds.Contains(id)
let m = Regex.Match(line, @"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)")
where m.Success == true
select new { Text = line, ItemId = id, Path = m.Groups[2].Value };
return myLine;
}
}
```
I get a compile error,because "myLine" is not a IEnumerable[string] and I don't know how to write IEnumerable[Anonymous]
"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable[AnonymousType#1]' to 'System.Collections.Generic.IEnumerable[string]'" | You cannot declare `IEnumerable<AnonymousType>` because the type has no (known) name at build time. So if you want to use this type in a function declaration, make it a normal type. Or just modify your query to return a `IENumerable<String>` and stick with that type.
Or return `IEnumerable<KeyValuePair<Int32, String>>` using the following select statement.
```
select new KeyValuePair<Int32, String>(id, m.Groups[2].Value)
``` | I am not necessarily recommending this...
It is a kind of subversion of the type system but you could do this:
1) change your method signature to return `IEnumerable` (the non generic one)
2) add a [cast by example](http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx) helper:
```
public static class Extensions{
public static IEnumerable<T> CastByExample<T>(
this IEnumerable sequence,
T example) where T: class
{
foreach (Object o in sequence)
yield return o as T;
}
}
```
3) then call the method something like this:
```
var example = new { Text = "", ItemId = 0, Path = "" };
foreach (var x in SeachItem(ids).CastByExample(example))
{
// now you can access the properties of x
Console.WriteLine("{0},{1},{2}", x.Text, x.ItemId, x.Path);
}
```
And you are done.
The key to this is the fact that if you create an anonymous type with the same order, types and property names in two places the types will be reused. Knowing this you can use generics to avoid reflection.
Hope this helps
Alex | LINQ: How to declare IEnumerable[AnonymousType]? | [
"",
"c#",
".net",
"linq",
""
] |
I am receiving an error a web based application that allows corporate intranet users to update their active directory details (phone numbers, etc).
The web application is hosted on IIS6 running Windows Server 2003 (SP1). The IIS website is using NTLM Authentication and the website has integrated security enabled. The IIS application pool runs using the “Network Service” account.
The web.config contains the following elements
```
<LdapConfigurations server="xxx.internal" root="OU=Staff Accounts,DC=xxx,DC=internal" domain="xxx" />
<identify impersonate=”true” />
```
Active Directory delegation is not needed as the following C# (.NET 3.5) code should pass on the correct impersonation details (including security token) onto Active Directory.
```
public void UpdateData(string bus, string bus2, string fax, string home, string home2, string mob, string pager, string notes)
{
WindowsIdentity windId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try
{
ctx = windId.Impersonate();
DirectorySearcher ds = new DirectorySearcher();
DirectoryEntry de = new DirectoryEntry();
ds.Filter = m_LdapUserFilter;
// i think this is the line causing the error
de.Path = ds.FindOne().Path;
this.AssignPropertyValue(bus, ADProperties.Business, ref de);
this.AssignPropertyValue(bus2, ADProperties.Business2, ref de);
this.AssignPropertyValue(fax, ADProperties.Fax, ref de);
this.AssignPropertyValue(home, ADProperties.Home, ref de);
this.AssignPropertyValue(home2, ADProperties.Home2, ref de);
this.AssignPropertyValue(mob, ADProperties.Mobile, ref de);
this.AssignPropertyValue(pager, ADProperties.Pager, ref de);
this.AssignPropertyValue(notes, ADProperties.Notes, ref de);
// this may also be causing the error?
de.CommitChanges();
}
finally
{
if (ctx != null)
{
ctx.Undo();
}
}
}
private void AssignPropertyValue(string number, string propertyName, ref DirectoryEntry de)
{
if (number.Length == 0 && de.Properties[propertyName].Value != null)
{
de.Properties[propertyName].Remove(de.Properties[propertyName].Value);
}
else if (number.Length != 0)
{
de.Properties[propertyName].Value = number;
}
}
```
User details can be retrieved from Active Directory without a problem however the issue arises when updating the users AD details. The following exception message is displayed.
```
System.Runtime.InteropServices.COMException (0x80072020): An operations error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at xxx.UpdateData(String bus, String bus2, String fax, String home, String home2, String mob, String pager, String notes)
at xxx._Default.btnUpdate_Click(Object sender, EventArgs e)
```
The code works fine in our development domain but not in our production domain. Can anyone please assist in helping resolving this problem? | The problem wasn't with the code but how the server was setup on the domain. For some reason the network administrator did not select the "Trust Computer for Delegation" option in active directory.
Happily the problem was not a "double-hop" issue :) | This is more than likely a permissions problem - there are numerous articles regards impersonation and delegation and the vagaries thereof here: <http://support.microsoft.com/default.aspx?scid=kb;en-us;329986> and here: <http://support.microsoft.com/default.aspx?scid=kb;en-us;810572>. | Updating Active Directory from Web Application Error | [
"",
"c#",
"asp.net",
"security",
"active-directory",
""
] |
I'm working with a 3rd party c# class that has lots of great methods and properties - but as time has gone by I need to extend that class with methods and properties of my own. If it was my code I would just use that class as my base class and add my own properties and method on top - but this class has an internal constructor. (In my opinion it was short sited to make the constructor internal in the first place - why limit the ability to subclass?)
The only thing I could think of was to create method / properties on my class that simply called into theirs - but it's acres of code and, well, it just doesn't "feel" right.
Is there any way to use this class a base class? | I will not discuss whether you can build your own Facade around that 3rd party class. Previous authors are right, the library could be designed in the way that will not allow this. Suppose they have some coupled classes that have singletons that should be initialized in specific order or something like this - there may be a lot of design mistakes (or features) that 3rd party developers never care about, because they do not suppose that you will use their library in that way.
But OK, lets suppose that building a facade is not an impossible task, and you have in fact only one problem - **there are too many methods you have to write wrappers around**, and it is not good to do this manually.
I see 3 solutions to address exactly that problem
1) I suppose that new "dynamic" types of .NET 4.0 will allow you to workaround that problem without having to write "acres of code"
You should incapsulate an instance of 3rd party class into your class as a privare member with dynamic keyword
Your class should be derived from Dynamic or implement IDynamicObject interface. You will have to implement GetMember/SetMember functions that will forward all calls to the encapsulated instance of 3rd party class
Well, c# 4.0 is a future, Let's see on other solutions:
2) Do not write code manually if you have significant number of public methods (say more then 100). I would write a little console app that uses reflection and finds all public members and then automatically generates code to call encapsulated instance. For example
```
public type MethodName(params)
{
this.anInstanceOf3rdPartyClass.MethodName(params);
}
```
3) You can do the same as 2, but with the help of existing reflection tools, for example RedGate .NET Reflector. It will help you to list all classes and methods signatures. Then, paste all this in Word and a simple VB macro will let you generate the same code as you could do in 2.
*Remark: As soon as you are not copying the code, but only copying method signatures, that are publicly available, I don't think you will violate the license agreement, but anyway it worth to re-check* | You ask: "Why limit the ability to subclass?"
Because designing for inheritance is tricky, particularly if you're designing for other developers to inherit from your class. As Josh Bloch says in Effective Java, you should design for inheritance or prohibit it. In my view, unless you have a good reason to design for inheritance, you shouldn't do so speculatively.
Does the class implement an interface which you could also implement (possibly by proxying most calls back to an instance of the original)? There's often no really elegant answer here - and the best solution will depend on the exact situation, including what you're trying to add to the class.
If you're not adding any more state - just convenience methods, effectively - then extension methods may work well for you. But they don't change what data an object is capable of storing, so if you need to add your own specialised data, that won't work. | Is there a way to derive from a class with an internal constructor? | [
"",
"c#",
"constructor",
"design-patterns",
""
] |
I'm sure you're all familiar with the voting systems that use AJAX (Um... look right over there <----)
I have something similar and when you vote up or down it uses AJAX to request the new value from votes.php. The problem is that I am using a session to get the userid so a person can only vote once. What happens if they sit on the page for an hour and then vote so the session is no longer there? What would be a good way of handling this situation? Should I redirect their page to the login screen? If so, how can I do that from the votes.php page that is being referenced by the AJAX request? Am I overlooking a good way of handling this situation? Any advice would be helpful. | Consider returning an http status of 401, and a JSON object detailing the reason. If you're using jQuery, that'll drop you to the `error()` callback, which you can then parse your object.
```
$.ajax({
data: {},
dataType: 'html',
success: function(data) {
// do whatever here
},
type: 'POST',
url: 'myserver.com',
error: function(XMLHttpRequest, textStatus, errorThrown) {
// XMLHttpRequest.responseText has your json string
// XMLHttpRequest.status has the 401 status code
if (XMLHttpRequest.status === 401) {
location.href = 'login.php';
}
}
});
```
I'm not familiar with PHP anymore, but this should work for just about any environment. You *may* have to suppress any automatic login form redirection though. In asp.net mvc the framework will see the 401 and push the default login form back, with a status of 200. | You should only store a link to the users identity in the session. Use sessions to identify a user as *x* and then get user *x*'s information from the database.
If your problem is with users sessions timing out then you should reconsider how you're using your sessions. Perhaps make them last until the browser closes? If you really want to make them a duration, then perhaps ping the server in intervals to keep the session alive.
Decide in your php script whether or not the user should be able to vote. If the session isn't set, or if they have already voted, return a message that you can identify with on the client side. If they already voted perhaps return `"voted":"true"` in a JSON object. Use JS to parse this object and understand what it means, taking the appropriate action. If the session isn't set, perhaps return `"session_set":"false"`, and then make javascript redirect with a `window.location = "login.php"` etc.
Only increment the counter for the user on a successful return of a counted vote. | How to deal with session timeouts in AJAX requests | [
"",
"php",
"session",
"error-handling",
"jquery",
""
] |
I'm having a problem when passing nulls to a ExecuteCommand() method using linq. My code is similar to the one that follows:
```
public void InsertCostumer(string name, int age, string address)
{
List<object> myList = new List<object>();
myList.Add(name);
myList.Add(age);
myList.Add(address);
StringBuilder queryInsert = new StringBuilder();
queryInsert.Append("insert into Customers(name, address) values ({0}, {1}, {2})");
this.myDataContext.ExecuteCommand(queryInsert.ToString(), myList.ToArray());
}
```
But, when a parameter is null (address, for instance), I get the following error: "A query parameter cannot be of type 'System.Object'."
The error doesn't occur if no parameters are null. I know the design in my example is a little poor, I just created a simplified example to focus on the problem. Any suggestions? | This is a known bug and Microsoft does not intend to fix it...
<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=305114&wa=wsignin1.0>
The work around is to either:
1. Drop into ADO.NET and execute the SQL Command directly
2. Format the string you're executing yourself and call ExecuteCommand with an empty object array (new object[0])
The second isn't a good idea as it opens you up to SQL inject attacks, but its a quick hack. | [Kevin is right](https://stackoverflow.com/a/1212258/2055187).
an example of his work around #1 in LinqPad. Need this **(Object)s??DBNull.Value**
```
string s = null;
//ExecuteCommand("insert into T(C1) values({0})", s); //Exception
SqlCommand cmd= new SqlCommand(){
CommandText = "insert into T(C1) values(@P0)",
Connection = new SqlConnection(this.Connection.ConnectionString),
};
//cmd.Parameters.AddWithValue("@P0", s); //SqlException
cmd.Parameters.AddWithValue("@P0", (Object)s??DBNull.Value);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Ts.OrderByDescending(t=>t.ID).Take(1).Dump();
``` | Linq ExecuteCommand doesn't understand nulls | [
"",
"c#",
"linq-to-sql",
"null",
""
] |
I'm writing a module for a php cms. In a function (a callback) I can access an object that comes from the framework code.
This object is of type `__PHP_Incomplete_Class` because the needed header file is not included before the session starts. I cannot include it without hacking the core cms code.
I wonder if is possibile to access the object properties anyway (casting to array does not work). I ask this because I can see the values with `var_dump()` but using `$object->var` I always get nulls. | This issue appends when you un serialize an object of a class that hasn't been included yet.
For exemple, if you call session\_start before include the class.
A PHPIncompleteClass object can't be accessed directly, but it's ok with foreach, serialize and gettype.
Calling is\_object with an PHPIncompleteClass object will result false.
So, if you find a '\_\_PHP\_Incomplete\_Class' object in your session and you've included your class after the session\_load, you can use this function :
```
function fixObject (&$object)
{
if (!is_object ($object) && gettype ($object) == 'object')
return ($object = unserialize (serialize ($object)));
return $object;
}
```
This will results a usable object :
```
fixObject($_SESSION['member']);
``` | I found this hack which will let you cast an object:
```
function casttoclass($class, $object)
{
return unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($class) . ':"' . $class . '"', serialize($object)));
}
```
From <http://blog.adaniels.nl/articles/a-dark-corner-of-php-class-casting/>
So you can do:
```
$obj = casttoclass('stdClass', $incompleteObject);
```
and then access properties as normal.
---
You could also define an `unserialize_callback_func` in a .htaccess/Apache configuration file. That way you wouldn't need to hack any PHP but you could include the file on demand. | forcing access to __PHP_Incomplete_Class object properties | [
"",
"php",
""
] |
Is it best to use a pre created class / api for database interaction (e.g Pear MDB2 or php's PDO) or create your own?
I will be only be using mysql with 1 database and perform relatively simple SELECT, INSERT, UPDATE, DELETE queries. | For small personal projects, I prefer to use my own DB interface class over a pre-built, but other people swear by pre-built APIs. By creating your own class, you are almost guaranteed to be reinventing the wheel. Using a pre-built API typically only requires that you learn how to issue your commands within that API. If you are working with a team of programmers, I recommend using a well documented API and incorporating its use into your best practices and procedures. In my experience I have felt that team programming and home-brewed DB classes don't mix well.
One thing I will say, if you have never written a class like this, I recommend doing so as a learning opportunity just to get some behind the scenes comprehension. The experience I gleaned from writing my own class has definitely helped me more than a few times when debugging work done by other programmers who used an API that I was unfamiliar with.
[Edit - Fixed some really bad grammar] | Definitely either use PDO or mysqli directly for your situation.
The only reason I would ever use a DB-abstraction layer, is if you plan to write distributable software that *must* run on multiple RDBM's.
If you know your target (just mysql) and you're going to write an app you manage, skip the db abstraction layer altogether. When you do finally get into a situation where you need to switch, you will often have to rewrite a lot of queries anyway (unless you use perfect standard SQL, which is kinda supported everywhere..).
Refactoring is key, abstraction might just over-complicate things. | PHP Database Class | [
"",
"php",
"mysql",
"database",
"class",
""
] |
I seem to have a bizarre error I just can't quite figure out. My website was working on one server, but when I transferred it to a new one it stopped working. I believe I've narrowed the error down to this line of code:
```
$ret = move_uploaded_file($tmp_name, $orig_path);
```
This is executed through an AJAX call so it's a little bit tricky to debug, but the script can send back an error code and then my JavaScript will `alert` it. So, I've wrapped it in two of these debug statements:
```
echo json_encode(array(
'success' => false,
'errno' => $tmp_name.' -> '.$orig_path,
));
exit;
$ret = move_uploaded_file($tmp_name, $orig_path);
echo json_encode(array(
'success' => false,
'errno' => 'no error',
));
exit;
```
The first one works fine and spits out something like:
```
error /tmp/phpk3RICU -> /home/username/Websites/website/photos/o/2-4a3354dd017a9.jpg
```
Perhaps I'm a bit of a linux noob, but I can't actually find `/tmp/phpk3RICU` on my system (is it deleted as soon as the script exits or what?). More on that in a sec though.
If I delete the first debug check and let `move_uploaded_file` run, the 2nd debug check never seems to get executed, which leads me to believe move\_uploaded\_file is hanging.
If instead of using `$tmp_name` I use a file I *know* doesn't exist, then the 2nd check DOES get executed. So... it seems like it just doesn't want to move that tmp file, but it's not reporting an error.
I'm running a fresh install of the LAMP stack on my Unbutu machine, installed through apt-get... let me know if you need more info.
Oh.. and don't know if it's relevant, but the file gets uploaded through flash. | Ugh. The problem was with permissions. 755 was enough on the other server, but not for this server it seems... not really sure why, I guess PHP is running under a different user? I'm not really sure how the whole permissions stuff works. What really boggles me is why `mkdir` and `move_uploaded_file` didn't fail and return false... | Do you upload the file via the AJAX call?
Uploaded files are deleted as soon as the script you uploaded them to finishes executing - that's why you can't find it in /tmp. | move_uploaded_file hangs? | [
"",
"php",
"upload",
"flash",
"apache2",
""
] |
Does anyone know of a Python class similar to [Java Robot](http://java.sun.com/javase/6/docs/api/java/awt/Robot.html)?
Specifically I would like to perform a screen grab in Ubuntu, and eventually track mouse clicks and keyboard presses (although that's a slightly different question). | If you have GTK, then you can use the [gtk.gdk.Display](http://www.pygtk.org/docs/pygtk/class-gdkdisplay.html) class to do most of the work. It controls the keyboard/mouse pointer grabs a set of `gtk.gdk.Screen` objects. | Check out [GNU LDTP](http://ldtp.freedesktop.org/wiki/):
> GNU/Linux Desktop Testing Project (GNU
> LDTP) is aimed at producing high
> quality test automation framework
> [...]
Especially [Writing LDTP test scripts in Python scripting language](http://ldtp.freedesktop.org/wiki/LDTP_test_scripts_in_python) | Is there a Python equivalent to Java's AWT Robot class? | [
"",
"python",
"linux",
"automation",
"screenshot",
"awtrobot",
""
] |
The error message is "The type or namespace name 'T' could not be found."
???
```
public static Expression<Func<T, bool>> MakeFilter(string prop, object val)
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
PropertyInfo pi = typeof(T).GetProperty(prop);
MemberExpression me = Expression.MakeMemberAccess(pe, pi);
ConstantExpression ce = Expression.Constant(val);
BinaryExpression be = Expression.Equal(me, ce);
return Expression.Lambda<Func<T, bool>>(be, pe);
}
```
Related links:
[Using reflection to address a Linqed property](https://stackoverflow.com/questions/791187/using-reflection-to-address-a-linqed-property)
<http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/>
[Runtime creation of generic Func<T>](https://stackoverflow.com/questions/658316/runtime-creation-of-generic-funct) | You need to make the method itself generic:
```
public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
-+-
^
+- this
``` | There's no generic argument defined for your method. You should define one (`MakeFilter<T>`):
```
public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
PropertyInfo pi = typeof(T).GetProperty(prop);
MemberExpression me = Expression.MakeMemberAccess(pe, pi);
ConstantExpression ce = Expression.Constant(val);
BinaryExpression be = Expression.Equal(me, ce);
return Expression.Lambda<Func<T, bool>>(be, pe);
}
``` | Returning a nested generic Expression<Func<T, bool>> | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
I am working on a CRON job that invokes a PHP script which does a lot of database work with loops.
It executes properly when I limit the data set, but when I run it against the full data set, the script errors out with a message:
```
Killed
```
set\_time\_limit is (0) and memory\_limit is (-1)
Here is the code section where it consistently dies:
```
echo "I'm in _getMemberDemographicAttrs\n";
if (! empty ( $member_id )) {
$query .= ' AND member_id = ' . $member_id;
}
$result = mysql_query ( $query, $this->_db );
if ($result) {
while ( $rule = mysql_fetch_assoc ( $result ) ) {
$rules [] = $rule;
}
if (! empty ( $rules )) {
mysql_free_result ( $result );
echo "I'm leaving _getMemberDemographicAttrs\n";
return $rules;
}
}
```
The output looks like this:
```
I'm in _getMemberDemographicAttrs<br/>
I'm leaving _getMemberDemographicAttrs<br/>
I'm in _getMemberDemographicAttrs<br/>
I'm leaving _getMemberDemographicAttrs<br/>
I'm in _getMemberDemographicAttrs<br/>
Killed
```
I've never seen this generic `Killed` error message and I'm wondering what is causing it to be killed? | You might be triggering the Linux out-of-memory (OOM) killer. Check `dmesg` for messages about it. It says which process was killed when this happens. | **Simple way to reproduce this `Killed` error:**
I was able to reproduce this error on `Ubuntu 12.10` with `PHP 5.3.10`.
Create a PHP script called `m.php` and save it:
```
<?php
function repeat(){
repeat();
}
repeat();
?>
```
Run it:
```
el@apollo:~/foo$ php m.php
Killed
```
The program takes 100% CPU for about 15 seconds then halts with the `Killed` message. Look at `dmesg | grep php` and there are clues:
```
el@apollo:~/foo$ dmesg | grep php
[2387779.707894] Out of memory: Kill process 2114 (php) score 868 or
sacrifice child
```
So in my case, the PHP program halted and printed "Killed" because it ran out of memory due to an infinite loop.
**Solutions:**
1. Increase the amount of RAM available or amount of memory available to this PHP program.
2. Break down the problem into smaller chunks that operate sequentially.
3. Rewrite the program so it has smaller memory requirements or doesn't go so deep with recursion. | Generic "Killed" error in PHP script | [
"",
"php",
"mysql",
"cron",
""
] |
I have a log file that has the following appender added to it :
```
logger.addAppender(new FileAppender(new PatternLayout(),"log.txt"));
```
the thing is, each time I'm running my application, additional logging information gets appended to the same log file. What can I do to overwrite the file each time ? | Use RollingFileAppender. | If you have an appender declared like so in a properties file:
```
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=file.log
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d %-5p %c - %m%n
```
Then what you want to add is
```
log4j.appender.LOGFILE.Append=false
```
The default value is `true`.
So, if you are declaring your appenders programmatically, then what you want to do is call `setAppend(false)`. | How do I overwrite a log file in log4j? | [
"",
"java",
"log4j",
"overwrite",
""
] |
```
public abstract class Parent {
private Parent peer;
public Parent() {
peer = new ??????("to call overloaded constructor");
}
public Parent(String someString) {
}
}
public class Child1 extends parent {
}
public class Child2 extends parent {
}
```
When I construct an instance of Child1, I want a "peer" to automatically be constructed which is also of type Child1, and be stored in the peer property. Likewise for Child2, with a peer of type Child2.
The problem is, on the assignment of the peer property in the parent class. I can't construct a new Child class by calling `new Child1()` because then it wouldn't work for Child2. How can I do this? Is there a keyword that I can use that would refer to the child class? Something like `new self()`? | ```
public abstract class Parent implements Clonable{
private Object peer;
// Example 1
public Parent() {
try {
peer = this.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
// Example 2
public Parent(String name) {
try {
peer = this.getClass().getConstructor(String.class).newInstance(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public <T extends Parent> T getPeer() {
return (T)peer;
}
}
public class Child01 extends Parent { }
public class Child02 extends Parent { }
```
It seems that the code may be more simple. | I'm not sure if it is possible to do this without running into cycles. I am convinced that it would be a lot clearer to write this using factory methods instead of constructors. | Call subclass constructor from abstract class in Java | [
"",
"java",
""
] |
I have a program where some Java classes are available. It is possible to decompile them? Is it possible to modify the source code of a class and recompile it, without having all the other `.class` files?
For example, suppose I have a `dog.class` file, that implement a subclass of animal, which is defined in `animal.class`.
* Can I recompile `dog.java` without `animal.class`?
* Can I recompile `dog.java` without `animal.java`?
I am not a Java developer, so please correct me if I'm not making any sense. | You'll need the `class` file in order to actually use the class, but that doesn't mean you'll need the source file.
Let's take a look at the possibilities using the `Dog` and `Animal` class example. Assuming that the `Dog` class is a subclass of the `Animal` class, we can do the following:
* If you have both `Animal.class` and `Animal.java`, you can make a `Dog` class.
* If you have `Animal.class` but not `Animal.java`, you can make a `Dog` class.
* If you don't have `Animal.class` but have `Animal.java`, you can make a `Dog` class. (This means that the `Animal.java` file will need to be compiled when the `Dog.java` file is compiled.)
* If you don't have either `Animal.class` nor `Animal.java`, you cannot make a `Dog` class.
Here is a tabular version of the above:
```
Have Animal.java? Have Animal.class? Can make Dog class?
----------------- ------------------ -------------------
Yes Yes --> Yes
Yes No --> Yes
No Yes --> Yes
No No --> No
```
If you have the `class` file, there are programs which can decompile the `class` file to produce a human-readable `java` source file, however, it will not restore the exact source that was used to produce the `class` file.
However, in this case, if all that is necessary is to extend the `Animal` class to make a new `Dog` class, the source code itself is not necessary.
Keep this in mind -- whenever a class is made in Java, it always extends the `Object` class. Even if we don't have access to the source code of the `Object` class, since we have access to the `Object.class` in Java, we are able to create our own classes.
This case is similar -- as long as we have the `class` file for a class, we can use it to the fullest extent. The only thing that is missing is the actual implementation which is listed in the source code. | In general, no. You could, however, make stubs for those missing classes (just for the compile), and then substitute in the original when you do have them. | Java class decompiling and recompiling | [
"",
"java",
"reverse-engineering",
"bytecode",
""
] |
I have two separate SELECT statements which are both GROUP-BY'd separately e.g.:
```
SELECT x, y, z FROM a GROUP BY x
SELECT x, n, o FROM b GROUP BY x
```
I would very much like to JOIN these two SELECTs together to combine their columns, such as:
```
SELECT x as x1, y, z FROM a GROUP BY x
LEFT JOIN (
SELECT x as x2, n, o FROM b GROUP BY x)
ON x1=x2;
```
Is this possible? I ask because MySQL is complaining
> You have an error in your SQL syntax;
> check the manual that corresponds to
> your MySQL server version for the
> right syntax to use near 'LEFT JOIN
> SELECT
> x as x2
If this is possible, any thoughts on what's wrong with my syntax?
Thanks very much! | This works
```
select * from (
(select 1 a,2 b,3 c) t1 left join (select null a,2 b,5 c) t2 on (t1.b=t2.b)
);
```
Alternatively,
```
select * from (
(select 1 a,2 b,3 c) t1 left join (select null a,2 b,5 c) t2 using (b)
);
```
Both result in
```
+---+---+---+------+---+---+
| a | b | c | a | b | c |
+---+---+---+------+---+---+
| 1 | 2 | 3 | NULL | 2 | 5 |
+---+---+---+------+---+---+
1 row in set (0.00 sec)
``` | There are a few ways that you can achieve this:
1. Best: Join the tables BEFORE grouping like so:
```
SELECT a.x, y, z, n, o
FROM a INNER JOIN b ON a.x = b.x
GROUP BY a.x, b.x;
```
2. Select from the two queries as sub-queries like so:
```
SELECT *
FROM (SELECT x, y, z FROM a GROUP BY x) AS a
INNER JOIN (SELECT x, n, o FROM b GROUP BY x) AS b
ON a.x = b.x;
``` | MySQL: Is it possible to JOIN the GROUP-BY'd results to two SELECTs? | [
"",
"sql",
"mysql",
"join",
""
] |
I'm trying to run this query:
```
SELECT
Destaque.destaque, Noticia.id, Noticia.antetitulo,
Noticia.titulo, Noticia.lead, Noticia.legenda,
Noticia.publicacao, Seccao.descricao, Album.pasta,
Foto.ficheiro, Foto.descricao, Cronista.nome,
Cronista.profissao, Cronista.ficheiro,
AudioFile.*, AudioCollection.*, VideoFile.*, VideoCollection.*
FROM
nt_highlights AS Destaque
LEFT JOIN nt_noticias AS Noticia ON Destaque.noticia_id = Noticia.id
LEFT JOIN mm_fotos AS Foto ON Noticia.foto_id = Foto.id
LEFT JOIN nt_temas AS Seccao ON Noticia.tema_id = Seccao.id
LEFT JOIN mm_albuns AS Album ON Foto.album_id = Album.id
LEFT JOIN nt_cronistas AS Cronista ON Cronista.id = Noticia.cronista_id
LEFT JOIN ntNoticias_mmFiles AS Rel ON Rel.noticia_id = Noticia.id
LEFT JOIN mm_files AS AudioFile ON AudioFile.id = Rel.file_id
LEFT JOIN mm_coleccoes AS AudioCollection ON AudioFile.coleccao_id = AudioCollection.id
LEFT JOIN mm_files AS VideoFile ON VideoFile.id = Rel.file_id
LEFT JOIN mm_coleccoes AS VideoCollection ON VideoFile.coleccao_id = VideoCollection.id
WHERE
Destaque.area_id = 1
AND Noticia.paraPublicacao = 1
AND Noticia.publicacao <= NOW()
AND (AudioFile.mimeType != '' OR AudioFile.id IS NULL)
AND (VideoFile.mimeType = '' OR VideoFile.id IS NULL)
ORDER BY
Destaque.destaque
```
This will get me a number of articles (from `nt_noticias`) and the idea is to get at the same time a `Video` and an `Audio` file from the `mm_files` table.
What happens is that when I have an article with a sound and a video, MySQL will return 4 rows:
* with the sound (video is null)
* with the video (sound is null)
* with all nulls
* with the sound AND the video
How can I "force" it to return just one row per article with any existing video AND audio associated? What am I doing wrong here? | I *think* you want something like this:
```
SELECT
Destaque.destaque, Noticia.id, Noticia.antetitulo,
Noticia.titulo, Noticia.lead, Noticia.legenda,
Noticia.publicacao, Seccao.descricao, Album.pasta,
Foto.ficheiro, Foto.descricao, Cronista.nome,
Cronista.profissao, Cronista.ficheiro,
AudioFile.*, AudioCollection.*, VideoFile.*, VideoCollection.*
FROM
nt_highlights AS Destaque
LEFT JOIN nt_noticias AS Noticia ON Destaque.noticia_id = Noticia.id
LEFT JOIN mm_fotos AS Foto ON Noticia.foto_id = Foto.id
LEFT JOIN nt_temas AS Seccao ON Noticia.tema_id = Seccao.id
LEFT JOIN mm_albuns AS Album ON Foto.album_id = Album.id
LEFT JOIN nt_cronistas AS Cronista ON Cronista.id = Noticia.cronista_id
LEFT JOIN ntNoticias_mmFiles AS AudioRel ON Rel.noticia_id = Noticia.id
AND AudioRel.file_id IN (
SELECT file_id
FROM ntNoticias_mmFiles
WHERE noticia_id = Noticia.id AND IsAudioFile = 1 /* whatever the check is */
LIMIT 1
)
LEFT JOIN mm_files AS AudioFile ON AudioFile.id = Rel.file_id
LEFT JOIN mm_coleccoes AS AudioCollection ON AudioFile.coleccao_id = AudioCollection.id
LEFT JOIN ntNoticias_mmFiles AS VideoRel ON VideoRel.noticia_id = Noticia.id
AND VideoRel.file_id IN (
SELECT file_id
FROM ntNoticias_mmFiles
WHERE noticia_id = Noticia.id AND IsVideoFile = 1 /* whatever the check is */
LIMIT 1
)
LEFT JOIN mm_files AS VideoFile ON VideoFile.id = Rel.file_id
AND VideoFile.IsVideoFile = 1
LEFT JOIN mm_coleccoes AS VideoCollection ON VideoFile.coleccao_id = VideoCollection.id
WHERE
Destaque.area_id = 1
AND Noticia.paraPublicacao = 1
AND Noticia.publicacao <= NOW()
ORDER BY
Destaque.destaque
```
My thought was this:
You want one audio file and one video file, at most. There are several files available per `Noticia`, so you need to make sure that a maximum of one file per type gets into the join. This also means you have to join in the `ntNoticias_mmFiles` table twice — once per type.
This is what the sub-queries in the join conditions are supposed to do: Select one row per file type. Going on from there you LEFT JOIN the rest of the data in, just like you already do. | The JOIN will return all the combinations, that's the problem.
If you only have one audio and/or videofile per article then you might want to look at subselects.
In SQL Server this would look something like (untested code):
```
SELECT title,
(select TOP 1 audio from audio where audio.aid = articles.id) as Audio,
(select TOP 1 video from video where video.aid = articles.id) as Video
FROM articles
```
Be careful that on large datasets this can perform poorly as the subselects in this example are executed individually for each row returned to the outer query. For example, if you return 10,000 articles then a total of 20,001 queries would actually be executed on the server.
There are other possible answers to overcome this but they get more involved (I suspect you could do something with a derived table but it eludes me at the moment). | MySQL with 2 LEFT JOINs on the same table | [
"",
"sql",
"mysql",
"left-join",
""
] |
Referring on [this question](https://stackoverflow.com/questions/868112/loading-files-into-variables-in-python), I have a similar -but not the same- problem..
On my way, I'll have some text file, structured like:
```
var_a: 'home'
var_b: 'car'
var_c: 15.5
```
And I need that python read the file and then create a variable named var\_a with value 'home', and so on.
Example:
```
#python stuff over here
getVarFromFile(filename) #this is the function that im looking for
print var_b
#output: car, as string
print var_c
#output 15.5, as number.
```
Is this possible, I mean, even keep the var type?
Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.
**EDIT**: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with
```
config.get("set", "var_name")
```
But what I'll love is to refer to the variable directly, as I declared it in the python script...
There is a way to import the file as a python dictionary?
Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.
**Edit 2**: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:
```
#for the example, i dont load the file but create a var with the supposed file content
file_content = "'var_a': 4, 'var_b': 'a string'"
mydict = dict(file_content)
#Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required
file_content_2 = "{'var_a': 4, 'var_b': 'a string'}"
mydict_2 = dict(json.dump(file_content_2, True))
#Error:
#Traceback (most recent call last):
#File "<pyshell#5>", line 1, in <module>
#mydict_2 = dict(json.dump(file_content_2, True))
#File "C:\Python26\lib\json\__init__.py", line 181, in dump
#fp.write(chunk)
#AttributeError: 'bool' object has no attribute 'write'
```
In what kind of issues can I fall with the JSON format?
And, how can I read a JSON array in a text file, and transform it in a python dict?
P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language. | Load your file with [JSON](http://docs.python.org/library/json.html) or [PyYAML](http://pyyaml.org/wiki/PyYAML) into a dictionary `the_dict` (see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using `globals().update(the_dict)`.
If you want it in a local dictionary instead (e.g. inside a function), you can do it like this:
```
for (n, v) in the_dict.items():
exec('%s=%s' % (n, repr(v)))
```
as long as it is safe to use `exec`. If not, you can use the dictionary directly. | > But what i'll love is to refer to the variable direclty, as i declared it in the python script..
Assuming you're happy to change your syntax slightly, just use python and import the "config" module.
```
# myconfig.py:
var_a = 'home'
var_b = 'car'
var_c = 15.5
```
Then do
```
from myconfig import *
```
And you can reference them by name in your current context. | Best way to retrieve variable values from a text file? | [
"",
"python",
"variables",
"text-files",
""
] |
I have `jdk1.6.0_13` installed, but when I try to find a `javax.servlet` package, or press `Ctrl`+`Space` in Eclipse after `Servlet` I cannot get anything. Where can I download this package, and why isn't it included in standard distribution for developers? | `javax.servlet` is a package that's part of Java EE (Java Enterprise Edition). You've got the JDK for Java SE (Java Standard Edition).
You could use [the Java EE SDK](http://java.sun.com/javaee/downloads/?intcmp=1282) for example.
Alternatively simple servlet containers such as [Apache Tomcat](http://tomcat.apache.org/) also come with this API (look for `servlet-api.jar`). | A bit more detail to Joachim Sauer's answer:
On Ubuntu at least, the metapackage `tomcat6` depends on metapackage `tomcat6-common` (and others), which depends on metapackage `libtomcat6-java`, which depends on package **`libservlet2.5-java`** (and others). It contains, among others, the files `/usr/share/java/servlet-api-2.5.jar` and `/usr/share/java/jsp-api-2.1.jar`, which are the servlet and JSP libraries you need. So if you've installed Tomcat 6 through apt-get or the Ubuntu Software Centre, you already have the libraries; all that's left is to get Tomcat to use them in your project.
Place libraries `/usr/share/java/servlet-api-2.5.jar` and `/usr/share/java/jsp-api-2.1.jar` on the class path like this:
* For all projects, by configuring Eclipse by selecting Window ->
Preferences -> Java -> Installed JREs, then selecting the JRE you're
using, pressing Edit, then pressing Add External JARs, and then by
selecting the files from the locations given above.
* For just one
project, by right-clicking on the project in the Project Explorer
pane, then selecting Properties -> Java Build Path, and then pressing
Add External JARs, and then by selecting the files from the locations
given above.
Further note 1: These are the correct versions of those libraries for use with Tomcat 6; for the other Tomcat versions, see the table on page <http://tomcat.apache.org/whichversion.html>, though I would suppose each Tomcat version includes the versions of these libraries that are appropriate for it.
Further note 2: Package `libservlet2.5-java`'s description (`dpkg-query -s libservlet2.5-java`) says: 'Apache Tomcat implements the **Java Servlet and the JavaServer Pages (JSP)** specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run. This package contains the Java Servlet and JSP library.' | Where's javax.servlet? | [
"",
"java",
"servlets",
""
] |
I need a function which takes a line (known by its coordinates)
and return a line with **same** angle, but **limited to certain length**.
My code gives correct values **only** when the line is turned **'right'**
(proven only empirically, sorry).
Am I missing something?
```
public static double getAngleOfLine(int x1, int y1, int x2, int y2) {
double opposite = y2 - y1;
double adjacent = x2 - x1;
if (adjacent == Double.NaN) {
return 0;
}
return Math.atan(opposite / adjacent);
}
// returns newly calculated destX and destY values as int array
public static int[] getLengthLimitedLine(int startX, int startY,
int destX, int destY, int lengthLimit) {
double angle = getAngleOfLine(startX, startY, destX, destY);
return new int[]{
(int) (Math.cos(angle) * lengthLimit) + startX,
(int) (Math.sin(angle) * lengthLimit) + startY
};
}
```
BTW: I know that returning arrays in Java is stupid,
but it's just for the example. | In Python because I don't have a Java compiler handy:
```
import math
def getLengthLimitedLine(x1, y1, x2, y2, lengthLimit):
length = math.sqrt((x2-x1)**2 + (y2-y1)**2)
if length > lengthLimit:
shrink_factor = lengthLimit / length
x2 = x1 + (x2-x1) * shrink_factor
y2 = y1 + (y2-y1) * shrink_factor
return x2, y2
print getLengthLimitedLine(10, 20, 25, -5, 12)
# Prints (16.17, 9.71) which looks right to me 8-)
``` | It would be easier to just treat it as a vector. Normalize it by dividing my its magnitude then multiply by a factor of the desired length.
In your example, however, try Math.atan2. | Need a function to limit a line (known by its coordinates) in its length | [
"",
"java",
"math",
"graphics",
"image-processing",
"drawing",
""
] |
I am migrating a MSSQL script to Oracle SQL and I can't figure out what one line in the script is doing.
I am very new to SQL.
```
CREATE TABLE HA_BACKUP_PROCESSES
(
ID numeric (10, 0) NOT NULL ,
PROCESS_ID numeric (10, 0) NOT NULL ,
BACKUP_PROCESS_ID numeric (10, 0) NOT NULL ,
CONSTRAINT HA_BCK_PROC_PK PRIMARY KEY (ID)
USING INDEX TABLESPACE userdata001
)
```
In the above code, what is the '`USING INDEX TABLESPACE userdata001`' statement doing? | This clause allows selection of the tablespace in which the index associated with a UNIQUE or PRIMARY KEY constraint will be created. If not specified, default\_tablespace is used, or the database's default tablespace if default\_tablespace is an empty string | Tablespaces are nothing more than logical containers for datafiles and indexes.
When setting up an Oracle instance, you must define your tablespaces before you can create datafiles. Then, when you create a table or index you must specify the tablespace you want to create the datafile in, or accept the default tablespace. | What Does This Oracle SQL Statement Do? | [
"",
"sql",
"oracle",
""
] |
I've reflecting a load of tables in an exiting mysql db. I want to express that any columns of a certain name in any table default to datetime.now(). However naively looping through the tables and columns and just setting default on those I find that have a certain name doesn't work, When doing session.add(); session.flush() I get the following error:
```
AttributeError: 'builtin_function_or_method' object has no attribute '__visit_name__'
```
This would seem to be tied up in the call to \_set\_parent (and the this `self._init_items(*toinit)` at line 721 in sqlalchemy.schema.
Does anyone know if there's a way to do this without either going through all of my reflected tables and adding Column(..) lines every where all doing the same thing or resorting to really ugly hacks? | Five years later, you can use event listeners[1]. You can register a listener with a function to run:
```
def do_this_on_column_reflect(inspector, table, column_info):
column_name = column_info.get("name")
if column_name == "create_datetime":
column_info["default"] = datetime.now()
event.listen(Table, "column_reflect", do_this_on_column_reflect)
```
[1] <http://docs.sqlalchemy.org/en/latest/core/events.html#sqlalchemy.events.DDLEvents.column_reflect>
[2] <http://docs.sqlalchemy.org/en/latest/core/event.html#sqlalchemy.event.listen> | Another option is to override the columns that need defaults while reflecting:
```
Table('some_table', metadata,
Column('create_time', DateTime, default=datetime.now),
autoload=True)
```
Unfortunately you currently can't reflect the datatype and set SQLAlchemy side default at the same time. One could argue though that the datatype is part of the interface definition and so the redundancy doesn't create a maintenance issue - if the columns datatype changes you most likely need to change the default value function too. | Override default in sqlalchemy reflected tables | [
"",
"python",
"sqlalchemy",
""
] |
i want to take inputs like this
10 12
13 14
15 16
..
how to take this input , as two diffrent integers so that i can multiply them in python
after every 10 and 12 there is newline | I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space.
In python you do:
```
s = raw_input('Insert 2 integers separated by a space: ')
a,b = [int(i) for i in s.split(' ')]
print a*b
```
Explanation:
```
s = raw_input('Insert 2 integers separated by a space: ')
```
raw\_input takes everything you type (until you press enter) and returns it as a string, so:
```
>>> raw_input('Insert 2 integers separated by a space: ')
Insert 2 integers separated by a space: 10 12
'10 12'
```
In s you have now '10 12', the two int are separated by a space, we split the string at the space with
```
>>> s.split(' ')
['10', '12']
```
now you have a list of strings, you want to convert them in int, so:
```
>>> [int(i) for i in s.split(' ')]
[10, 12]
```
then you assign each member of the list to a variable (a and b) and then you do the product a\*b | ```
f = open('inputfile.txt')
for line in f.readlines():
# the next line is equivalent to:
# s1, s2 = line.split(' ')
# a = int(s1)
# b = int(s2)
a, b = map(int, line.split(' '))
print a*b
``` | Parsing numbers in Python | [
"",
"python",
"parsing",
""
] |
EDIT: When I merge link\_def.cpp with link\_dec.h, I only get the first error, not the second two.
I got these linker errors when I tried to compile some code:
CODE:
```
#include"list_dec.h"
#include"catch.h"
int main()
{
list<int, 100> L1;
try
{
L1.return_current();
}
catch(err)
{
return -1;
}
return 0;
}
```
ERRORS:
```
Linking...
main.obj : error LNK2019: unresolved external symbol "public: __thiscall list<int,100>::~list<int,100>(void)" (??1?$list@H$0GE@@@QAE@XZ) referenced in function __catch$_main$0
main.obj : error LNK2019: unresolved external symbol "public: int __thiscall list<int,100>::return_current(void)" (?return_current@?$list@H$0GE@@@QAEHXZ) referenced in function _main
main.obj : error LNK2019: unresolved external symbol "public: __thiscall list<int,100>::list<int,100>(void)" (??0?$list@H$0GE@@@QAE@XZ) referenced in function _main
```
If anyone needs the code for list\_dec.h, catch.h, and list\_def.cpp (the definition for the list class), just comment, I don't want to include them if they're irrelevent though, as they are very large.
since someone wanted to see list\_dec.h (which i've merged with list\_def.cpp for the time being)
list\_dec.h:
```
template<class T, size_t limit>
class list
{
public:
//constructors
list();
list(const list<T, limit>& lst);
~list();
//assignment operator
void operator=(const list<T, limit>& lst);
//append new items
void append(const T& item);
//clear the list
void clear();
//return current item
T return_current();
//test if item is last item
bool last();
//make current item head of the list
void make_head();
//move to the next item
bool next();
//interrogation
size_t return_count();
size_t return_limit();
protected:
size_t count; //# of items in list
size_t current; //current item
T data[limit]; //array of elements of list
//internal functions
void copy(const list<T, limit>& lst);
};
//copier function
template<class T, size_t limit>
void list<T, limit>::copy(const list<T, limit>& lst)
{
count = lst.count;
current = lst.current;
for(size_t n = 0; n < count; n++)
{
data[n] = lst.data[n];
}
return;
}
//constructor
template<class T, size_t limit>
inline list<T, limit>::list()
{
count = 0;
current = 0;
}
//copy constructor
template<class T, size_t limit>
inline list<T, limit>::list(const list<T, limit>& lst)
{
copy(lst);
}
//assignment operator
template<class T, size_t limit>
inline void list<T, limit>::operator=(const list<T, limit>& lst)
{
clear();
copy(lst);
return;
}
//destructor
template<class T, size_t limit>
inline list<T, limit>::~list()
{
clear();
}
//append function
template<class T, size_t limit>
void list<T, limit>::append(const T& item)
{
if(count == limit)
{
throw CX_OVERFLOW;
}
data[count] = item;
count++;
return;
}
//return current item
template<class T, size_t limit>
T list<T, limit>::return_current()
{
if(count == 0)
{
throw CX_NULL;
}
if(current == count)
{
throw CX_ATEND;
}
return data[current];
}
//test if <current> pointer is at tail
template<class T, size_t limit>
inline bool list<T, limit>::last()
{
if(current == count)
{
return true;
}
else
{
return false;
}
}
//set current pointer to head
template<class T, size_t limit>
inline void list<T, limit>::make_head()
{
current = 0;
return;
}
//set current pointer to next pointer in list
template<class T, size_t limit>
bool list<T, limit>::next()
{
if(count == 0)
{
throw CX_NULL;
}
if(current == count)
{
throw CX_ATEND;
}
current++;
if(current == count)
{
return false;
}
return true;
}
//interrogation functions
template<class T, size_t limit>
inline size_t list<T, limit>::return_count()
{
return count;
}
template<class T, size_t limit>
inline size_t list<T, limit>::return_limit()
{
return limit;
}
``` | It is possible to read linker errors with a bit of effort. Let's give it a try:
```
main.obj : error LNK2019: unresolved external symbol "public: __thiscall list<int,100>::~list<int,100>(void)" (??1?$list@H$0GE@@@QAE@XZ) referenced in function __catch$_main$0
```
* The error occurs in `main.obj`, that is the object file generated from main.cpp.
* The problem is an "unresolved external symbol". That is, you reference a symbol that is expected to be defined in another compilation unit, but the linker can not find this definition.
* The symbol in question is a public member function (\_\_thiscall is the calling convention for member functions).
* Now we come to the really useful information: `list<int,100>::~list<int,100>(void)"` tells us that the problem is the destructor for the class template list, specialized for `<int, 100>`. This part is nicely formatted and perfectly straightforward. For the second error, we also see the return type: `int __thiscall list<int,100>::return_current(void)`. That is, a function that returns an int, uses the \_\_thiscall calling convention, belongs to list, is called return\_current, and takes no parameters.
* `??1?$list@H$0GE@@@QAE@XZ` can pretty much be ignored. This is the name of the symbol, mangled by the compiler, and so this is the name the linker looks for inside the .obj file. But since the linker already told us the readable C++ name of the symbol, we don't really need this. (unless you decide to go digging in the .obj file yourself).
* Finally, it tells us that the symbol is referenced in the function main. (The general rule when reading linker errors is to ignore the bits you don't understand. And I'm not entirely sure what the "catch" part here means, but it's tied to the exception handling you do inside main.
So there you have it. The first error states that the definition of the list's destructor can not be found. If the function is not declared inline in the class definition, it should be defined in another .cpp file. I assume this is your `list_def.cpp`, and that this file gets compiled and passed to the linker as well.
However, this leads us to a nice little problem with templates. They are compile-time constructs, and a template has to be instantiated before the compiler emits code for it. In the output from your compiler, no code exists for the class template `list`, nor for the specialization `list<int, 84>`, because that specialization is not used. The compiler only generates the specializations that are actually needed.
And when the compiler processes list\_def.cpp, *no* specializations seem to be required. It can't see into other .cpp files, like your main.cpp. It only sees the .cpp file currently being compiled, and anything it `#include`s. Since it can't see `list<int, 100>`, it doesn't generate any code for that specialization, and then when the object files are passed to the linker, it is unable to find the definition of the `list<int, 100>` symbol and emits an error.
The usual solution is to define all members of class templates inline in the header. That way, the definition is visible to any compilation unit including the header, and so the required templates specializations can be created by the compiler.
Specifically, the following will produce a linker error:
```
// .h
template <int n>
class Foo {
int Bar();
};
// .cpp
template <int n>
int Foo::Bar() {
return n; // Error: This is not visible from other .cpp files
}
```
So will simply moving the .cpp contents into the header:
```
// .h
template <int n>
class Foo {
int Bar();
};
template <int n>
int Foo::Bar() {
return n; // Error: This is will cause the function to be defined in every .cpp file that includes it, so you'll get a *different* linker error instead (multiple definitions)
}
```
But this works, and is the usual solution
```
// .h
template <int n>
class Foo {
int Bar() { return n; } // just define it here, inside the class definition, and it is implicitly inline, so it's ok that multiple .cpp files see it
};
```
Or alternatively:
```
// .h
template <int n>
class Foo {
int Bar();
};
// still in .h
template <int n>
inline int Foo::Bar() { // explicitly marking it inline works too. Now the compiler knows that it might be defined in multiple .cpp files, and these definitions should be merged back together
return n;
}
```
A more unusual, but occasionally useful, solution is to explicitly instantiate the template in the compilation unit that defines it. So in `list_def.cpp`, add this line after the template definition:
```
template class list<int, 100>;
```
This tells the compiler specifically to generate code for that specialization, even if it is not otherwise used in this compilation unit. And obviously, this approach is only useful if you know in advance which specializations will be needed.
**Edit:**
It looks like you never define the `clear()` function which is called from the destructor. That is the reason for the final linker error you're getting after including everything in the header. | Another hunch: how have you defined the class template's member functions? Are they `inline`d? Do you have the definition in a separate implementation file? If you do, you may be running into this issue: [FAQ 35.16](http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16). | What do these linking errors mean? (C++) (MSVC++) | [
"",
"c++",
"templates",
"linker",
""
] |
I'm looking for an Open Source Project for delivering a course trainings and to manage courses, instructors. I need something similar to [Moodle](http://moodle.org) but in Java.
Thanks | Check out <http://www.jediproject.net/> | There is [Sakai](http://sakaiproject.org/portal). Reasonably documented, but also pretty complex. | Java Open Source Course Management System | [
"",
"java",
"open-source",
"sakai",
""
] |
I make an AJAX POST request to a PHP script on my server. That script in turn makes a GET request to a php script on an external server to check the contents of a text file. However, it takes a very long time to come back with a result. Why is the case?
**AJAX Post Request to Script on my server**
```
session_start();
$fileName = $_POST['textFile'];
$result = file_get_contents($_SESSION['serverURL']."fileReader.php?textFile=$fileName");
echo $result;
```
**GET Request to a script on different server**
```
$fileName = $_GET['textFile'];
if (file_exists('text/'.$fileName.'.txt')) {
$lines = file('text/'.$fileName.'.txt');
echo $lines[sizeof($lines)-1];
}
else{
echo 0;
}
```
These are very simple scripts and its only checking a very small text file, so why does it take so long?
I am making other AJAX request on my site but these surely can't be causing a problem. Having said this, the returned value of that text file always co-incides with the completion of another AJAX request which initiates a script that takes a while to complete on my server, but how would these effect each other?! They shouldn't right? | You don’t have to take the route over HTTP to get the last line of a file. Why don’t you stay inside the file system and use a function like that to retrieve the last line:
```
function fileGetLine($filename, $line) {
if (!is_file($filename) || !is_readable($filename)) {
// invalid file name or not readable
return false;
}
if (!is_int($line)) {
// invalid line number
return false;
}
$lines = file($filename);
$lineCount = count($lines);
if ($line < 0) {
// negative line number, count from end
$line = $lineCount + $line;
}
if ($line < 0 || $line >= $lineCount) {
// line number out of bounds
return false;
}
return $lines[$line];
}
session_start();
echo fileGetLine('text/'.basename($_POST['textFile']).'.txt', -1);
``` | Network latency and CPU overload are likely the biggest factors in the delay here.
Every time you open up a new connection, you have the overhead of opening the connection, as well as the reduced transfer rate(as opposed to reading a file directly).
Also regarding your "other" AJAX request which takes a while to complete... This can in fact affect everything else on the system. If it takes a long time to complete, it is probably safe to say that it is eating up a lot of CPU or disk bandwidth. Any intensive process like this can affect everything else on the system. Especially if you are working with the same files or database tables, you can be thrashing your filesystem or database at this time.
It's really hard to say what the problem is without seeing it, you should time each piece of your system, and monitor CPU and memory loads during requests. Try to figure out where the bottleneck is. | Why does file_get_contents take so long? | [
"",
"php",
"ajax",
"file",
""
] |
I know that I can use implicit conversions with a class as follows but is there any way that I can get a instance to return a string without a cast or conversion?
```
public class Fred
{
public static implicit operator string(Fred fred)
{
return DateTime.Now.ToLongTimeString();
}
}
public class Program
{
static void Main(string[] args)
{
string a = new Fred();
Console.WriteLine(a);
// b is of type Fred.
var b = new Fred();
// still works and now uses the conversion
Console.WriteLine(b);
// c is of type string.
// this is what I want but not what happens
var c = new Fred();
// don't want to have to cast it
var d = (string)new Fred();
}
}
``` | In fact, the compiler will implicitly cast `Fred` to `string` but since you are declaring the variable with `var` keyword the compiler would have no idea of your actual intention. You could declare your variable as string and have the value implicitly casted to string.
```
string d = new Fred();
```
Put it differently, you might have declared a dozen implicit operators for different types. How you'd expect the compiler to be able to choose between one of them? The compiler will choose the actual type by default so it won't have to perform a cast at all. | With an implicit operator (which you have) you should just be able to use:
```
string d = new Fred();
``` | Class implicit conversions | [
"",
"c#",
"casting",
"type-inference",
"implicit-typing",
""
] |
I like to reuse expressions for DRY reasons, but how do I reuse the expressions within a LINQ statement?
e.g.
I have
```
public static class MyExpressions {
public static Expression<Func<Product,bool>> IsAGoodProduct() {
return (p) => p.Quality>3;
}
}
```
And would like to use that in LINQ statements, so
```
var goodProds = from p in dataContext.Products
where ????? // how do I use IsAGoodProduct here?
select p;
```
Sure, I could use the IQueryableExtension.Where function, but that would make joins and other functions alot uglier for more complex queries.
Is this possible or is it a limitation of LINQ? | If you move from the LINQ syntactic sugar it is possible:
```
var goodProds = dataContext.Products.Where(MyExpressions.IsAGoodProduct());
```
Without it, it isn't possible.
There's nothing to stop you mixing the two styles to build a single query though.
Example:
```
var goodProds = from p in dataContext.Products
.Where(MyExpressions.IsAGoodProduct())
group p by p.Category into g
select new {Category = g.Key, ProductCount = g.Group.Count()};
``` | I had the same problem and wanted to preserve the ability to use extension methods within the query syntax (as with ordinary supported functions...). A solution might be [this library](https://github.com/axelheer/nein-linq) (spoiler: I‘m the author).
You just implement the method to reuse twice, once for general use and once for queries.
```
public static class MyFunctions {
[InjectLambda]
public static bool IsAGoodProduct(Product product) {
return product.Quality>3;
}
public static Expression<Func<Product,bool>> IsAGoodProduct() {
return (p) => p.Quality>3;
}
}
```
The actual query can then look like expected.
```
var goodProds = from p in dataContext.Products.ToInjectable()
where p.IsAGoodProduct()
select p;
```
The `ToInjectable` call creates a lightweight proxy, which replaces the `IsAGoodProduct` method call (if marked accordingly) with the desired lambda expression. Thus, you can use extension methods wherever within the query -- parameterized methods work as well. | How can I reuse expressions within LINQ statements? | [
"",
"c#",
"linq",
"lambda",
""
] |
I recently became quite interested in developing an adobe air application, and just had a few questions that maybe some more experienced air developers could answer.
Firstly, what is the average time-frame required for an air project. Mainly I'm planning a somewhat ambitious project of porting a specific forum framework over to an air app. How long would you estimate this would take me to do personally? I want something more than just the standard browser inside an app, more along the lines of built in controls/features for all the standard functionality.
Secondly, can apps be done completely with javascript/html/xml? I'm quite proficient with these 3 technologies, but have no real experience with flex/flash. This includes making the chrome as well. Do specific features require specific languages to be involved?
Finally, any good books/articles you would recommend? Preferably more advanced books/resources that lay the groundwork for making professional quality applications.
Any additional tips or insights on what you think may be useful are very much welcomed. | [Start reading Adobe AIR for AJAX Developers](http://www.adobe.com/products/air/develop/ajax/), particularly the [Getting Started section](http://www.adobe.com/devnet/air/ajax/getting_started.html) | Without knowing your skill level how would we know how long it will take you personally?
I have built and released apps in one week in my spare time, doesn't mean your project or your skillset for this project will be comparable.
Adobe Air development is fast and easy in general.
Don't reinvent the wheel making button and menu classes, leverage what's already out there.
Take a look at MadComponents: <http://code.google.com/p/mad-components/> for UI
Other than that there are several robust tweening and graphics libraries out there.
There's also stage3d and frameworks to support 2d and 3d development for almost near native performance. | Adobe Air Questions/Resources | [
"",
"javascript",
"apache-flex",
"flash",
"air",
"adobe",
""
] |
I created a sort of modal overlay and then a content with the overlay.. the modal overlay has opacity set and it works but the content of the overlay also has opacity.. i think its inheriting it... I don't really want to apply a new class to the content, is there a way to say only apply to
here is my css
```
.modal-overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #000000;
display: none;
}
```
and my jquery to create the model and content
```
var overlayLayer = $("<div id='office-location'></div>").addClass('modal-overlay'); //THIS HAS THE OVERLAY CLASS OF CSS - SO IT SHOULD HAVE A OPACITY SET AND IT DOES
$('body').append(overlayLayer);
$('<div id="content-for-overlay" style="background-color: white;"></div>').appendTo(overlayLayer); /// CONTENT IS ALSO HAS OPACITY BUT ITS WRONG
this.render({ to: "content-for-overlay", partial: "office-location-modal" });// THIS Sends a content from one file to my ID content-for-overlay... Its standard html
$("body").css("overflow", "hidden");
$('#office-location').css("opacity", 0.8).fadeIn(150);
$('#content-for-overlay').css("opacity", 1);
``` | The CSS "opacity" property is not being inherited, although it may seem so.
Since the content is *within* the overlay the opacity will, at best, be that of the parent (overlay). So, if the parent has an opacity of 0.5 then, visually, all its children can only ever achieve that opacity (no higher).
To avoid this, the elements must be separate in the HTML. I know it's a pain and I think CSS should really have some way of dealing with this but unfortunately it doesn't.
Another method which would work with nested elements is to forget about the opacity property and instead use a PNG image with alpha transparency and set that as the background to the overlay. | the following js which was written on jquery 1.3 :
```
$(document).ready(function() {
$(document.body).prepend('<div class="modalOverLay"></div>');
$('.modalOverLay').css({ opacity: 0.5, width: '100%', height: '100%' });
$('#trigger').click(function() {
$('.modalOverLay').fadeIn('slow');
$('.contentBox').css({
position: 'absolute',
left: ($(document).width() - $('.contentBox').width()) / 2,
top: ($(document).height() - $('.contentBox').height()) / 2
});
$('.contentBox').fadeIn(500);
});
});
```
and the following mark up :
```
<a href="#" id="trigger">Trigger Modal pop up</a>
<div class="contentBox">
<p>I am on overlay but don't have the same opacity</p>
</div>
```
this way your content will not have the same opacity as your modal overlay and seats nicely in the middle of what we all look at sometimes too much!! :) | Using jquery to create overlay but content inherits CSS opacity | [
"",
"javascript",
"jquery",
"css",
"opacity",
""
] |
I am drawing a string on a big bounding box and using StringFormat to align the string appropriately. However I need the actual (X, Y) location of the string once it's drawn (not just the size given by MeasureString).
I'm using the code below:
```
CharacterRange[] ranges = { new CharacterRange(0, this.Text.Length) };
format.SetMeasurableCharacterRanges(ranges);
//Measure character range
Region[] region = g.MeasureCharacterRanges(this.Text, this.Font, layoutRect, format);
RectangleF boundsF = region[0].GetBounds(g);
bounds = new Rectangle((int)boundsF.Left, (int)boundsF.Top,
(int)boundsF.Width, (int)boundsF.Height);
```
It's a code segment so ignore any missing declarations. The point is that rectangle the code above gives is not the right size, the last character of the string is dropped and only the first line of strings are drawn.
Anyone know why, or perhaps a better way to go about this?
Thanks | Make sure you're using the right format for measuring your text. You haven't included the entire source code, so I can't tell if you are.
There are two 'standard' format values you can use:
`StringFormat.GenericTypographic` and `StringFormat.GenericDefault`. If memory serves, the default one selected is typically `GenericDefault`, but the one you want when rendering UI is `GenericTypographic`.
Therefore, instead of doing `new StringFormat()`, you want to do `StringFormat.GenericTypographic.Clone()` instead. That should correct the margins/spacing and give you measurement results that match what you see rendered on the `Graphics` surface.
The strategy I typically use is to construct a single `StringFormat` instance and use it for both text rendering and measurement to ensure things line up - I avoid any method that lets me omit the `StringFormat` since the default probably isn't what I want.
Hope this helps. If you're still having trouble, try posting a more complete code snippet so we can see how you're painting your text. | Use:
```
TextBox tb = new TextBox { Text = "Test", Multiline = true };
Size size = System.Windows.Forms.TextRenderer.MeasureText(tb.Text, tb.Font);
Point location = new Point( //Is this what you were looking for?
tb.Location.X + size.Width,
tb.Location.Y + size.Height);
```
Note that there are additional overloads to this method, please check out. | Determining the Position of a String After it is Drawn using WinForms (C#) | [
"",
"c#",
"winforms",
""
] |
Based on an answer I got [here](https://stackoverflow.com/questions/938784/good-client-socket-pool), I started to give [commons-pool](http://commons.apache.org/pool/) a serious look. My last experience of using it was around 2003, probably version 1.1 or 1.2. Its main user, [DBCP](http://commons.apache.org/dbcp/), is considered by many as flawed and to be avoided.
Does anyone uses commons pool in production to write pool of your own? What is the best pool type to use? I plan to store **client** TCP sockets in it.
Is there another generic pool that replaces it? | > Does anyone uses commons pool in
> production to write pool of your own?
Yes, I do and the pool holds TCP connections, like you intend it to. It's wired up via Spring, so assuming you understand Spring configuration:
```
<bean class="com.company.ConnectionSupplier">
<constructor-arg>
<!-- The ConnectionSupplier wraps an object pool -->
<bean class="org.apache.commons.pool.impl.GenericObjectPool">
<constructor-arg>
<!-- The ObjectPool uses a ConnectionFactory to build new connections -->
<bean class="com.company.ConnectionFactory">
<constructor-arg value="server" />
<constructor-arg value="3000" />
</bean>
</constructor-arg>
<property name="maxActive" value="20" />
<property name="testOnBorrow" value="true" />
</bean>
</constructor-arg>
</bean>
```
The ConnectionFactory extends BasePoolableObjectFactory and is a small wrapper around a SocketFactory.
@First comment:
The ConnectionFactory constructor takes a server and a port. In the overriden makeObject(), it creates sockets that connect to that server and port. It returns 'Connection' objects that wrap the created socket with some convenience methods for communicating through the socket.
The connection is tested using a sort of 'ping' or 'echo' provided by the protocol used to communicate over the socket. Should that not have been available, validation/testing of the connection is not really possible, except for asking the socket whether it has been closed. In that case, a Connection in the pool would have been invalidated if it threw an exception and every method using Connections should be prepared for that kind of failure and attempt the same operation with another connection. | Have you looked into [Netty](http://jboss.org/netty) or [Apache MINA](http://mina.apache.org/)? They will both keep track of your TCP connections and should make implementing whatever communications protocol those TCP sockets will use easier as well. | Tips for using commons-pool in production | [
"",
"java",
"sockets",
"pool",
""
] |
> I asked this question a long time ago,
> I wish I had read the answers to
> [*When not to use Regex in C# (or
> Java, C++ etc)*](https://stackoverflow.com/questions/968919/when-not-to-use-regex) **first!**
I wish to use Regex (regular expressions) to get a list of all strings in my C# source code, including strings that have double quotes embedded in them.
This should not be hard, however before I spend time trying to build the Regex expression up, has anyone got a “pre canned” one already?
This is not as easy as it seems as first due to
* “av\”d”
* @”ab””cd”
* @”ab”””
* @”””ab”
* etc | I am posting this as my answer so it stands out to other reading the questions.
As has been pointed out in the helpful comments to my question, it is clear that regex is not a good tool for finding strings in C# code. I could have written a simple “parser” in the time I spent reminding my self of the regex syntax. – (Parser is a over statement as there are no “ in comments etc, it is my source code I am dealing with.)
This seems to sums it up well:
> [Some people, when confronted with a problem, think “I know, I'll use](http://regex.info/blog/2006-09-15/247)
> [regular expressions.” Now they have two problems.](http://regex.info/blog/2006-09-15/247)
However until it breaks on my code I will use the regular expression Blixt has posted, but if it give me problems I will not spend match time trying to fix it before writing my own parser. E.g as a C# string it is
```
@"@Q(?:[^Q]+|QQ)*Q|Q(?:[^Q\\]+|\\.)*Q".Replace('Q', '\"')
```
Update, the above regEx had problem, so I just wrote my own parser, including writing unit tests it took about 2 hours to write the parser. That's I lot less time then I spend just trying to find (and test) a pre-canned Regex on the web.
The problem I see to have, is I tend to avoid Regex and just write the string handling code my self, then have a lot of people claim I am wasting the client’s money by not using Regex. However whenever I try to use Regex what seems like a simple match pattern becomes match harder quickly. (None the on-line articles on using Regex in .net that I have read, have a good instruction that make it clear when NOT to use Regex. Likewise with it’s MSDN documentation)
Lets see if we can help solve this problem, I have just created a stack overflow questions “[When not to use Regex](https://stackoverflow.com/questions/968919/when-not-to-use-regex)” | The regular expression for finding C-style strings is:
```
"(?:[^"\\]+|\\.)*"
```
This will not take comments into consideration, so your best bet would be to remove all comments first, using the following regular expression:
```
/\*(?s:(?!\*/).)*\*/|//.*
```
Note that if you put the above regular expressions in a string you'll need to double all backslashes and escape any citation marks.
Update:
Changed regular expression for comments to use DOTALL flag for multi-line comments.
Also, you may want to support literal strings, so use this instead of the other string regex:
```
@"(?:[^"]+|"")*"|"(?:[^"\\]+|\\.)*"
```
And a reminder: Don't use DOTALL as a global flag for any of these regular expressions, as it would break the single-line comments and single-line strings (normal strings are single-line, while literal strings can span multiple lines.) | Regex to parse C# source code to find all strings | [
"",
"c#",
".net",
"regex",
""
] |
I am using prototype + jquery on a site. Now the prototype plugins use $. I do not want jQuery to use $. How do I make jQuery not register the $. Also, how do I then call jQuery functions.
Thank you for your time. | The jQuery [documentation](http://docs.jquery.com/Using_jQuery_with_Other_Libraries) has an article on how to make jQuery play nice with other libraries.
This is one suggested way from that article:
```
<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>
``` | 1. link jquery first and prototype second. this will override the $.
2. for jQuery, use the function `jQuery(...)`. | jQuery not register $ | [
"",
"javascript",
"jquery",
""
] |
While migrating a legacy application to spring security I got the following exception:
```
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainProxy': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainList': Cannot resolve reference to bean '_filterSecurityInterceptor' while setting bean property 'filters' with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterSecurityInterceptor': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Unsupported configuration attributes: [superadmin]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
```
In the old application there are roles like "superadmin", "editor", "helpdesk" etc. But in all Spring Security examples I only see roles like "ROLE\_" ("ROLE\_ADMIN" etc). When I rename "superadmin" to "ROLE\_ADMIN" and only use this role in the config, everything works.
Doesn't work:
```
<http auto-config="true">
<intercept-url pattern="/restricted/**" access="superadmin"/>
<form-login
authentication-failure-url="/secure/loginAdmin.do?error=true"
login-page="/secure/loginAdmin.do" />
</http>
```
Works:
```
<http auto-config="true">
<intercept-url pattern="/restricted/**" access="ROLE_ADMIN"/>
<form-login
authentication-failure-url="/secure/loginAdmin.do?error=true"
login-page="/secure/loginAdmin.do" />
</http>
```
Is possible to use custom role names? | You are using the default configuration which expects that roles starts with the `"ROLE_"` prefix. You will have to add a custom security configuration and set `rolePrefix` to "";
<http://forum.springsource.org/archive/index.php/t-53485.html> | Here is a complete configuration using access expressions (link provided by @rodrigoap seems a little bit outdated):
```
<http
access-decision-manager-ref="accessDecisionManager"
use-expressions="true">
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
<beans:bean class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value=""/>
</beans:bean>
<beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
</beans:list>
</beans:property>
</beans:bean>
``` | How do I use custom roles/authorities in Spring Security? | [
"",
"java",
"spring",
"spring-security",
""
] |
For the project that I'm currently on, I have to deliver specially formatted strings to a 3rd party service for processing. And so I'm building up the strings like so:
```
string someString = string.Format("{0}{1}{2}: Some message. Some percentage: {3}%", token1, token2, token3, number);
```
Rather then hardcode the string, I was thinking of moving it into the project resources:
```
string someString = string.Format(Properties.Resources.SomeString, token1, token2, token3, number);
```
The second option is in my opinion, not as readable as the first one i.e. the person reading the code would have to pull up the string resources to work out what the final result should look like.
How do I get around this? Is the hardcoded format string a necessary evil in this case? | I do think this is a necessary evil, one I've used frequently. Something smelly that I do, is:
```
// "{0}{1}{2}: Some message. Some percentage: {3}%"
string someString = string.Format(Properties.Resources.SomeString
,token1, token2, token3, number);
```
..at least until the code is stable enough that I might be embarrassed having that seen by others. | There are several reasons that you would want to do this, but the only great reason is if you are going to localize your application into another language.
If you are using resource strings there are a couple of things to keep in mind.
1. Include format strings whenever possible in the set of resource strings you want localized. This will allow the translator to reorder the position of the formatted items to make them fit better in the context of the translated text.
2. Avoid having strings in your format tokens that are in your language. It is better to use
these for numbers. For instance, the message:
"The value you specified must be between {0} and {1}"
is great if {0} and {1} are numbers like 5 and 10. If you are formatting in strings like "five" and "ten" this is going to make localization difficult.
3. You can get arround the readability problem you are talking about by simply naming your resources well.
string someString = string.Format(Properties.Resources.IntegerRangeError, minValue, maxValue );
4. Evaluate if you are generating user visible strings at the right abstraction level in your code. In general I tend to group all the user visible strings in the code closest to the user interface as possible. If some low level file I/O code needs to provide errors, it should be doing this with exceptions which you handle in you application and consistent error messages for. This will also consolidate all of your strings that require localization instead of having them peppered throughout your code. | Should we store format strings in resources? | [
"",
"c#",
"localization",
"resources",
"string-formatting",
""
] |
The directory 'C:\temp' has two files named 'GZ96A7005.tif' and 'GZ96A7005001.tif'. They have different length with the same extension. Now I run below code:
```
string[] resultFileNames = Directory.GetFiles(@"C:\temp", "????????????.tif");
```
The 'resultFileNames' return two items 'c:\temp\GZ96A7005.tif' and 'c:\temp\GZ96A7005001.tif'.
But the Window Search will work fine. This is why and how do I get I want?
 | I know I've read about this somewhere before, but the best I could find right now was this reference to it in [Raymond Chen's blog post](http://blogs.msdn.com/oldnewthing/archive/2007/12/17/6785519.aspx). The point is that Windows keeps a short (8.3) filename for every file with a long filename, for backward compatibility, and filename **wildcards are matched against both the long and short filenames**. You can see these short filenames by opening a command prompt and running "`dir /x`". Normally, getting a list of files which match `????????.tif` (8) returns a list of file with 8 or less characters in their filename and a .tif extension. But **every file with a long filename also has a short filename with 8.3 characters, so they all match this filter**.
In your case both `GZ96A7005.tif` and `GZ96A7005001.tif` are long filenames, so they both have a 8.3 short filename which matches `????????.tif` (anything with 8 or more `?`'s).
UPDATE... from [MSDN](http://msdn.microsoft.com/en-us/library/wz42302f.aspx):
> Because this method checks against
> file names with both the 8.3 file name
> format and the long file name format,
> a search pattern similar to "`*1*.txt`"
> may return unexpected file names. For
> example, using a search pattern of
> "`*1*.txt`" returns "`longfilename.txt`"
> because the equivalent 8.3 file name
> format is "`LONGFI~1.TXT`".
---
UPDATE: The MSDN docs specifiy different behavior for the "`?`" wildcard in Directory.GetFiles() and DirectoryInfo.GetFiles(). The documentation seems to be wrong, however. See [Matthew Flaschen's answer](https://stackoverflow.com/questions/963279/c-using-directory-getfiles-to-get-files-with-fixed-length/963289#963289). | For [Directory.GetFiles](http://msdn.microsoft.com/en-us/library/wz42302f.aspx), ? signifies "Exactly zero *or* one character." On the other hand, you could use [DirectoryInfo.GetFiles](http://msdn.microsoft.com/en-us/library/8he88b63.aspx), for which ? signifies "Exactly one character" (apparently what you want).
EDIT:
Full code:
```
string[] resultFileNames = (from fileInfo in new DirectoryInfo(@"C:\temp").GetFiles("????????????.tif") select fileInfo.Name).ToArray();
```
You can probably skip the ToArray and just let resultFileNames be an `IEnumerable<string>`.
People are reporting this doesn't work for them on MS .NET. The below exact code works for me with on Mono on Ubuntu Hardy. I agree it doesn't really *make sense* to have two related classes use different conventions. However, that is what the documentation (linked above) says, and Mono complies with the docs. If Microsoft's implementation doesn't, they have a bug:
```
using System;
using System.IO;
using System.Linq;
public class GetFiles
{
public static void Main()
{
string[] resultFileNames = (from fileInfo in new DirectoryInfo(@".").GetFiles("????????????.tif") select fileInfo.Name).ToArray();
foreach(string fileName in resultFileNames)
{
Console.WriteLine(fileName);
}
}
}
``` | C#: Using Directory.GetFiles to get files with fixed length | [
"",
"c#",
".net",
"windows",
"filenames",
"long-filenames",
""
] |
I'm a .net programmer vb & c#, but I can't seem to figure out how to get my objects into a list or array in PHP.
```
var mylist = new List<myobject>();
mylist.add(myobject1);
mylist.add(myobject2);
```
What I have tried.
Products being a property for a collection of `orderitems`:
```
$this->Products = getOrderItems();
public function getOrderItems()
{
$items = array();
$count = 0;
// connect to db, query.....
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$count++;
$items[$count] = ($row);
}
echo 'Count of Order Items...' . $count;
return $items;
}
```
Am I even close? | ```
$items = array();
while($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$items[] = $row;
}
echo 'Count of Order Items...', count($items);
``` | * `$this->Products = getOrderItems();` is legal in PHP, but it refers to the (global) function `getOrderItems()` instead of the class method. class methods and variables always have to be prefixed with `$this->` (or `self::`, if they're static vars) when called from inside the class.
in your sample-code, you have that wrong. getOrderItems is defined as class method, but your call is not `$this->`-scoped, thus php assumes a function. it should throw an `function not found`-error.
* the `[]` notation adds an element to the end of an array.
* the index of the first element in your sample code is 1 (isn't that the standard case for VB?). php normally starts at 0 - though it's possible (because php-arrays are not real arrays) to start at arbitrary indices i'd recommend to stick with zero.
* `mysql_fetch_array` is an *ancient* way of working with mysql. nowadays you're better of with mysqli or (even better) PDO.
* > (...) a list or array in php.
lists, arrays, stacks, whatever: in php everthing is an ordered map (misleadingly called array):
> [PHP: Arrays](http://www.php.net/manual/en/language.types.array.php): An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
**update:**
sorry, i haven't got enough time right now to explain the finer nuances of [pdo](http://www.php.net/pdo)/[mysqli](http://www.php.net/mysqli) over [mysql](http://www.php.net/mysql).
so here are just the basics:
* **oop:** pdo and mysqli are object oriented (tough mysqli got functional aliases)
* **prep statements:** most important: pdo/mysqli got prepared statements. that means, you first prepare the query with placeholders once, then fill in the values later (without the need to prepare the query a second time). this approach has 3 obvious advantages:
+ **performance:** it's faster, because the database only has to analyze, compile and optimize the query once *(at least with complex queries)*
+ **security:** no need for quoted strings (happens automatically!), making sql-injection attacks harder
+ **maintainability:** the logic and data part of the query are separated, thus easier to read and you don't have to do a lot of string concenation
* **driver driven:** pdo is not database specific. there are several supported db-systems, making it easier to port your code to other db-backends *(but it's not an db-abstraction layer like ODBC, so the SQL still has to be compatible)* and increasing reusability
of course, there's a lot more to it | How do I create a list or an array of objects in PHP? | [
"",
"php",
""
] |
I am putting together a simple simulated network in java, where i can add computers, servers, and connect two objects with ethernet ports. This is where the null pointer exception is being thrown, when i call "this.etherPort.addElement(t);"
```
import java.util.Vector;
public class Server extends Computer{
public Vector<Ethernet> etherPort;
public void addPort(Ethernet t)
{
this.etherPort.addElement(t);
}
}
```
This code is run when i make a new Ethernet object using this code:
```
public class Ethernet {
```
public Computer terminal1, terminal2;
public int volume;
public Ethernet(Computer term, Server term2)
{
this.terminal1 = term;
this.terminal2 = (Computer) term2;
if(term != null)
{
term.addPort(this);
}
if(term2 != null)
{
term2.addPort(this);
}
}
} | You need to instanciate your etherPort member :
```
public class Server extends Computer{
public Vector<Ethernet> etherPort = new Vector<Ethernet>();
public void addPort(Ethernet t)
{
this.etherPort.addElement(t);
}
}
```
You should make sure that addPort() is not overriding a method called from your Computer constructor, though. Given the context, I assume it's safe (*i.e.* Computer has no addPort() method).
As stated below in a comment, it's generally better to use interfaces that don't constrain the containers implementations : you'd better declare etherPort as a
```
List<Ethernet>
```
instead of a
```
Vector<Ethernet>
```
and use etherPort.add(element) instead of the Vector-specific addElement method. | You didn't initialize the vector. Should be:
```
public Vector<Ethernet> etherPort = new Vector<Ethernet>();
``` | help with null pointer exception in Java | [
"",
"java",
""
] |
I have an `onclick` event attached to a region in my page that causes a certain action to fire when the user clicks in it (naturally). I recently added an image to that region. When the user clicks on that image, I want another action to occur, and I do NOT want the action associated with the entire region to occur. However, I find that both events are, in fact fired when one clicks the image. How do I suppress the region-wide action when the image is clicked? | Darit is correct, you need to stop the event from bubbling (propagating):
```
function imgEventHandler(e) {
// ^notice: pass 'e' (W3C event)
// W3C:
e.stopPropagation();
// IE:
if (window.event) {
window.event.cancelBubble = true;
}
}
``` | The issue you are running into is known as event bubbling. The click event of the image bubbles up to all parent elements of that node. You want to cancel bubbling.
The best way to do this that works across all browsers is by using a JavaScript framework. [jQuery](http://jquery.com/) has a very simple way to do this. Other frameworks have similar mechanisms to cancel bubbling, I just happen to be most familiar with jQuery.
For example, you could do something like this in jQuery:
```
$('img').click(function () {
// Do some stuff
return false;// <- Cancels bubbling to parent elements.
});
``` | Multiple events firing from single action | [
"",
"javascript",
"dom-events",
""
] |
What specification supports optional parameters? | There are several ways to simulate optional parameters in Java:
1. **Method overloading.**
void foo(String a, Integer b) {
//...
}
void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
}
foo("a", 2);
foo("a");
One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.
1. **Varargs.**
a) All optional parameters are of the same type:
```
void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
```
b) Types of optional parameters may be different:
```
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
```
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.
1. **Nulls.** To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:
void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
//...
}
foo("a", null, 2);
Now all arguments values must be provided, but the default ones may be null.
1. **Optional class.** This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:
void foo(String a, Optional bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
//...
}
foo("a", Optional.of(2));
foo("a", Optional.absent());
Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.
Update: Java 8 includes the class `java.util.Optional` out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.
2. **Builder pattern.** The builder pattern is used for constructors and is implemented by introducing a separate Builder class:
```
class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
//...
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();
```
3. **Maps.** When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:
void foo(Map<String, Object> parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
}
a = (Integer)parameters.get("a");
}
if (parameters.containsKey("b")) {
//...
}
//...
}
foo(ImmutableMap.<String, Object>of(
"a", "a",
"b", 2,
"d", "value"));
In Java 9, this approach became easier:
```
@SuppressWarnings("unchecked")
static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {
return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
}
void foo(Map<String, Object> parameters) {
String a = getParm(parameters, "a", "");
int b = getParm(parameters, "b", 0);
// d = ...
}
foo(Map.of("a","a", "b",2, "d","value"));
```
Please note that you can combine any of these approaches to achieve a desirable result. | varargs could do that (in a way). Other than that, all variables in the declaration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter.
```
private boolean defaultOptionalFlagValue = true;
public void doSomething(boolean optionalFlag) {
...
}
public void doSomething() {
doSomething(defaultOptionalFlagValue);
}
``` | How do I use optional parameters in Java? | [
"",
"java",
"optional-parameters",
""
] |
I'm attempting to compile **Java 1.4** code that was created by **IBM's** **WSDL2Java** on **Java5** without recreating the stubs and saw this error in **Eclipse**.
I'm under the assumption that the stubs generated should just compile as long as the runtime `jars` are available (they are).
`Access restriction: The type QName is not accessible due to restriction on required library C:\Program Files\Java\jdk1.5.0_16\jre\lib\rt.jar`
The full class name is `javax.xml.namespace.QName`
> What exactly is going on here? Is this a case where I am trying to refactor a pig from sausage? Am I better off recreating the stubs? | There's another solution that also works.
1. Go to the *Build Path* settings in the project properties.
2. Remove the *JRE System Library*
3. Add it back; Select *"Add Library"* and select the *JRE System Library*. The default worked for me.
This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first.
If you want a fundamental solution make sure you exclude the jar files with the same classes.
For me I have: `javax.xml.soap.SOAPPart` in three different jars: `axis-saaj-1.4.jar`, `saaj-api-1.3.jar` and the `rt.jar` | <http://www.digizol.com/2008/09/eclipse-access-restriction-on-library.html> worked best for me.
**On Windows:** Windows -> Preferences -> Java -> Compiler -> Errors/Warnings
-> Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning
**On Mac OS X/Linux:** Eclipse -> Preferences -> Java -> Compiler -> Errors/Warnings
-> Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning | Access restriction on class due to restriction on required library rt.jar? | [
"",
"java",
"eclipse",
"wsdl",
"stub",
"wsdl2java",
""
] |
`Django` uses real Python files for settings, `Trac` uses a `.ini` file, and some other pieces of software uses XML files to hold this information.
Are one of these approaches blessed by Guido and/or the Python community more than another? | Depends on the predominant intended audience.
If it is programmers who change the file anyway, just use python files like settings.py
If it is end users then, think about ini files. | As many have said, there is no "offical" way. There are, however, many choices. There was [a talk at PyCon](http://pyvideo.org/video/190/pycon-2009--data-storage-in-python---an-overview0) this year about many of the available options. | What's the official way of storing settings for Python programs? | [
"",
"python",
"settings",
""
] |
In the MVC way of doing things, where is the best place to run, for example `htmlspecialchars()` on any input? Should it happen in the view (it sort of makes sense to do it here, as I should be dealing with the raw input throughout the controller and model?)
I'm not quite sure... What are benefits of doing it in the view or controller? This is just reguarding outputting to a page... to minimize potential XSS exploits. | Well, that depends, doesn't it? You should sanitize everything you OUTPUT in the view. First, because sanitization depends on the format of your output. A JSON sanitized output is different than an HTML sanitized output, right? Second, because you never want to trust the data you have. It might have been compromised through any number of ways.
That won't protect against SQL injections and such, though. Now, you never want to do that in a client-side javascript, because an attacker may easily replace that. Again, my advice is sanitization at the point of usage. If you are just writing to a file, it might not be needed. And some database access libraries do not needed it either. Others do.
At any rate, do it at the point of usage, and all the source code becomes more reliable against attacks and bugs (or attacks through bugs). | This is why thinking in design patterns sucks. What you should be asking is where is the most **efficient** place to do this? If the data is write-once/read-many then sanitising it every time it's output (on page view) is going to put unnecessary load on the server. Make your decision based on how the data will be used, where you can setup caching, how you do searches, etc.. not on the merits of a pattern.
From what you've said I'd perform the sanitation just ahead of writing it to the DB. Then you're not only ensuring the data is safe to insert but you're also ensuring that no future mistakes can result in unsanitised data being sent. If you ever want the original text for some reason you just invert your original transformation.
You should not be concerned about storing html encoded text in your DB since ALL text is encoded in one form or another. If you need to search the text you just encode the search string as well. If you need another format then that's another story but then you would have to evaluate your options based on your needs. | Where is the best place to sanitize user input that will be output on a webpage? | [
"",
"php",
"security",
"xss",
""
] |
I need to find a way to show the value of a custom attribute in place of the "Product Name" shown in the image below.
[](https://i.stack.imgur.com/qCdw4.gif)
(source: [magentocommerce.com](http://www.magentocommerce.com/images/uploads/grouped_prod_front.gif))
I'm working with /app/design/frontend/default/defaultx/template/catalog/product/view/type/grouped.php
The code below doesn't work(the custom attribute is yearmade):
```
<?php if (count($_associatedProducts)): ?>
<?php foreach ($_associatedProducts as $_item): ?>
<tr>
<td><?php echo $this->htmlEscape($_item->getYearmade()) ?></td>
```
Any help would be appreciated.
EDIT: So the answer turned out to be quite simple. You see what I failed to mention above was that there *was* indeed output... but that it was just a number (eg: 52). Turns out this was the ID for that custom attribute value (It was a Dropdown type of custom attribute).
So in summary
This works for custom attributes of type text:
```
echo $this->htmlEscape($_item->getYearmade())
```
But for all other types of custom attribute (I think), the following should be used:
```
echo $this->htmlEscape($_item->getAttributeText('yearmade'))
```
I would not have discovered this without the most excellent answer provided by Alan Storm, below. Thank you sir. | All Magento models have a "getData" method available, which will return an php-array of key/value pairs. Try this at the top of your grouped.phtml file (after $\_product is defined)
```
print('<pre>');print_r($_product->getData());print('</pre>');
```
You should see output that looks something like the following.
```
Array
(
[store_id] => 1
[entity_id] => 3437
[entity_type_id] => 4
[attribute_set_id] => 27
[type_id] => grouped
[sku] =>
[category_ids] =>
[created_at] => 2009-04-16 03:37:51
...
```
So, you can grab an array of properties and just pull the key out. You could also use Magento's convenience/magic getX and setX methods. On all Magento models, you can access any property in the data array by calling a method based on the camel case version of the name,
```
$created_at = $_product->getCreatedAt();
$_product->setCreatedAt($date);
```
So, whatever your custom attribute name is, you should be able to get at it using the above, and if you're not sure just print\_r or var\_dump the contents of the array returned by getData().
Finally, if the custom attribute is on one of the related products simple product, you'll wants something more like
```
$_associatedProducts[0]->getCreatedAt();
``` | I had the same problem.
1. You must locate grouped.phtml
`app/design/frontend/base/default/template/catalog/product/view/type/grouped.phtml`
2. Get the item, example
`$_item[units]`
3. Add a cell into the table and paste echo `$_item['units'];`
4. Thats all :) | Magento - Show Custom Attributes in Grouped Product table | [
"",
"php",
"magento",
"custom-attributes",
""
] |
I would really like to make maven write the "target" folder to a different device (ramdisk), which I would normally consider to be a different path. Is there any maven2-compliant way to do this ?
I am trying to solve this problem on windows, and a maven-compliant strategy would be preferred. | If you happen to have all of your projects extending a corporate parent pom, then you could try adding Yet Another Layer of Indirection as follows:
Corporate POM:
```
<build>
<directory>${my.build.directory}</directory>
</build>
<properties>
<!-- sensible default -->
<my.build.directory>target</my.build.directory>
</properties>
```
In your settings.xml:
```
<properties>
<!-- Personal overridden value, perhaps profile-specific -->
<my.build.directory>/mnt/other/device/${project.groupId}-${project.artifactId}/target</my.build.directory>
</properties>
```
If the local POM definition takes precedence over the settings.xml definition, then you could try omitting the default value at the cost of having every Maven instance in your control (developers, build machines, etc) specify ${my.build.directory} in its settings.xml. | Actually, Maven is not as *constrained* as everybody thinks, all the POMs are extended of one [Super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Super_POM) in which is defined the name of the target folder
```
<build>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory>
.
.
.
</build>
```
Of course you can overwrite with any value you want, so just go ahead and change the <directory /> element (and other related elements) in your POM | Can I move maven2 "target" folder to another device? | [
"",
"java",
"maven-2",
""
] |
I need to run a couple of relatively simple SQL update statements to update a single column in an Oracle table with 14.4 million rows. One statement runs a function written in Java and the JVM runs out of memory as I’m doing the update on all 14.4 million rows.
Have you written a kind of batch PL/SQL routine that can break this simple update into sets of, say, 10K records per batch? I know that if I can commit my updates after a bunch of records, it’ll go a lot faster and I won’t run out of memory. I’m sure there’s a simple way to do this using a `FOR loop` and `row_num` but I'm not making much progress.
Here are the two statements I need to run for each batch of *n* records:
first one:
```
update vr_location l set l.usps_address=(
select mylib.string_utils.remove_duplicate_whitespace(
house_number || ' ' || pre_street_direction || ' ' || street_name || ' ' ||
street_description || ' ' || post_street_direction)
from vr_address a where a.address_pk=l.address_pk);
```
second:
```
update vr_location set usps_address = mylib.usaddress_utils.parse_address(usps_address);
``` | Do an initial select to retrieve some kind of grouping attribute, so that you end up with groups that have the desired number of rows. Experiment with the grouping clause, for instance the last three digits of a zip-code or something semi random.
Loop over the grouping clause, using the clause as parameter to limit the rows targeted by each update statement. commit at the end of each iteration. | You (or your DBA) should size the UNDO properly and do this as a single SQL transaction
The advantages are:
* read consistency on table while this is happening
* you retain the ability to rollback the transaction in case something fails
If you're in some sort of loading environment where you don't care about either of these, then use CTAS (create table as select) to make a new table with the modified value, build the indexes, constraints, etc and then swap the table names. 14 million rows isn't that big these days. | Run Oracle update statements in a batch mode | [
"",
"sql",
"oracle",
"plsql",
""
] |
Im running a file host thats grown beyond the capacity of a single server, and I need to implement multiple server storage of files. I'd like to do this as cheap as possible, so those fancy mass storage methods are out of the question. I simply want to move a file thats uploaded by the user to the "gateway" server, which hosts all the http and mysql, to one of the media servers. It can either be done at the end of the user's request, or via cron every couple of minutes.
At this point the only method Im truly familiar with, is using ftp\_put php function, and simply ftping the file to a different server, but I've had problems with this method in the past, especially for larger files, and a lot of the files that will be getting transferred will be over 100mb.
Can anyone suggest a good solution for this? Preferably Im looking for a purely software solution... hopefully nothing more than a php/bash script. | One method that requires no programmatic setup, and is quite secure is to mount a folder from the other server, and use php to save to that directory like you would normally.
You don't have to use sshfs, there are a bunch of other ways to provide the same solution. I would use sshfs for this situation as it works across ssh, and therefore is secure and relatively easy to setup.
To achieve this (using sshfs):
1. Install [sshfs](http://fuse.sourceforge.net/sshfs.html)
2. Mount a ssfs file to a folder accessable to php
3. Use a php script to store the files within the sshfs mount, and therefore on the other server.
Another method is to setup an [rsync](http://www.samba.org/rsync/) command between the two using crontab. | you can write a bash script that run in cron
and use command line like scp or sftp or rsync
example :
```
[bash]# scp filename alice@galaxy.example.com:/home/alice
```
Copy "filename" into alice's home directory on the remote galaxy.example.com server | Whats the best way to transport a file to a different server? | [
"",
"php",
"scaling",
""
] |
The `java.util.Properties` class is meant to represent a map where the keys and values are both Strings. This is because `Properties` objects are used to read `.properties` files, which are text files.
So, why in Java 5 did they retrofit this class to implement `Map<Object,Object>` and not `Map<String,String>`?
The [javadoc](http://java.sun.com/j2se/1.5.0/docs/api/) states:
> Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail.
Since the keys and values are both supposed to be Strings then why not enforce that statically by using the proper generic type?
I guess making `Properties` implement `Map<String,String>` would not be fully backward compatible with code written for pre-Java 5. If you have older code that sticks non-strings into a Properties object then that code would no longer compile with Java 5. But... isn't that a good thing? Isn't the whole point of generics to catch such type errors at compile time? | Because they did it in a hurry in the early days of Java, and didn't realise what the implications would be four versions later.
Generics were supposed to be part of the design of Java from the beginning, but the feature was dropped as being too complicated and, at the time, unnecessary. As a result, lots of code in the standard libraries is written with the assumption of non-generic collections. It took the prototype language "Pizza" from Martin Odersky to show how they could be done fairly well while maintaining near perfect backwards compatibility, with both Java code and bytecode. The prototype led to Java 5, in which the collections classes were retrofitted with generics in a way that allowed old code to keep working.
Unfortunately, if they were to retroactively make `Properties` inherit from `Map<String, String>`, then the following previously valid code would stop working:
```
Map<Object, Object> x = new Properties()
x.put("flag", true)
```
Why anybody would do that is beyond me, but Sun's commitment to backwards compatibility in Java has gone beyond heroic into the pointless.
What's now appreciated by most educated observers is that `Properties` should never have inherited from `Map` at all. It should instead wrap around `Map`, exposing only those features of Map that make sense.
Since reinventing Java, Martin Odersky has gone on to create the new Scala language, which is cleaner, inherits fewer mistakes, and breaks new ground in a number of areas. If you're finding Java's niggles annoying, take a look at it. | It was originally intended that `Properties` would indeed extends `Hashtable<String,String>`. Unfortunately the implementation of bridge methods caused a problem. `Properties` defined in such a way causes javac to generate synthetic methods. `Properties` should define, say, a `get` method that returns a `String` but needs to override a method that returns `Object`. So a synthetic bridge method is added.
Suppose you had a class written in the bad old 1.4 days. You've overridden some methods in `Properties`. But what you haven't done is overridden the new methods. This leads to unintended behaviour. To avoid these bridge methods, `Properties` extends `Hashtable<Object,Object>`. Similarly `Iterable` does not return a (read-only) `SimpleIterable`, because that would have added methods to `Collection` implementations. | Why does java.util.Properties implement Map<Object,Object> and not Map<String,String> | [
"",
"java",
"generics",
"collections",
""
] |
Has anyone tried mixing `JavaFX` and `JRuby`? I've built a JRuby desktop application with a Swing GUI (100% JRuby) and I'm toying with the idea of replacing the GUI with JavaFX for a more slick feel.
To fit with my current application, I want to implement an MVC pattern with the View being JavaFX and the Controller and Model being Ruby. | As far as conceptual differences between JavaFX Script,and J Ruby, there are quite a few. I'll start with JRuby. JRuby is not
actually a language, per se. It is instead an implementation *in Java*
of the Ruby programming language. The original runtime interpreter for
Ruby was written in C (and perhaps some in C++, I'm not sure). The
JRuby project was started by some guys who wanted a runtime
implementation of Ruby that was written in Java instead.
Why? Well, there are some interesting advantages. First of all, they
were able to make it very easy to invoke Java code from a Ruby
application. Secondly, it means that Ruby programs end up being run by
the Java Virtual Machine (JVM) and therefore can benefit from all the
optimization work that has been done on JVMs over the last ten years.
Today JRuby functions as an interpreter only, but from what I heard from
one of the project leads earlier this month, they are very close to
being able to compile Ruby programs directly into JVM bytecode, which
would provide another performance boost.
In the end, JRuby is very interesting for projects that are written in
Ruby but that want to leverage either: existing Java libraries or
existing Java runtimes (the JVM and even application/web servers like
GlassFish and Tomcat) or both.
JavaFX on the other hand is scripting language which is directly injected for creating graphics kind of stuff.Very pragmatic too.So coming to usage when you are following a design pattern in this case MVC if you are following the rules it should be fine.But trust there
might be very few cases which may started using FX with JRuby. | There is now a [JRubyFX](https://github.com/jruby/jrubyfx) gem from the JRuby project for working with JavaFX 2.0. It supports both JavaFX in code and FXML. Most things should work, but it has a few issues that are documented in the Readme. | Anyone Tried Mixing JavaFX and JRuby? | [
"",
"java",
"swing",
"jruby",
"javafx",
""
] |
In benchmarking some Java code on a Solaris SPARC box, I noticed that the first time I call the benchmarked function it runs EXTREMELY slowly (10x difference):
* First | 1 | 25295.979 ms
* Second | 1 | 2256.990 ms
* Third | 1 | 2250.575 ms
Why is this? I suspect the JIT compiler, is there any way to verify this?
**Edit:** In light of some answers I wanted to clarify that this code is the simplest
possible test-case I could find exhibiting this behavior. So my goal isn't to get
it to run fast, but to understand what's going on so I can avoid it in my real
benchmarks.
**Solved:** Tom Hawtin correctly pointed out that my "SLOW" time was actually reasonable.
Following this observation, I attached a debugger to the Java process. During the first, the inner loop looks like this:
```
0xf9037218: cmp %l0, 100
0xf903721c: bge,pn %icc,0xf90371f4 ! 0xf90371f4
0xf9037220: nop
0xf9037224: ld [%l3 + 92], %l2
0xf9037228: ld [%l2 + 8], %l6
0xf903722c: add %l6, 1, %l5
0xf9037230: st %l5, [%l2 + 8]
0xf9037234: inc %l0
0xf9037238: ld [%l1], %g0
0xf903723c: ba,pt %icc,0xf9037218 ! 0xf9037218
```
On the following iterations, the loop looks like this:
```
0xf90377d4: sub %l2, %l0, %l3
0xf90377d8: add %l3, %l0, %l2
0xf90377dc: add %l2, 1, %l4
0xf90377e0: inc %l0
0xf90377e4: cmp %l0, 100
0xf90377e8: bl,pn %icc,0xf90377d8 ! 0xf90377d8
```
So HotSpot removed memory accesses from the inner loop, speeding it up by an order of magnitude.
**Lesson:** Do the math! I should have done Tom's calculation myself.
Benchmark Java code:
```
private int counter;
private int nThreads;
private void measure(String tag) throws Exception {
MyThread threads[] = new MyThread[nThreads];
int i;
counter = 0;
for (i = 0; i < nThreads; i++)
threads[i] = new MyThread();
long start = System.nanoTime();
for (i = 0; i < nThreads; i++)
threads[i].start();
for (i = 0; i < nThreads; i++)
threads[i].join();
if (tag != null)
System.out.format("%-20s | %-2d | %.3f ms \n", tag, nThreads,
new Double((System.nanoTime() - start) / 1000000.0));
}
public MyBench() {
try {
this.nThreads = 1;
measure("First");
measure("Second");
measure("Third");
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
private class MyThread extends Thread {
public void run() {
while (counter < 10000000) {
// work
for (int j = 0; j < 100; j++)
counter++;
counter -= 99;
}
}
}
``` | Some ugly, unrealistic code (the stuff of microbenchmarks):
```
while (counter < 10000000) {
// work
for (int j = 0; j < 100; j++)
counter++;
counter -= 99;
}
```
So what is this doing and how fast should it run.
The inner loop increments counter 100 times, then the counter is decremented by 99. So an increment of 1. Note counter is a member variable of an outer class, so some overhead there. This is then run 10,000,000 times. So the inner loop is run 1,000,000,000 times.
A loop using to accessor methods, call it 25 cycles. 1,000,000,000 times at 1 GHz, gives 25s.
Hey, we predicted the **SLOW** time. The slow time is fast. The fast times are after the benchmark has been broken in some way - 2.5 cycles an iteration? Use -server and you might find it gets even more silly. | Probably it's class loading or dynamic linking of native methods. If you run Java with the following JVM parameters (see [here](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) for full list), it will print information about what is taking the time:
`-verbose:class -verbose:jni -verbose:gc -XX:+PrintCompilation`
To find out exactly where each of the measure() calls start and end, add initializations of some new classes between those methods as markers, so that `-verbose:class` will show at what point in the logs the marker class is loaded. See [this answer](https://stackoverflow.com/questions/804620/java-why-do-two-consecutive-calls-to-the-same-method-yield-different-times-for-e/804743#804743) for a similar measurement.
To find out exactly what your code does, I modified it like this:
```
public MyBench() {
try {
this.nThreads = 1;
new Mark1();
measure("First");
new Mark2();
measure("Second");
new Mark3();
measure("Third");
new Mark4();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
private static class Mark1 {
}
private static class Mark2 {
}
private static class Mark3 {
}
private static class Mark4 {
}
```
Then by looking at when the JVM loaded those Mark1 etc. classes, here are the results.
During the first call to measure(), a total of 85 classes were loaded, 11 native methods were dynamically linked and 5 methods were JIT compiled:
```
[Loaded MyBench$Mark1 from file:/D:/DEVEL/Test/classes/]
[Loaded java.net.InetSocketAddress from shared objects file]
[Loaded java.net.InetAddress from shared objects file]
[Loaded MyBench$MyThread from file:/D:/DEVEL/Test/classes/]
[Loaded sun.security.action.GetBooleanAction from shared objects file]
[Dynamic-linking native method java.net.InetAddress.init ... JNI]
[Loaded java.net.InetAddress$Cache from shared objects file]
[Loaded java.lang.Enum from shared objects file]
[Loaded java.net.InetAddress$Cache$Type from shared objects file]
[Loaded java.net.InetAddressImplFactory from shared objects file]
[Dynamic-linking native method java.net.InetAddressImplFactory.isIPv6Supported ... JNI]
22 MyBench::access$508 (12 bytes)
[Loaded java.net.InetAddressImpl from shared objects file]
[Loaded java.net.Inet4AddressImpl from shared objects file 1% MyBench$MyThread::run @ 14 (48 bytes)
]
[Loaded sun.net.spi.nameservice.NameService from shared objects file]
[Loaded java.net.InetAddress$1 from shared objects file]
[Loaded java.net.Inet4Address from shared objects file]
[Dynamic-linking native method java.net.Inet4Address.init ... JNI]
[Dynamic-linking native method java.net.PlainSocketImpl.socketCreate ... JNI]
[Dynamic-linking native method java.net.PlainSocketImpl.socketBind ... JNI]
[Dynamic-linking native method java.net.PlainSocketImpl.socketListen ... JNI]
[Loaded java.net.Socket from shared objects file]
[Dynamic-linking native method java.net.PlainSocketImpl.socketAccept ... JNI]
[Loaded java.lang.Integer$IntegerCache from shared objects file]
[Loaded java.util.Formatter from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.regex.Pattern$6 from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.text.DecimalFormatSymbols from shared objects file]
[Loaded java.util.spi.LocaleServiceProvider from shared objects file]
[Loaded java.text.spi.DecimalFormatSymbolsProvider from shared objects file]
[Loaded sun.util.LocaleServiceProviderPool from shared objects file]
[Loaded java.util.LinkedHashSet from shared objects file]
[Loaded sun.util.LocaleServiceProviderPool$1 from shared objects file]
[Loaded java.util.ServiceLoader from shared objects file]
[Loaded java.util.ServiceLoader$LazyIterator from shared objects file]
[Loaded java.util.ServiceLoader$1 from shared objects file]
[Loaded java.util.HashMap$EntrySet from shared objects file]
[Loaded java.util.LinkedHashMap$LinkedHashIterator from shared objects file]
[Loaded java.util.LinkedHashMap$EntryIterator from shared objects file]
[Loaded sun.misc.Launcher$1 from shared objects file]
23 ! java.io.BufferedReader::readLine (304 bytes)
[Loaded sun.misc.Launcher$2 from shared objects file]
[Loaded sun.misc.URLClassPath$2 from shared objects file]
[Loaded java.lang.ClassLoader$2 from shared objects file]
[Loaded sun.misc.URLClassPath$1 from shared objects file]
[Loaded java.net.URLClassLoader$3 from shared objects file]
[Loaded sun.misc.CompoundEnumeration from shared objects file]
24 sun.nio.cs.UTF_8$Decoder::decodeArrayLoop (553 bytes)
[Loaded java.io.FileNotFoundException from shared objects file]
[Loaded java.net.URLClassLoader$3$1 from shared objects file]
[Dynamic-linking native method java.security.AccessController.doPrivileged ... JNI]
[Loaded sun.util.resources.LocaleData from shared objects file]
[Loaded sun.util.resources.LocaleData$1 from shared objects file]
[Loaded java.util.ResourceBundle$Control from shared objects file]
[Loaded sun.util.resources.LocaleData$LocaleDataResourceBundleControl from shared objects file]
[Loaded java.util.Arrays$ArrayList from shared objects file]
[Loaded java.util.Collections$UnmodifiableCollection from shared objects file]
25 java.lang.String::startsWith (78 bytes)
[Loaded java.util.Collections$UnmodifiableList from shared objects file]
[Loaded java.util.Collections$UnmodifiableRandomAccessList from shared objects file]
[Loaded java.util.ResourceBundle from shared objects file]
[Loaded java.util.ResourceBundle$1 from shared objects file]
[Dynamic-linking native method java.util.ResourceBundle.getClassContext ... JNI]
[Loaded java.util.ResourceBundle$RBClassLoader from shared objects file]
[Loaded java.util.ResourceBundle$RBClassLoader$1 from shared objects file]
[Loaded java.util.ResourceBundle$CacheKey from shared objects file]
[Loaded java.util.ResourceBundle$CacheKeyReference from shared objects file]
[Loaded java.util.ResourceBundle$LoaderReference from shared objects file]
[Loaded java.util.ResourceBundle$SingleFormatControl from shared objects file]
[Loaded sun.util.LocaleDataMetaInfo from shared objects file]
[Loaded java.util.AbstractList$Itr from shared objects file]
[Loaded java.util.ListResourceBundle from shared objects file]
[Loaded sun.text.resources.FormatData from shared objects file]
[Dynamic-linking native method java.lang.Class.isAssignableFrom ... JNI]
[Loaded java.util.ResourceBundle$BundleReference from shared objects file]
[Loaded sun.text.resources.FormatData_fi from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded sun.text.resources.FormatData_fi_FI from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Currency from shared objects file]
[Loaded java.util.Currency$1 from shared objects file]
[Loaded java.util.CurrencyData from shared objects file]
[Loaded sun.reflect.UnsafeFieldAccessorFactory from shared objects file]
[Loaded sun.reflect.UnsafeQualifiedStaticFieldAccessorImpl from shared objects file]
[Loaded sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl from shared objects file]
[Loaded java.util.spi.CurrencyNameProvider from shared objects file]
[Loaded sun.util.resources.OpenListResourceBundle from shared objects file]
[Loaded sun.util.resources.LocaleNamesBundle from shared objects file]
[Loaded sun.util.resources.CurrencyNames from shared objects file]
[Loaded sun.util.resources.CurrencyNames_fi_FI from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.regex.MatchResult from shared objects file]
[Loaded java.util.regex.Matcher from shared objects file]
[Loaded java.util.regex.ASCII from shared objects file]
[Loaded java.util.Formatter$FormatString from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Formatter$FormatSpecifier from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Formatter$Flags from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Formatter$Conversion from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Formatter$FixedString from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded java.util.Formattable from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Dynamic-linking native method java.io.FileOutputStream.writeBytes ... JNI]
First | 1 | [Loaded sun.misc.FormattedFloatingDecimal from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded sun.misc.FormattedFloatingDecimal$1 from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded sun.misc.FormattedFloatingDecimal$Form from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
[Loaded sun.misc.FormattedFloatingDecimal$2 from C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar]
2072,825 ms
```
During the second call, only one method was JIT compiled:
```
[Loaded MyBench$Mark2 from file:/D:/DEVEL/Test/classes/]
26 MyBench$MyThread::run (48 bytes)
Second | 1 | 2058,669 ms
```
During the third call, there was no additional work happening:
```
[Loaded MyBench$Mark3 from file:/D:/DEVEL/Test/classes/]
Third | 1 | 2093,659 ms
```
This was run on Windows with jdk1.6.0\_11, so your system might do things a little bit differently. For example, maybe one of those linkings of dynamic methods is exceptionally slow on your system. Or then all of the class loading is slower. Try to have a look at the logs, whether there is an unusually long pause, or whether all of those operations are equally slow. | First time a Java loop is run SLOW, why? [Sun HotSpot 1.5, sparc] | [
"",
"java",
"performance",
"jvm-hotspot",
"microbenchmark",
""
] |
We developed a handheld system (WM5) deployed to 800 Engineer about a year ago. Currently the handheld polls a public web-service every 5 min's to check for new jobs, we are wanting to change this and use push technology so when there's a now job its pushed directly to the handheld bit like exchange email.
Could you please advice how this can be achieved, also if you have any tip would be a big help. | [Comet](http://en.wikipedia.org/wiki/Comet_(programming)) is the umbrella term for different HTTP push methods. Basically, Exchange uses [Long Polling](http://en.wikipedia.org/wiki/Push_technology#Long_polling) which is a way of maintaining a long lived HTTP connection so that the server can send data as it's received instead of queuing for the next poll.
When the connection times out or is closed, the client immediately reconnects. So, the overall flow looks something like:
1. Client connects
2. Client asks for notifications for the next 10 mins
3. If no notification in 10 mins, server sends HTTP 200 OK and closes the connection
4. Back to 1
Exchange, of course, is [a little bit smarter](http://technet.microsoft.com/en-us/library/aa997252.aspx) in that it tries to dynamically adjust the timeout values to compensate for different network conditions that may reset the connection sooner. If the client wakes up after 10 mins and sees that the server never responded or the connection is broken, it'll use a smaller timeout the next time. | You could use the store and forward [WCF Exchange transport](http://msdn.microsoft.com/en-us/library/bb397812.aspx). This would leverage the email subsystem already in place for transport and get you a check-in rate of whatever you have your Exchange server set for. | Push Data to Handhelds | [
"",
"c#",
".net",
"windows-mobile",
""
] |
> **Possible Duplicate:**
> [C++ overload resolution](https://stackoverflow.com/questions/72010/c-overload-resolution)
I ran into a problem where after my class overrode a function of its base class, all of the overloaded versions of the functions were then hidden. Is this by design or am I just doing something wrong?
Ex.
```
class foo
{
public:
foo(void);
~foo(void);
virtual void a(int);
virtual void a(double);
};
class bar : public foo
{
public:
bar(void);
~bar(void);
void a(int);
};
```
the following would then give a compile error saying there is no a(double) function in bar.
```
main()
{
double i = 0.0;
bar b;
b.a(i);
}
``` | In class bar, add
```
using foo::a;
```
This is a common 'gotcha' in C++. Once a name match is found in the a class scope, it doesn't look further up the inheritance tree for overloads. By specifying the 'using' declaration, you bring all of the overloads of 'a' from 'foo' into the scope of 'bar'. Then overloading works properly.
Keep in mind that if there is existing code using the 'foo' class, its meaning could be changed by the additional overloads. Or the additional overloads could introduce ambiguity and and the code will fail to compile. This is pointed out in James Hopkin's answer. | That is the way the language used to work. Prior to the *using* keyword, if you overrode one overloaded function, you had to overload them all:
```
class bar : public foo
{
public:
bar(void);
~bar(void);
a(int);
a(double d) { foo::a(d); } // add this
}
```
This annoyed enough people that the language committee added the *using* feature, but some old habits die hard; and the habitués† have a good argument.
As James Hopkins points out, by adding *using*, the programmer is expressing the intention that the derived class will, without warning, add any future overrides of foo::a() to its list of acceptable signatures.
Here is an example of what he describes:
```
#include <iostream>
class Base {
public:
virtual void f(double){ std::cout << "Base::Double!" << std::endl; }
// virtual void f(int) { std::cout << "Base::Int!" << std::endl; } // (1)
virtual ~Base() {}
};
class Derived : public Base {
public:
// using Base::f; // (2)
void f(double) { std::cout << "Derived::Double!" << std::endl; }
};
int main(int, char **) {
Derived d;
d.f(21);
return 0;
}
```
The output will be "Derived::Double!" because the compiler will promote the integer argument to a double. g++ 4.0.1 -Wall will not warn that this promotion occurred.
Uncomment (1) to simulate a future change to Base adding the method Base::f(int). The code compiles, again without warning even with -Wall, and "Derived::Double!" remains the output.
Now uncomment (2) to simulate a decision by the Derived programmer to include all Base::f signatures. The code compiles (without warnings), but the output is now "Base::Int!".
—
† I cannot think of an English word for "those who have the habit" and "addicted" is much too strong. | Overriding a Base's Overloaded Function in C++ | [
"",
"c++",
"inheritance",
"polymorphism",
"overriding",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.