Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I'm trying to run a freshly created ASP.NET Website using C#, however when I do so it launches FireFox and attempts to connect to <http://localhost:1295/WebSite1/Default.aspx> (for example), but after about 10-15 seconds it displays a "Connection Interrupted - The connection to the server was reset while the page was loading." Error.
This issue is also present with older ASP.NET C# pages/Web Services I've built in the past, nothing is actually running off the ASP.NET Development server.
I am using: Windows XP Pro SP2, Visual Studio 2008
For reference I have SQL Server 2005 Developer Edition installed as well.
I have tried:
* Browsing it with IE instead of Mozilla
* Trying 2.0 framework instead of 3.5
* Reinstalling Visual Studio 2008
This problem seems so trivial the more I think about it, but I havn't been able to work it out just yet! Appreciate any help on the matter.
|
When you launch the application, a little info mark appears at the right bottom of your screen telling you that the local web server was started and on wich port. You should compare that port to the one that appears in your browser. If they are different, an anti-virus could be responsible for that problem.
Another place to look is your [host](http://en.wikipedia.org/wiki/Hosts_file) file. Some software tweak this file and can make your localhost disbehave.
|
I had the same problem, and when I was about to quit and run away and join a monastry I had an idea to check ELMAH - maybe it had caught it...
Sure enough, ELMAH told me it had caught this:
```
System.Web.HttpException (0x80004005): Maximum request length exceeded.
```
and this fixed it:
```
<system.web>
<httpRuntime maxRequestLength="65535" />
</system.web>
```
Good luck,
Dave
|
What could cause "Connection Interrupted" on LocalHost when debugging in ASP.NET
|
[
"",
"c#",
"asp.net",
"localhost",
""
] |
I have a list of articles, and each article belongs to a section.
```
class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
```
I want to display the articles, grouped by section.
```
Sponsorships, Advertising & Marketing
1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams
2. Phil Jackson Questions Harrah's Signage At New Orleans Arena
3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account
4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider
5. Marketplace Roundup
Sports Media
6. Many Patriots Fans In New England Will Not See Tonight's Game
7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation
8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09
9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic
10. Media Notes
Leagues & Governing Bodies
11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team
12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed
13. Average Ticket Price For NFL Playoff Games To Drop By 10%
```
I figured out how to do most of it with Django's template system.
```
{% regroup articles by section as articles_by_section %}
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
<ul>
{% for item in article.list %}
<li>{{ forloop.counter }}. {{ item.headline }}</li>
{% endfor %}
</ul>
{% endfor %}
```
I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?
|
Following Jeb's suggeston in a comment, I created a [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags).
I replaced `{{ forloop.counter }}` with `{% counter %}`, a tag that simply prints how many times it's been called.
Here's the code for my counter tag.
```
class CounterNode(template.Node):
def __init__(self):
self.count = 0
def render(self, context):
self.count += 1
return self.count
@register.tag
def counter(parser, token):
return CounterNode()
```
|
This isn't exactly neat, but may be appropriate for someone:
```
{% for article in articles %}
{% ifchanged article.section %}
{% if not forloop.first %}</ul>{% endif %}
<h4>{{article.section}}</h4>
<ul>
{% endifchanged %}
<li>{{forloop.counter}}. {{ article.headline }}</li>
{% if forloop.last %}</ul>{% endif %}
{% endfor %}
```
|
Django Template System: How do I solve this looping / grouping / counting?
|
[
"",
"python",
"django",
"django-templates",
""
] |
I'd like to send mail without bothering with the SMTP-Server which is used for delivery.
So [JavaMail API](http://java.sun.com/products/javamail/) doesn't work for me because I have to specify a SMTP server to connect to.
I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.
I'm looking for something like [Aspirin](https://aspirin.dev.java.net/). Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.
An embeddable version of [James](http://james.apache.org/) would do the task. But I haven't found documentation concerning whether this is possible.
Or does anyone know about other libraries I could use?
|
This is completely the wrong way to handle this.
Anyone connected to the internet will have some kind of "legit" SMTP server available to them to take the submission of email -- your ISP, your office, etc.
You WANT to leverage because they do several things for you.
1) they take your message and the responsibility to handle that message. After you drop it off, it's not your problem anymore.
2) Any mail de-spamming technologies are handled by the server. Even better, when/if those technologies change (Domain keys anyone?), the server handles it, not your code.
3) You, as a client of that sending mail system, already have whatever credentials you need to talk to that server. Main SMTP servers are locked down via authentication, IP range, etc.
4) You're not reinventing the wheel. Leverage the infrastructure you have. Are you writing an application or a mail server? Setting up mail server is an every day task that is typically simple to do. All of those casual "dumb" users on the internet have managed to get email set up.
|
One possible solution: get the MX record on your own and use [JavaMail API](http://java.sun.com/products/javamail/).
You can get the MX record using the [dnsjava](http://www.dnsjava.org/) project:
Maven2 dependency:
```
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.0.1</version>
</dependency>
```
Method for MX record retrieval:
```
public static String getMXRecordsForEmailAddress(String eMailAddress) {
String returnValue = null;
try {
String hostName = getHostNameFromEmailAddress(eMailAddress);
Record[] records = new Lookup(hostName, Type.MX).run();
if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }
if (log.isTraceEnabled()) {
// log found entries for debugging purposes
for (int i = 0; i < records.length; i++) {
MXRecord mx = (MXRecord) records[i];
String targetString = mx.getTarget().toString();
log.trace("MX-Record for '" + hostName + "':" + targetString);
}
}
// return first entry (not the best solution)
if (records.length > 0) {
MXRecord mx = (MXRecord) records[0];
returnValue = mx.getTarget().toString();
}
} catch (TextParseException e) {
throw new RuntimeException(e);
}
if (log.isTraceEnabled()) {
log.trace("Using: " + returnValue);
}
return returnValue;
}
private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
String parts[] = mailAddress.split("@");
if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
return parts[1];
}
```
Sending mail via JavaMail code:
```
public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
String smtpServer = getMXRecordsForEmailAddress(toAddress);
// create session
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props);
// create message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddress));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
msg.setSubject(subject);
msg.setText(body);
// send message
Transport.send(msg);
}
```
|
Someone knows a mail (SMTP) delivery library for Java?
|
[
"",
"java",
"smtp",
"email",
"james",
""
] |
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes `devenv` without the necessary context.
```
os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
```
think of it as in i'm in bash, and i need to execute a command in a perl context, so i type `perl -c 'asdf'`. executing perl and asdf back to back won't work, i need to get the `devenv` inside of the perl context.
|
I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.
```
compileit.cmd
call C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
devenv $1.sln /rebuild Debug /Out last-build.txt
```
|
I think that the proper way for achieving this would be running this command:
```
%comspec% /C "%VCINSTALLDIR%\vcvarsall.bat" x86 && vcbuild "project.sln"
```
Below you'll see the Python version of the same command:
```
os.system('%comspec% /C "%VCINSTALLDIR%\\vcvarsall.bat" x86 && vcbuild "project.sln"')
```
This should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.
There is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0]
"InstallDir"="c:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\"
```
Add `..\..\VC\vcvarsall.bat` to this path. Also is a good idea to test for other versions of Visual Studio.
|
launching vs2008 build from python
|
[
"",
"python",
"windows",
"visual-studio-2008",
"build-automation",
""
] |
I would like to know if it is possible, to select certain columns from one table, and another column from a second table, which would relate to a non imported column in the first table. I have to obtain this data from access, and do not know if this is possible with Access, or SQL in general.
|
Assuming the following table structure:
```
CREATE TABLE tbl_1 (
pk_1 int,
field_1 varchar(25),
field_2 varchar(25)
);
CREATE TABLE tbl_2 (
pk_2 int,
fk_1 int,
field_3 varchar(25),
field_4 varchar(25)
);
```
You could use the following:
```
SELECT t1.field_1, t2.field_3
FROM tbl_1 t1
INNER JOIN tbl_2 t2 ON t1.pk_1 = t2.fk_1
WHERE t2.field_3 = "Some String"
```
In regard to Bill's post, there are two ways to create JOIN's within SQL queries:
* Implicit - The join is created using
the WHERE clause of the query with multiple tables being specified in the FROM clause
* Explicit - The join is created using
the appropriate type of JOIN clause
(INNER, LEFT, RIGHT, FULL)
It is always recommended that you use the explicit JOIN syntax as implicit joins can present problems once the query becomes more complex.
For example, if you later add an explicit join to a query that already uses an implicit join with multiple tables referenced in the FROM clause, the first table referenced in the FROM clause will not be visible to the explicitly joined table.
|
What you are looking for are JOINs:
<http://en.wikipedia.org/wiki/Join_(SQL)>
You need primary keys for the referenced data sets and foreign keys in the first table.
|
SQL statement from two tables
|
[
"",
"sql",
"ms-access",
""
] |
.NET 3.5, C#
I have a web app with a "search" feature. Some of the fields that are searchable are first-class columns in the table, but some of them are in fact nested fields inside an XML data type.
Previously, I built a system for dynamically constructing the SQL for my search. I had a nice class hierarchy that built SQL expressions and conditional statements. The only problem was it was not safe from SQL injection attacks.
I was reading [Rob Conery's excellent article](http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/) which pointed out that multiple queries can combined into a single TSQL query for the server if the IQueryable result is never enumerated. This got me to thinking that my dynamic search construction was much too complicated - I just needed to combine multiple LINQ expressions.
For example (contrived):
```
Author:
ID (int),
LastName (varchar(32)),
FirstName (varchar(32))
context.Author.Where(xx => xx.LastName == "Smith").Where(xx => xx.FirstName == "John")
```
Results in the following query:
```
SELECT [t0].[ID], [t0].[LastName], [t0].[FirstName]
FROM [dbo].[Author] AS [t0]
WHERE ([t0].[LastName] = Smith) AND ([t0].[FirstName] = John)
```
I realized this might be the perfect solution for a simple dynamic query generation that's safe from SQL injection - I'd just loop over my IQueryable result and execute additional conditionals expressions to get my final single-execution expression.
However, I can't find any support for evaluation of XML data. In TSQL, to get a value from an XML node, we would do something like
```
XMLField.value('(*:Root/*:CreatedAt)[1]', 'datetime') = getdate()
```
But I can't find the LINQ to SQL equivalent of creating this evaluation. Does one exist? I know I can evaluate all non-XML conditions DB side, and then do my XML evaluations code side, but my data are large enough that A) that's a lot of network traffic to drag on performance and B) I'll get out-of-memory exceptions if I can't evaluate the XML first DB side to exclude certain result sets.
Ideas? Suggestions?
Bonus question - If XML evaluation is in fact possible DB side, what about FLWOR support?
|
Now that is an interesting question.
Right now, you cannot instruct SQL Server to perform XML functions directly from Linq.
However, you can get Linq to use user defined functions...
so, you could setup a udf to process the xml, get the right data, etc, and then use that in your Linq expresion. This will execute on the server and should do what you want. There's an important limitation, though: The XML path you're looking for (the first parameter to `xmlColumn.value` or similar) has to be built into the function because it has to be a string *literal*, it can't be built from an input parameter (for instance). So you can use UDFs for getting fields you know about when writing the UDF, but not as a general-purpose way to get data from XML columns.
Check out the Supporting User Defined Functions (UDFs) section of [Scott Gutherie's excellent Blog series on Linq to SQL](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx) for more info on implementation.
Hope this helps.
|
To clarify Daniel's answer - you cannot use a function to do this unless the XPath part of the query is fixed. See my blog entry on this: <http://conficient.wordpress.com/2008/08/11/linq-to-sql-faq-xml-columns-in-sql/>
Basically you cannot query an xml column via LINQ to SQL. Although it returns an XElement type you cannot do any SQL translations when trying to filter on this column.
LINQ to SQL does support using UDFs - but SQL itself will not allow you to use a parameter string in a XML xpath query - it has to be a string literal. That means it can work if the XPath is fixed at design time, but not if you wanted to be able to pass a variable XPath statement.
This leads to only two other alternative ways of doing it: inline SQL statement (which negates the value of having LINQ) and writing a SQL Library function in .NET CLR to do this.
|
Can LINQ to SQL query an XML field DB-serverside?
|
[
"",
"sql",
"xml",
"linq-to-sql",
".net-3.5",
""
] |
```
class C {
T a;
public:
C(T a): a(a) {;}
};
```
Is it legal?
|
Yes it is legal and works on all platforms.
It will correctly initialize your member variable a, to the passed in value a.
It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)
Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:
<member>(<value>)
You can verify what I wrote above by creating a simple program that does this: (It will not compile)
```
class A
{
A(int a)
: a(5)//<--- try to initialize a non member variable to 5
{
}
};
```
You will get a compiling error something like: A does not have a field named 'a'.
---
On a side note:
One reason why you **may not want** to use the same member name as parameter name is that you would be more prone to the following:
```
class A
{
A(int myVarriable)
: myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly
{
}
int myVariable;
};
```
---
On a side note(2):
One reason why you **may want** to use the same member name as parameter name is that you would be less prone to the following:
```
class A
{
A(int myVariable_)
{
//<-- do something with _myVariable, oops _myVariable wasn't initialized yet
...
_myVariable = myVariable_;
}
int _myVariable;
};
```
This could also happen with large initialization lists and you use \_myVariable before initializing it in the initialization list.
|
One of the things that may lead to confusion regarding this topic is how variables are prioritized by the compiler. For example, if one of the constructor arguments has the same name as a class member you could write the following in the initialization list:
```
MyClass(int a) : a(a)
{
}
```
But does the above code have the same effect as this?
```
MyClass(int a)
{
a=a;
}
```
The answer is no. Whenever you type "a" inside the body of the constructor the compiler will first look for a local variable or constructor argument called "a", and only if it doesn't find one will it start looking for a class member called "a" (and if none is available it will then look for a global variable called "a", by the way). The result is that the above statment "a=a" will assign the value stored in argument "a" to argument "a" rendering it a useless statement.
In order to assign the value of the argument to the class member "a" you need to inform the compiler that you are referencing a value inside **this** class instance:
```
MyClass(int a)
{
this->a=a;
}
```
Fine, but what if you did something like this (notice that there isn't an argument called "a"):
```
MyClass() : a(a)
{
}
```
Well, in that case the compiler would first look for an argument called "a" and when it discovered that there wasn't any it would assign the value of class member "a" to class member "a", which effectively would do nothing.
Lastly you should know that you can only assign values to class members in the initialization list so the following will produce an error:
```
MyClass(int x) : x(100) // error: the class doesn't have a member called "x"
{
}
```
|
Can I use identical names for fields and constructor parameters?
|
[
"",
"c++",
"parameters",
"constructor",
""
] |
I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.
The other factor to be taken into account is that the button is within a asp:Login control template.
I've no idea how to do this, suggestions on a postcard please.
|
You could look at the [`DefaultButton`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx) property of the panel control.
|
You could set the DefaultButton property on the form. Either as an attribute of the form tag in your markup DefaultButton = "btnSubmit" or using something like this in your code-behind:
```
Page.Form.DefaultButton = "btnSubmit"
```
|
Call a specific button onClick event when the enter key is pressed C#
|
[
"",
"c#",
"onclick",
"keypress",
"enter",
""
] |
Let's say I wanted to make a python script interface with a site like Twitter.
What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?
(This isn't Python run from a webserver, but run locally via the command line)
|
For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like [python-twitter](http://code.google.com/p/python-twitter/). This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implementation details.
If you want to roll your own interface library, you're going to have to get familiar with [urllib](https://docs.python.org/library/urllib.html) and depending on what format they provide results, either [lxml](http://lxml.de/) (or some other xml parser) or [simplejson](http://undefined.org/python/#simplejson).
|
Python has urllib2, which is extensible library for opening URLs
Full-featured easy to use library.
<https://docs.python.org/library/urllib2.html>
|
What Python tools can I use to interface with a website's API?
|
[
"",
"python",
"web-services",
"twitter",
""
] |
We've used both JWebUnit and HttpUnit in the past to do functional tests of web applications. Both of them seem to have issues in handling javascript. We are not particularly interested in testing the javascript at this point, but JWebUnit and HttpUnit tests have broken since we added some small Ajax components (Dojo Date / Time pickers for instance) to our pages.
Selenium and Watir do not fit because they essentially drive browsers and we are running these tests from CruiseControl on a box where we are not allowed to install a browser.
|
[Canoo's WebTest](http://webtest.canoo.com/webtest/manual/Downloads.html) is pretty good and can handle what you're looking for.
|
You want [HtmlUnit](http://htmlunit.sourceforge.net/).
It isn't perfect browser emulation (for that you need a browser driver) but it has significant javascript support. Check out the [introduction to testing your JavaScript](http://htmlunit.sourceforge.net/javascript-howto.html).
|
Replacement for JWebUnit / HttpUnit
|
[
"",
"java",
"testing",
"continuous-integration",
"web-testing",
""
] |
If you have a Java object and an XML schema (XSD), what is the best way to take that object and convert it into an xml file in line with the schema. The object and the schema do not know about each other (in that the java classes weren't created from the schema).
For example, in the class, there may be an integer field 'totalCountValue' which would correspond to an element called 'countTotal' in the xsd file. Is there a way of creating a mapping that will say "if the object contains an int totalCountValue, create an element called 'countTotal' and put it into the XML".
Similarly, there may be a field in the object that should be ignored, or a list in the object that should correspond to multiple XML elements.
I looked at XStream, but didn't see any (obvious) way of doing it. Are there other XML libraries that can simplify this task?
|
I believe this can be achieved via JAXB using it's annotations. I've usually found it much easier to generate Objects from JAXB ( as defined in your schema) using XJC than to map an existing Java object to match my schema. YMMV.
|
I'm doing Object do XML serialization with XStream. What don't you find "obvious" with this serializer? Once you get the hang of it its very simple.
In the example you provided you could have something like this:
```
...
XStream xstream = new XStream(new DomDriver());
xstream.alias("myclass", MyClass.class);
xstream.aliasField("countTotal", MyClass.class, "totalCountValue");
String xml = xstream.toXML(this);
...
```
for this sample class:
```
class MyClass {
private int totalCountValue;
public MyClass() {
}
}
```
If you find some serializer more simple or "cool" than this please share it with us. I'm also looking for a change...
Check the XStream mini tutorial [here](http://xstream.codehaus.org/tutorial.html)
|
Java object to XML schema
|
[
"",
"java",
"xml",
"object",
""
] |
I would like to include a different file depending on the version of GCC. More precisely I want to write:
```
#if GCC_VERSION >= 4.2
# include <unordered_map>
# define EXT std
#elif GCC_VERSION >= 4
# include <tr1/unordered_map>
# define EXT std
#else
# include <ext/hash_map>
# define unordered_map __gnu_cxx::hash_map
# define EXT __gnu_cxx
#endif
```
I don't care about gcc before 3.2.
I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.
|
Ok, after more searches, it one possible way of doing it is using `__GNUC_PREREQ` defined in `features.h`.
```
#ifdef __GNUC__
# include <features.h>
# if __GNUC_PREREQ(4,0)
// If gcc_version >= 4.0
# elif __GNUC_PREREQ(3,2)
// If gcc_version >= 3.2
# else
// Else
# endif
#else
// If not gcc
#endif
```
|
There are a number of macros that should be defined for your needs:
```
__GNUC__ // major
__GNUC_MINOR__ // minor
__GNUC_PATCHLEVEL__ // patch
```
The version format is major.minor.patch, e.g. 4.0.2
The documentation for these can be found [here](http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html).
|
How to test the current version of GCC at compile time?
|
[
"",
"c++",
"c",
"gcc",
"versions",
""
] |
I'm stuck in having to write a simple spam filter
I'm not really sure about how I'm going to do it.
So far I've come up with wordlist and domain filtering, which will give or remove points up to a certain threshold.
For example, if you're writing about "v1agr4" from a blacklisted domain, you'll get like 2 points for spam, but if you're writing about "v1agr4" from a hotmail.com account, you'll get only 1 "spam point".
Do you guys have any other suggestions / ressources?
This is more about learning spam filters than developing something enterprise grade
|
Some really good algorithm info here:
<http://www.paulgraham.com/spam.html>
<http://www.paulgraham.com/better.html>
But, seriously, why reinvent the wheel?
Just download K9: <http://keir.net/k9.html>
|
Some open source Java projects related to Bayesian Spam Filtering (that was mentioned by LFSR Consulting):
* [Classifier4j](http://classifier4j.sourceforge.net/)
* [jBNC](http://sourceforge.net/project/showfiles.php?group_id=49871)
* [Naiban](http://www.tempeststrings.com/naiban/)
And one extra for C++:
* [SpamProbe](http://sourceforge.net/projects/spamprobe/)
|
How to write spam filter
|
[
"",
"java",
"email-spam",
""
] |
**In C#, is there a way to instantiate an instance of a class without invoking its constructor?**
Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.
NOTE: I specifically **do not want to call any constructor** so using reflection to access the internal constructor is not an option.
|
I have not tried this, but there is a method called [FormatterServices.GetUninitializedObject](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx) that is used during deserialization.
Remarks from MSDN says:
> Because the new instance of the object
> is initialized to zero and no
> constructors are run, the object might
> not represent a state that is regarded
> as valid by that object.
|
Actually it sounds like they made the constructor internal just so you can't instantiate it. It may have a builder or factory method.
Check out these articles:
[Preventing Third Party Derivation: Part 1](http://blogs.msdn.com/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx)
[Preventing Third Party Derivation: Part 2](http://blogs.msdn.com/ericlippert/archive/2008/10/06/preventing-third-party-derivation-part-two.aspx)
they kind of explain the reasoning.
|
Create object instance without invoking constructor?
|
[
"",
"c#",
""
] |
What is the most concise and efficient way to find out if a JavaScript array contains a value?
This is the only way I know to do it:
```
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
```
Is there a better and more concise way to accomplish this?
This is very closely related to Stack Overflow question *[Best way to find an item in a JavaScript Array?](https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array)* which addresses finding objects in an array using `indexOf`.
|
Modern browsers have [`Array#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#browser_compatibility), which does *exactly* that and [is widely supported](https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes) by everyone except IE:
```
console.log(['joe', 'jane', 'mary'].includes('jane')); // true
```
You can also use [`Array#indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), which is less direct, but doesn't require polyfills for outdated browsers.
```
console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); // true
```
---
Many frameworks also offer similar methods:
* jQuery: [`$.inArray(value, array, [fromIndex])`](https://api.jquery.com/jquery.inarray/)
* Underscore.js: [`_.contains(array, value)`](https://underscorejs.org/#contains) (also aliased as `_.include` and `_.includes`)
* Dojo Toolkit: [`dojo.indexOf(array, value, [fromIndex, findLast])`](https://dojotoolkit.org/reference-guide/1.10/dojo/indexOf.html)
* Prototype: [`array.indexOf(value)`](http://api.prototypejs.org/language/Array/prototype/indexOf/)
* MooTools: [`array.indexOf(value)`](https://mootools.net/core/docs/1.6.0/Types/Array#Array:indexOf)
* MochiKit: [`findValue(array, value)`](http://mochi.github.io/mochikit/doc/html/MochiKit/Base.html#fn-findvalue)
* MS Ajax: [`array.indexOf(value)`](https://web.archive.org/web/20140819232945/http://www.asp.net/ajaxlibrary/Reference.Array-indexOf-Function.ashx)
* Ext: [`Ext.Array.contains(array, value)`](https://docs.sencha.com/extjs/7.5.1/modern/Ext.Array.html#method-contains)
* Lodash: [`_.includes(array, value, [from])`](https://lodash.com/docs#includes) (is `_.contains` prior 4.0.0)
* Ramda: [`R.includes(value, array)`](https://ramdajs.com/docs/#includes)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
|
**Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.**
As others have said, the iteration through the array is probably the best way, but it [has been proven](https://web.archive.org/web/20170403221045/https://blogs.oracle.com/greimer/entry/best_way_to_code_a) that a decreasing `while` loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:
```
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
```
Of course, you may as well extend Array prototype:
```
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
```
And now you can simply use the following:
```
alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false
```
|
How do I check if an array includes a value in JavaScript?
|
[
"",
"javascript",
"arrays",
"algorithm",
"time-complexity",
"javascript-objects",
""
] |
I am writing a small program. The interface I am writing to control each repository that is made defines a method of Save(IPublicObject). I am using LINQ for the SQL Version of the repository CRUD. My question is this. I would like to have only the one method which accepts the interface type. I want to think how I can best locate the Save action for the inherited type I then pass in.
In the book I am reading Patterns of Enterprise Application Architecture. I am leaning on the Inheritance Maping. So I create a derived object of
```
public class ConcretePublicObjectOne : IPublicObject{}
```
I want to then pass this into the Save Function of the respository. It is at this point where I am trying to think how best to say, ok we need to use "WHAT?" Save Method etc...
Should I use a registry, configuration setting mapping the types?
|
For LINQ-to-SQL, the data-context already does a lot of the mapping for you. As such, I think generics might be the best way to achieve a save while still having some consideration of your interface (although I'm not quite sure what the interface is giving you in this scenario...).
You can access the generic aspect of the data-context via `GetTable<T>()`:
```
static void Save<T>(T item)
where T : class, IPublicObject
{
using (DataContext ctx = GetDataContext())
{
Table<T> table = ctx.GetTable<T>();
// for insert...
table.InsertOnSubmit(item);
// for update...
table.Attach(item, true);
// for delete...
table.DeleteOnSubmit(item);
ctx.SubmitChanges();
}
}
```
Note that type-inference should mean that you don't need to specify the `T` when saving:
```
Foo foo = new Foo();
Save(foo); // <Foo> is inferred
```
Is that any use?
|
What you wish to do is to have a:
```
Repository.Save(publicObject)
```
and the repository to call a method from publicObject?
If this is the requirement then you can define the Save method in repository as:
```
public class Repository {
public void Save(IPublicObject publicObject) {
publicObject.Save();
}
}
```
where IPublicObject is defined as:
```
public interface IPublicObject {
void Save();
}
```
But with this approach you will have to define a save method for each entity (like ConcretePublicObjectOne in your example)
|
LINQ, Polymorphism, MetaDataMapping, Inheritance Mapper
|
[
"",
"c#",
"linq",
"poeaa",
""
] |
Is there a max length for an array in C++?
Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?
Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?
What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?
I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.
|
There are two limits, both not enforced by C++ but rather by the hardware.
The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's `std::size_t` can take. This data type is large enough to contain the size in bytes of any object
The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a `vector<int>` of a given size *n* typically takes multiple times as much memory as an array of type `vector<char>` (minus a small constant value), since `int` is usually bigger than `char`. Therefore, a `vector<char>` may contain more items than a `vector<int>` before memory is full. The same counts for raw C-style arrays like `int[]` and `char[]`.
Additionally, this upper limit may be influenced by the type of `allocator` used to construct the `vector` because an `allocator` is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.
Apart from that, C++ doesn't enforce any limits.
|
Nobody mentioned the limit on the size of the **stack frame**.
There are two places memory can be allocated:
* On the heap (dynamically allocated memory).
The size limit here is a combination of available hardware and the OS's ability to simulate space by using other devices to temporarily store unused data (**i.e.** move pages to hard disk).
* On the stack (Locally declared variables).
The size limit here is compiler defined (with possible hardware limits). If you read the compiler documentation you can often tweak this size.
Thus if you allocate an array dynamically (the limit is large and described in detail by other posts.
```
int* a1 = new int[SIZE]; // SIZE limited only by OS/Hardware
```
Alternatively if the array is allocated on the stack then you are limited by the size of the stack frame. **N.B.** vectors and other containers have a small presence in the stack but usually the bulk of the data will be on the heap.
```
int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame
```
|
Is there a max array length limit in C++?
|
[
"",
"c++",
"arrays",
""
] |
We have a system where customers, mainly European enter texts (in UTF-8) that has to be distributed to different systems, most of them accepting UTF-8, but now we must also distribute the texts to a US system which only accepts US-Ascii 7-bit
So now we'll need to translate all European characters to the nearest US-Ascii. Is there any Java libraries to help with this task?
Right now we've just started adding to a translation table, where Å (swedish AA)->A and so on and where we don't find any match for an entered character, we'll log it and replace with a question mark and try and fix that for the next release, but it seems very inefficient and somebody else must have done something similair before.
|
The [uni2ascii](http://billposer.org/Software/uni2ascii.html) program is written in C, but you could probably convert it to Java with little effort. It contains a large table of approximations (implicitly, in the switch-case statements).
Be aware that there are no universally accepted approximations: Germans want you to replace Ä by AE, Finns and Swedes prefer just A. Your example of [Å](http://en.wikipedia.org/wiki/%C3%85) isn't obvious either: Swedes would probably just drop the ring and use A, but Danes and Norwegians might like the historically more correct AA better.
|
You can do this with the following (from the NFD example in [this Core Java Technology Tech Tip](http://web.archive.org/web/20070917051642/http://java.sun.com/mailers/techtips/corejava/2007/tt0207.html#1)):
```
public static String decompose(String s) {
return java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+","");
}
```
|
How to convert UTF-8 to US-Ascii in Java
|
[
"",
"java",
"utf-8",
"ascii",
""
] |
I have a single user java program that I would like to have store data in a light weight database such as Derby or Sqlite. I would like to use a data abstraction layer in my program. Hibernate appears to require a lot of configuration and is overkill for what I need. What are light weight alternatives to Hibernate?
|
Hibernate requires next to zero configuration if you use annotations. It even can auto-discover mapped beans in the classpath! I don't see any alternative to it from both simplicity **and** power point of view.
It can also expose itself as JPA, which is (IMHO) even simpler.
|
My [ORMLite](http://ormlite.com/) library is one such alternative. It supports MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and Sqlite, and can be easily extended to others. It uses annotations to configure classes, good Spring support, flexible query builder, etc..
|
Light weight alternative to Hibernate?
|
[
"",
"java",
"database",
"hibernate",
"sqlite",
""
] |
So the [transparent background problem](https://stackoverflow.com/questions/214215/user-drawn-controls-are-using-the-previous-forms-background) is solved. Now, every time I show the form (or have to have it repainted), I get a lot of flickering. Is there any way I can not update the screen until the paint event is complete, or any other way to stop the 1/2 second of flickering and flashing while all the objects are being painted?
**ANSWER**: Double buffering is the way to go. I was already double buffering on the control, but it has to be set on the form. I though double buffering only worked when you were subclassing OnPaint yourself.
|
Did you try setting the [DoubleBuffered](https://stackoverflow.com/questions/220100/how-do-i-enable-double-buffering-of-a-control-using-c-window-forms) property for the form?
|
Double Buffering might help, another thing you might want to try is:
SuspendLayout();
dostuffhere...
ResumeLayout();
|
How to avoid screen flickering when showing form with user drawn controls?
|
[
"",
"c#",
".net",
"winforms",
"user-controls",
"onpaint",
""
] |
I have a loop that reads each line in a file using `getline()`:
```
istream is;
string line;
while (!getline(is, line).eof())
{
// ...
}
```
I noticed that calling `getline()` like this also seems to work:
```
while (getline(is, line))
```
What's going on here? `getline()` returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?
|
The `istream` returned by `getline()` is having its operator `void*()` method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to `eof()`.
|
**Updated:**
I had mistakenly pointed to the [basic\_istream documentation](http://www.unc.edu/depts/case/pgi/pgC++_lib/stdlibcr/bas_3074.htm#Sentry%20Classbool()) for the operator bool() method on the basic\_istream::sentry class, but as has been pointed out this is not actually what's happening. I've voted up Charles and Luc's correct answers. It's actually operator void\*() that's getting called. More on this [in the C++ FAQ](http://parashift.com/c++-faq-lite/input-output.html#faq-15.4).
|
std::getline() returns
|
[
"",
"c++",
"getline",
""
] |
I've written a VB.NET application that uses SQL CE 3.5. I'm curious if anyone has any best practice or code to help check if A) SQL CE is installed and B) If so, what version.
I searched msdn and google for anything but I didn't find anything helpful. I was poking around the registry and found this key:
HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server Compact Edition\v3.5
with a string value "Version" and the data was 3.5.5692.0.
So off the bat my assumption is to check for the presence of this key but it bothers me because the "3.5" key sure sounds like it's tied to the 3.5 DLL. What I'm trying to say is I'd hate to force someone to install SQL 3.5 if they have SQL CE (insert some future version of CE here).
Misc info:
Target Framework: .NET 2.0
Minimum Target OS: Windows XP SP2
|
The widely accepted method for doing this is checking the product identifier (GUID) which is saved in the registry by the MSI installer. If you dont have the product in question installed you can crack open the MSI with a tool called Orca (part of Windows SDK) and grab the GUID that way. Most if not all install builders have an action or task that can do this as part of a pre-req test, even VS2005/2008 has this capability.
To check versions, I would dig around again in the registry or maybe look at file versions.
|
Not sure if you are talking about SQL CE on a Windows machine or a portable device. On a PC, your best bet is to distribute the version of SQL CE with your application. You can register for the rights to do so at <http://www.microsoft.com/Sqlserver/2005/en/us/compact-redistribute.aspx>.
|
The best way to check if SQL CE is installed, and if so what version?
|
[
"",
".net",
"sql",
"vb.net",
"sql-server-ce",
""
] |
I've been hearing/reading a lot about the new language enhancements for C# 4. I'm a little curious if these same enhancements are also going to be applied to VB as well, or what. Does anyone know where I can get some insight here? With all the new changes happening to C#, it seems like there will very little reason left to be using VB unless you happen to like the syntax. Are there enhancements that MS isn't making to VB this time that are getting included in C#, or visa versa?
|
I'd actually overlook the dismissal of VB.Net by Lou Franco. Checkout Panopticon Central:
* <http://www.panopticoncentral.net/archive/2008/10/31/24803.aspx>
* <http://www.panopticoncentral.net/archive/2008/10/29/24764.aspx>
For example:
> Then Lucian did a really wonderful
> demo of VB 10.0, which is shipping in
> Visual Studio 2010. He showed (IIRC)
> the following features that should be
> familiar to the readers of this blog:
> array literals, collection
> initializers, automatic properties,
> implicit line continuations, statement
> lambdas, generic variance, and a
> feature that embeds primary interop
> assembly types in your assembly so you
> don’t have to deploy the PIA. I may
> have missed some, so check out the
> video when it’s posted!
|
Some of the changes to C# (e.g Named Optional Parameters) were already in VB. The main strength of VB.NET over C# was Office/COM integration, and the new C# is addressing that.
If you need to target an older .NET version, VB.NET will still be the one to use if you need these features.
|
New vb.net enhancements?
|
[
"",
"c#",
"vb.net",
""
] |
This code:
```
#include <iostream>
int main( int, char **argv )
{
std::cout << 1.23e45 << std::endl;
}
```
prints
> 1.23e+045
when compiled with MS Visual Studio 2003, and
> 1.23e+45
on my Linux machine.
How can I specify the width of the exponent field (and why is there a difference in the first place)?
|
I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how)
Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream.
Seems a lot of work, and while not rocket science, no trivial task either.
On the 'why' question: I know linux defines the exponent as minimum two digits, I suppose Windows specifies it as minimum three?
```
// on linux
std::cout << std::scientific << 1.23e4 << std::endl
```
Also adds a leading zero:
```
1.230000e+04
```
|
As a follow-up of @Pieter's answer, I've been looking inside the operator<< (ostream&, double). Indeed, there is no field to specify the significance or width of the exponent. On windows, the operator<< forwards to sprintf, which has no exponent-size either.
In it's turn, the sprintf function (on Windows) calls into \_cfltcvt\_l, a function we have no source code for, but whose signature doesn't provide for an exponent-precision.
I know nothing of the implementation on Linux.
|
How to set the width of the exponent field for an ostream?
|
[
"",
"c++",
""
] |
These two methods exhibit repetition:
```
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC,
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}
public static Expression<Func<Foo, FooListDto>> ListDtoSelector()
{
return f => new FooDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC
};
}
```
How can I refactor to eliminate this repetition?
UPDATE: Oops, I neglected to mention an important point. FooEditDto is a subclass of FooDto.
|
If `FooEditDto` is a sublass of `FooDto` and you don't need the MemberInitExpressions, use a constructor:
```
class FooDto
{ public FooDto(Bar a, Bar b, Bar c)
{ PropertyA = a;
PropertyB = b;
PropertyC = c;
}
public Bar PropertyA {get;set;}
public Bar PropertyB {get;set;}
public Bar PropertyC {get;set;}
}
class FooEditDto : FooDto
{ public FooEditDto(Bar a, Bar b, Bar c) : base(a,b,c)
public Bar PropertyD {get;set;}
public Bar PropertyE {get;set;}
}
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto(f.PropertyA,f.PropertyB,f.PropertyC)
{
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}
```
|
Well, I have a *really horrible* way you could do it.
You could write a method which used reflection (bear with me!) to work out all the properties for a particular type, and built a delegate (using Reflection.Emit) to copy properties from that type to another. Then use an anonymous type to make sure you only need to build the copying delegate once, so it's fast. Your method would then look like this:
```
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => MagicCopier<FooEditDto>.Copy(new {
f.PropertyA, f.PropertyB, f.PropertyC, f.PropertyD, f.PropertyC
});
}
```
The nuances here:
* MagicCopier is a generic type and Copy is a generic method so that you can explicitly specify the "target" type, but implicitly specify the "source" type.
* It's using a projection initializer to infer the names of the properties from the expressions used to initialize the anonymous type
I'm not sure whether it's really worth it, but it's quite a fun idea... I may have to implement it anyway :)
EDIT: With [MemberInitExpression](http://msdn.microsoft.com/en-us/library/system.linq.expressions.memberinitexpression.aspx) we could do it all with an expression tree, which makes it a lot easier than CodeDOM. Will give it a try tonight...
EDIT: Done, and it's actually pretty simple code. Here's the class:
```
/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// </summary>
public static class PropertyCopy<TTarget> where TTarget : class, new()
{
/// <summary>
/// Copies all readable properties from the source to a new instance
/// of TTarget.
/// </summary>
public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
{
return PropertyCopier<TSource>.Copy(source);
}
/// <summary>
/// Static class to efficiently store the compiled delegate which can
/// do the copying. We need a bit of work to ensure that exceptions are
/// appropriately propagated, as the exception is generated at type initialization
/// time, but we wish it to be thrown as an ArgumentException.
/// </summary>
private static class PropertyCopier<TSource> where TSource : class
{
private static readonly Func<TSource, TTarget> copier;
private static readonly Exception initializationException;
internal static TTarget Copy(TSource source)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
return copier(source);
}
static PropertyCopier()
{
try
{
copier = BuildCopier();
initializationException = null;
}
catch (Exception e)
{
copier = null;
initializationException = e;
}
}
private static Func<TSource, TTarget> BuildCopier()
{
ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
var bindings = new List<MemberBinding>();
foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
{
if (!sourceProperty.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
if (targetProperty == null)
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " is not present and accessible in " + typeof(TTarget).FullName);
}
if (!targetProperty.CanWrite)
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " is not writable in " + typeof(TTarget).FullName);
}
if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " has an incompatible type in " + typeof(TTarget).FullName);
}
bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
}
Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
}
}
```
And calling it:
```
TargetType target = PropertyCopy<TargetType>.CopyFrom(new { First="Foo", Second="Bar" });
```
|
Refactor To Eliminate Repetition In Lambda Expression
|
[
"",
"c#",
"refactoring",
"lambda",
""
] |
I was watching [Anders' talk about C# 4.0 and sneak preview of C# 5.0](http://channel9.msdn.com/pdc2008/TL16/), and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?
For example something like the `FileStream` class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an `IntPtr` and the ones from a `SafeFileHandle`.
```
FileStream(string,FileMode);
FileStream(string,FileMode,FileAccess);
FileStream(string,FileMode,FileAccess,FileShare);
FileStream(string,FileMode,FileAccess,FileShare,int);
FileStream(string,FileMode,FileAccess,FileShare,int,bool);
```
It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].
What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?
|
I'd consider the following:
* Do you need your code to be used from languages which don't support optional parameters? If so, consider including the overloads.
* Do you have any members on your team who violently oppose optional parameters? (Sometimes it's easier to live with a decision you don't like than to argue the case.)
* Are you confident that your defaults won't change between builds of your code, or if they might, will your callers be okay with that?
I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to `const` fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.
|
When a method overload normally performs the same thing with a different number of arguments then defaults will be used.
When a method overload performs a function differently based on its parameters then overloading will continue to be used.
I used optional back in my VB6 days and have since missed it, it will reduce a lot of XML comment duplication in C#.
|
Should you declare methods using overloads or optional parameters in C# 4.0?
|
[
"",
"c#",
"c#-4.0",
"overloading",
"optional-parameters",
""
] |
I have just started migrating my homegrown persistence framework to JPA.
Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.
I intend in all places to close them, but do I HAVE to?
At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.
|
It depends how you obtained it.
If you created it using EntityManagerFactory you will have to close it no matter what framework you use.
If you obtained it using dependency injection (eg using EJB and [@PersistenceContext](https://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html) annotation) you should not close it by hand (AFAIK it will cause RuntimeException).
|
You should.
Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.
The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".
Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.
|
Do I have to close() every EntityManager?
|
[
"",
"java",
"jpa",
"persistence",
"toplink",
""
] |
This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.
Thanks!
I was in error with my last comment all is good now.
|
You can use a check constraint on the column. IIRC the syntax for this looks like:
```
create table foo (
[...]
,Foobar int not null check (Foobar > 0)
[...]
)
```
As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.
```
alter table foo
add constraint Foobar_NonNegative
check (Foobar > 0)
```
You can get out the text of check constraints from the system data dictionary in `sys.check_constraints`:
```
select name
,description
from sys.check_constraints
where name = 'Foobar_NonNegative'
```
|
Create a database constraint:
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)
```
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)
```
|
In SQL Server 2005, how do I set a column of integers to ensure values are greater than 0?
|
[
"",
"sql",
"sql-server-2005",
"constraints",
"check-constraints",
""
] |
FreeMarker templates support an if-statement with the following syntax
```
<#if hot>
It's hot.
</#if>
```
I've looked in the documentation and can't find any support for an if-else statement. Of course, I could achieve the same result with:
```
<#if hot>
It's hot.
</#if>
<#if !hot>
It's not hot.
</#if>
```
Is there support for if-else in FreeMarker?
|
Yes, you can write:
```
<#if hot>
it's hot
<#else>
it's not
</#if>
```
And if you're doing lots of freemarker, I really can recommend IntelliJ IDEA 8, its freemarker support really helps...
|
Yes, the sintaxis is:
```
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
<#else>
...
<#/if>
```
You can find [Freemarker complete reference](http://freemarker.sourceforge.net/docs/)
If you are using Netbeans, there is [this plugin](http://plugins.netbeans.org/PluginPortal/faces/PluginListPage.jsp?search=freemarker)
|
if-else in FreeMarker template
|
[
"",
"java",
"template-engine",
"freemarker",
""
] |
Let's say I'm running a simple server and have `accept()`ed a connection from a client.
What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle this?
|
select (with the read mask set) will return with the handle signalled, but when you use ioctl\* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected: [Stephen Cleary, Detection of Half-Open (Dropped) Connections](http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html).
\* for Windows use ioctlsocket.
|
In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from `read()/recv()/recvXXX()` when reading.
There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and timeouts to know that it's broken and will eventually cause `write()/send()/sendXXX()` to return -1 with an `errno/WSAGetLastError()` value of `ECONNRESET,` or in some cases 'connection timed out'. Note that the latter is different from 'connect timeout', which can occur in the connect phase.
You should also set a reasonable read timeout, and drop connections that fail it.
The answer here about `ioctl()` and `FIONREAD` is compete nonsense. All that does is tell you how many bytes are presently in the socket receive buffer, available to be read without blocking. If a client doesn't send you anything for five minutes that doesn't constitute a disconnect, but it does cause `FIONREAD` to be zero. Not the same thing: not even close.
|
Detecting TCP Client Disconnect
|
[
"",
"c++",
"sockets",
"tcp",
""
] |
Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining.
Is there a way that I can optimize it without manipulating the string?
|
You **must** tokenize your input before starting this kind of process. (I can't recommend the famous [Dragon Book](http://en.wikipedia.org/wiki/21st_Century_Compilers) highly enough - even the ancient edition stood the test of time, the updated 2006 version looks great). Compiling is the sort of job that's best split up into smaller phases: if your first phase performs lexical analysis into tokens, splitting lines into keywords, identifiers, constants, and so on, then it's much simpler to find the references to macros and look them up in a symbol table. (It's also relatively easier to use a tool like lex or flex or one of their modern equivalents to do this job for you, than to attempt to do it from scratch).
The 'clue' seems to be *if the code has more number of macros then the code generation takes so much of time*. That sounds like the process is linear in the number of macros, which is certainly too much. I'm assuming this process occurs one line at a time (if your language allows that, obviously that has enormous value, since you don't need to treat the program as one huge string), and the pseudocode looks something like
```
for(each line in the program)
{
for(each macro definition)
{
test if the macro appears;
perform replacement if needed;
}
}
```
That clearly scales with the number of macro definitions.
With tokenization, it looks something like this:
```
for(each line in the program)
{
tokenize the line;
for(each token in the line)
{
switch(based on the token type)
{
case(an identifier)
lookup the identifier in the table of macro names;
perform replacement as necessary;
....
}
}
}
```
which scales mostly with the size of the program (not the number of definitions) - the symbol table lookup can of course be done with more optimal data structures than looping through them all, so that no longer becomes the significant factor. That second step is something that again programs like yacc and bison (and their more modern variants) can happily generate code to do.
**afterthought:** when parsing the macro *definitions*, you can store those as a token stream as well, and mark the identifiers that are the 'placeholder' names for parameter replacement. When expanding a macro, switch to that token stream. (Again, something things like flex can easily do).
|
I have an application which has its own grammer. It supports all types of datatypes that a typical compiler supports (Even macros). More precisely it is a type of compiler which generates the opcodes by taking a program (which is written using that grammer) as input.
For handling the macros, it uses the text replacement logic
For Example:
Macro Add (a:int, b:int)
```
int c = a + b
```
End Macro
// Program Sum
..
int x = 10, y = 10;
Add(x, y);
..
// End of the program
After replacement it will be
// Program Sum
..
int x = 10, y = 10;
int c = x + y
..
// End of program
This text replacement is taking so much of time i.e., replacing the macro call with macro logic.
Is there a optimal way to do it?
|
Macro Replacement during Code Generation
|
[
"",
"c++",
"compiler-construction",
"macros",
""
] |
At the moment my code looks like this:
```
# Assign values for saving to the db
$data = array(
'table_of_contents' => $_POST['table_of_contents'],
'length' => $_POST['length']
);
# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
$data = array(
'lossless_copy' => $_POST['lossless_copy']
);
}
// etc.
```
This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?
|
How about this:
```
// this is an array of default values for the fields that could be in the POST
$defaultValues = array(
'table_of_contents' => '',
'length' => 25,
'lossless_copy' => false,
);
$data = array_merge($defaultValues, $_POST);
// $data is now the post with all the keys set
```
`array_merge()` will merge the values, having the later values override the previous ones.
If you don't want to trust `array_merge()` then you can do a `foreach()` loop.
|
```
foreach ($_POST as $key => $value) {
$data[$key] = $value;
}
```
remember to sanitize your $\_POST values!
**edit**: if you're looking to match up optional $\_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):
```
$fields = array();
$table = 'Current_Table';
// we are not using mysql_list_fields() as it is deprecated
$query = "SHOW COLUMNS from {$table}";
$result = mysql_query($query);
while ($get = mysql_fetch_object($result) ) {
$fields[] = $get->Field;
}
foreach($fields as $field) {
if (isset($_POST[$field]) ) {
$data[$field] = $_POST[$field];
}
}
```
|
How to check for optional fields in $_POST
|
[
"",
"php",
"forms",
"post",
""
] |
This is a follow-up to [two](https://stackoverflow.com/questions/269417/which-language-should-i-use) [questions](https://stackoverflow.com/questions/271488/linking-languages) I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.
That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me.
I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates *be* the code as with php?
I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?
|
"how easy is CGI programming in python?" Easier than C, that's for sure. Python is easier because -- simply -- it's an easier language to work with than C. First and foremost: no memory allocation-deallocation. Beyond that, the OO programming model is excellent.
Beyond the essential language simplicity, the Python [WSGI](http://www.wsgi.org/wsgi/) standard is much easier to cope with than the CGI standard.
However, raw CGI is a huge pain when compared with the greatly simplified world of an all-Python framework ([TurboGears](http://turbogears.org/), [CherryPy](http://www.cherrypy.org/), [Django](http://www.djangoproject.com/), whatever.)
The frameworks impose a lot of (necessary) structure. The out-of-the-box experience for a CGI programmer is that it's too much to learn. True. All new things are too much to learn. However, the value far exceeds the investment.
With Django, you're up and running within minutes. Seriously. `django-admin.py startproject` and you have something you can run almost immediately. You do have to design your URL's, write view functions and design page templates. All of which is work. But it's *less* work than CGI in C.
Django has a better architecture than PHP because the presentation templates are completely separated from the processing. This leads to some confusion (see [Syntax error whenever I put python code inside a django template](https://stackoverflow.com/questions/276345/syntax-error-whenever-i-put-python-code-inside-a-django-template)) when you want to use the free-and-unconstrained PHP style on the Django framework.
**linking the user interface to the back-end**
Python front-end (Django, for example) uses Python view functions. Those view functions can contain any Python code at all. That includes, if necessary, modules written in C and callable from Python.
That means you can compile a [CLIPS](http://clipsrules.sourceforge.net/) module with a Python-friendly interface. It becomes something available to your Python code with the `import` statement.
Sometimes, however, that's ineffective because your Django pages are waiting for the CLIPS engine to finish. An alternative is to use something like a named pipe.
You have your CLIPS-based app, written entirely in C, reading from a named pipe. Your Django application, written entirely in Python, writes to that named pipe. Since you've got two independent processes, you'll max out all of your cores pretty quickly like this.
|
Python is a good choice.
I would avoid the CGI model though - you'll pay a large penalty for the interpreter launch on each request. Most Python web frameworks support [the WSGI standard](http://www.wsgi.org/wsgi/) and can be hooked up to servers in a myriad of ways, but most live in some sort of long-running process that the web server communicates with (via proxying, FastCGI, SCGI, etc).
Speaking of frameworks, the Python landscape is ripe with them. This is both good and bad. There are many fine options but it can be daunting to a newcomer.
If you are looking for something that comes prepackaged with web/DB/templating integration I'd suggest looking at [Django](http://www.djangoproject.com), [TurboGears](http://www.turbogears.org) or [Pylons](http://www.pylonshq.com). If you want to have more control over the individual components, look at [CherryPy](http://www.cherrypy.org), [Colubrid](http://wsgiarea.pocoo.org/colubrid/) or [web.py](http://www.webpy.org).
As for whether or not it is as "easy as PHP", that is subjective. Usually it is encouraged to keep your templates and application logic separate in the Python web programming world, which can make your *life* easier. On the other hand, being able to write all of the code for a page in a PHP file is another definition of "easy".
Good luck.
|
Using python to build web applications
|
[
"",
"python",
"cgi",
""
] |
What is the difference between `atan` and `atan2` in C++?
|
[`std::atan2`](http://en.cppreference.com/w/cpp/numeric/math/atan2) allows calculating the arctangent of all four quadrants. [`std::atan`](http://en.cppreference.com/w/cpp/numeric/math/atan) only allows calculating from quadrants 1 and 4.
|
From school mathematics we know that the tangent has the definition
```
tan(α) = sin(α) / cos(α)
```
and we differentiate between four quadrants based on the angle that we supply to the functions. The sign of the `sin`, `cos` and `tan` have the following relationship (where we neglect the exact multiples of `π/2`):
```
Quadrant Angle sin cos tan
-------------------------------------------------
I 0 < α < π/2 + + +
II π/2 < α < π + - -
III π < α < 3π/2 - - +
IV 3π/2 < α < 2π - + -
```
Given that the value of `tan(α)` is positive, we cannot distinguish, whether the angle was from the first or third quadrant and if it is negative, it could come from the second or fourth quadrant. So by convention, `atan()` returns an angle from the first or fourth quadrant (i.e. `-π/2 <= atan() <= π/2`), regardless of the original input to the tangent.
In order to get back the full information, we must not use the result of the division `sin(α) / cos(α)` but we have to look at the values of the sine and cosine separately. And this is what `atan2()` does. It takes both, the `sin(α)` and `cos(α)` and resolves all four quadrants by adding `π` to the result of `atan()` whenever the cosine is negative.
**Remark:** The `atan2(y, x)` function actually takes a `y` and a `x` argument, which is the projection of a vector with length `v` and angle `α` on the y- and x-axis, i.e.
```
y = v * sin(α)
x = v * cos(α)
```
which gives the relation
```
y/x = tan(α)
```
**Conclusion:**
`atan(y/x)` holds back some information and one can only assume that the input came from quadrants I or IV. In contrast, `atan2(y,x)` gets all the data and thus can resolve the correct angle.
|
What is the difference between atan and atan2 in C++?
|
[
"",
"c++",
"math.h",
""
] |
I am reworking some ui in an application written by freelance .Net developers from another country.
I am not going to go into how bad the code is and entangled the code with structure content and presentation are...
But one of the things I notice is that menu for accessing the parts of the app is made with Button controls that post to the server and return a different page. I would like to change the buttons to LinkControls are there any reasons that people might have done this ?
I notice that when I do change to to LinkButtons there is actually javascript that seems to trigger the post action. Any reasons or ways to avoid this ?
|
You could re-style the buttons to look like links, then you can maintain any server-side code, and not have to rely on javascript like the LinkButton does.
```
.linkButton
{
background-color: transparent;
border-style: none;
color: /* Something nice */
cursor: pointer;
text-align: left;
text-decoration: underline;
display: table-cell;
}
```
Of course if these buttons are simply used for navigation without any server side logic, then good old html links would do just fine...
|
A LinkButton is just that--an anchor tag with javascript that submits the page's form. If you don't want that behavior, don't use a link button. Just use a standard anchor tag.
I've used LinkButtons in the past because its a very easy way to merge the behavior of a button with the style of a regular html link. Noobs might also use them because its a simple way to create a link and they don't know better yet.
|
Why would someone use Button instead of LinkButton control in navigation
|
[
"",
"c#",
".net",
"web-applications",
""
] |
I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.
Setting the ContextMenuStrip for the ToolStripComboBox is easy:
```
myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu;
```
but there's no obvious equivalent for the ToolStripButton. How do I add a ContextMenuStrip to a ToolStripButton?
|
What Jeff Yates has suggested should work.
However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events will trigger the display of the context menu.
This offloads any of the knowledge needed to only those items interested.
Below is one such example using ToolStripTextBox as the item.
```
public class MyTextBox : ToolStripTextBox
{
ContextMenuStrip _contextMenuStrip;
public ContextMenuStrip ContextMenuStrip
{
get { return _contextMenuStrip; }
set { _contextMenuStrip = value; }
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (_contextMenuStrip !=null)
_contextMenuStrip.Show(Parent.PointToScreen(e.Location));
}
}
}
```
|
You will need to set the context menu to the ToolStrip and then handle the Popup of the context menu or a related event and hit test which button the mouse is over to determine if you should show the ToolStrip's context menu and what it should contain.
|
How do I add a ContextMenuStrip to a ToolStripButton?
|
[
"",
"c#",
"winforms",
"contextmenustrip",
"toolstripbutton",
""
] |
What exactly does *immutable* mean - that is, what are the consequences of an object being mutable or immutable? In particular, why are Java's `String`s immutable?
My understanding is that the `StringBuilder` type is something like a mutable equivalent to `String`. When would I use `StringBuilder` rather than `String`, and vice-versa?
|
Immutable means that once the constructor for an object has completed execution that instance can't be altered.
This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. *Especially when dealing with concurrency, there are no locking issues with objects that never change*
e.g.
```
class Foo
{
private final String myvar;
public Foo(final String initialValue)
{
this.myvar = initialValue;
}
public String getValue()
{
return this.myvar;
}
}
```
`Foo` doesn't have to worry that the caller to `getValue()` might change the text in the string.
If you imagine a similar class to `Foo`, but with a `StringBuilder` rather than a `String` as a member, you can see that a caller to `getValue()` would be able to alter the `StringBuilder` attribute of a `Foo` instance.
Also beware of the different kinds of immutability you might find: Eric Lippert wrote a [blog article](https://learn.microsoft.com/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability) about this. Basically you can have objects whose interface is immutable but behind the scenes actual mutables private state (and therefore can't be shared safely between threads).
|
An immutable object is an object where the internal fields (or at least, all the internal fields that affect its external behavior) cannot be changed.
There are a lot of advantages to immutable strings:
**Performance:** Take the following operation:
```
String substring = fullstring.substring(x,y);
```
The underlying C for the substring() method is probably something like this:
```
// Assume string is stored like this:
struct String { char* characters; unsigned int length; };
// Passing pointers because Java is pass-by-reference
struct String* substring(struct String* in, unsigned int begin, unsigned int end)
{
struct String* out = malloc(sizeof(struct String));
out->characters = in->characters + begin;
out->length = end - begin;
return out;
}
```
Note that *none of the characters have to be copied!* If the String object were mutable (the characters could change later) then you would have to copy all the characters, otherwise changes to characters in the substring would be reflected in the other string later.
**Concurrency:** If the internal structure of an immutable object is valid, it will always be valid. There's no chance that different threads can create an invalid state within that object. Hence, immutable objects are *Thread Safe*.
**Garbage collection:** It's much easier for the garbage collector to make logical decisions about immutable objects.
However, there are also downsides to immutability:
**Performance:** Wait, I thought you said performance was an upside of immutability! Well, it is sometimes, but not always. Take the following code:
```
foo = foo.substring(0,4) + "a" + foo.substring(5); // foo is a String
bar.replace(4,5,"a"); // bar is a StringBuilder
```
The two lines both replace the fourth character with the letter "a". Not only is the second piece of code more readable, it's faster. Look at how you would have to do the underlying code for foo. The substrings are easy, but now because there's already a character at space five and something else might be referencing foo, you can't just change it; you have to copy the whole string (of course some of this functionality is abstracted into functions in the real underlying C, but the point here is to show the code that gets executed all in one place).
```
struct String* concatenate(struct String* first, struct String* second)
{
struct String* new = malloc(sizeof(struct String));
new->length = first->length + second->length;
new->characters = malloc(new->length);
int i;
for(i = 0; i < first->length; i++)
new->characters[i] = first->characters[i];
for(; i - first->length < second->length; i++)
new->characters[i] = second->characters[i - first->length];
return new;
}
// The code that executes
struct String* astring;
char a = 'a';
astring->characters = &a;
astring->length = 1;
foo = concatenate(concatenate(slice(foo,0,4),astring),slice(foo,5,foo->length));
```
Note that concatenate gets called **twice** meaning that the entire string has to be looped through! Compare this to the C code for the `bar` operation:
```
bar->characters[4] = 'a';
```
The mutable string operation is obviously much faster.
**In Conclusion:** In most cases, you want an immutable string. But if you need to do a lot of appending and inserting into a string, you need the mutability for speed. If you want the concurrency safety and garbage collection benefits with it the key is to keep your mutable objects local to a method:
```
// This will have awful performance if you don't use mutable strings
String join(String[] strings, String separator)
{
StringBuilder mutable;
boolean first = true;
for(int i = 0; i < strings.length; i++)
{
if(first) first = false;
else mutable.append(separator);
mutable.append(strings[i]);
}
return mutable.toString();
}
```
Since the `mutable` object is a local reference, you don't have to worry about concurrency safety (only one thread ever touches it). And since it isn't referenced anywhere else, it is only allocated on the stack, so it is deallocated as soon as the function call is finished (you don't have to worry about garbage collection). And you get all the performance benefits of both mutability and immutability.
|
What is meant by immutable?
|
[
"",
"java",
"string",
"immutability",
""
] |
I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following:
```
Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
```
this errors with a incompatible types on Map.Entry. So if I type the declaration with:
```
Map<Object, Object> map = new HashMap();
```
then all works well. So what is the default type that gets set in the declaration about? Or am I missing something else?
|
The type is *java.lang.Object*.
The *for* construct takes a type of *Iterable* and calls its *iterator* method. Since the *Set* isn't typed with generics, the iterator returns objects of type *Object*. These need to be explicitly cast to type *Map.Entry*.
```
Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Object o : map.entrySet()) {
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
```
|
There is no default type.
The types in Java generics are only for compile-time checking. They are erased at runtime and essentially gone.
Think of generics as a static helper to a) better document your code, and b) enable some limited compile-time checking for type safety.
|
HashMap default types for K and V
|
[
"",
"java",
"generics",
"collections",
""
] |
I am evaluating several Javascript UI toolkits for building web applications that have a desktop-like feel, mainly because of dialogs and window management.
I looked at several options - here are my evaluations so far:
* [ExtJS](http://extjs.com/) - Great widget library, great docs! Not so great license.
* [jQuery UI](http://ui.jquery.com/) - Lack of ready-made window and dialog containers. I love jQuery though.
* [Yahoo! UI](http://developer.yahoo.com/yui/) - Same problem as above. Really mature (but, unfortunately, [is no longer being actively maintained](https://yahooeng.tumblr.com/post/96098168666/important-announcement-regarding-yui)) and well documented.
* [Mocha](http://mochaui.com/demo/) (Mootools-based) - Not as mature as the others. Lacks good documentation.
* [SproutCore](http://www.sproutcore.com/) - Same as above. Also doesn't have window and dialog widgets.
* [Cappuccino](http://cappuccino.org/) - Too weird and revolutionary.
What's your take on these? Are my evaluations correct?
|
In terms of a desktop look/feel the best of that bunch has to be ExtJS. In terms of the UI it really is leaps ahead of the rest. Of course there are licensing issues but they have their FLOSS exceptions and if you intend to make money from the project then a commercial license isn't exactly going to break the bank.
Other Very Rich Framework worth looking at (all have their good and bad points),
* [Bindows](http://www.bindows.net/)
* [Tibco General Interface](http://www.tibco.com/devnet/gi/)
* [vegUI](http://www.vegui.org/)
* [Echo](http://echo.nextapp.com/site/echo3)
|
Have you thought about GWT (Google Web Toolkit <http://code.google.com/webtoolkit/> )?
|
Javascript library for building desktop-like web application: ExtJS, jQuery, YahooUI, Mocha, SproutCore, Cappuccino, others?
|
[
"",
"javascript",
"jquery",
"extjs",
"yui",
"mootools",
""
] |
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.
The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdown` method, but it is missing in `HTTPServer`.
The whole `BaseHTTPServer` module has very little documentation :(
|
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve\_forever (from SocketServer.py) method looks like this:
```
def serve_forever(self):
"""Handle one request at a time until doomsday."""
while 1:
self.handle_request()
```
You could replace (in subclass) `while 1` with `while self.should_be_running`, and modify that value from a different thread. Something like:
```
def stop_serving_forever(self):
"""Stop handling requests"""
self.should_be_running = 0
# Make a fake request to the server, to really force it to stop.
# Otherwise it will just stop on the next request.
# (Exercise for the reader.)
self.make_a_fake_request_to_myself()
```
Edit: I dug up the actual code I used at the time:
```
class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
stopped = False
allow_reuse_address = True
def __init__(self, *args, **kw):
SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
self.register_function(lambda: 'OK', 'ping')
def serve_forever(self):
while not self.stopped:
self.handle_request()
def force_stop(self):
self.server_close()
self.stopped = True
self.create_dummy_request()
def create_dummy_request(self):
server = xmlrpclib.Server('http://%s:%s' % self.server_address)
server.ping()
```
|
Another way to do it, based on <http://docs.python.org/2/library/basehttpserver.html#more-examples>, is: instead of serve\_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:
```
import CGIHTTPServer
import BaseHTTPServer
KEEP_RUNNING = True
def keep_running():
return KEEP_RUNNING
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/cgi-bin"]
httpd = BaseHTTPServer.HTTPServer(("", 8000), Handler)
while keep_running():
httpd.handle_request()
```
|
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
|
[
"",
"python",
"http",
"basehttpserver",
""
] |
This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:
```
char DestFile[256];
char DestFile2[256];
//This part is just to show an example
strcpy(DestFile, "/foo/boo/goo.gz")
strcpy ( DestFile2, DestFile );
Ptr = strrchr ( DestFile2, '.' );
if ( Ptr != 0 ) {
if ( ( strcmp ( Ptr, ".gz" ) == 0 ) ||
( strcmp ( Ptr, ".Z" ) == 0 ) ) {
*Ptr = 0;
rename ( DestFile, DestFile2 );
}
}
```
DestFile2 is not set anywhere else in the function. I compiled the code above, and printing out the DestFile shows nothing has changed. The only thing i can think of that this does is removing the file extension (\*Ptr=0) but my knowledge of C is very limited...
Any ideas? It looks like every time it gets a file with .gz or .z it renames the file to the same name.
|
You are correct.
In C a string is an array of chars terminated by a character with ASCII code 0.
So, first, DestFile is copied to DestFile2
Then a scan from the right is performed, to find the right-most occurrence of '.'
This returns a pointer to the char that matches, or null if no occurrence is found.
So now you have (example name: myfile.gz)
DestFile2
> ```
> |- Ptr
> v
> M y f i l e . g z \0
> ```
Then it compares if the string starting at Ptr matches .Z or .gz and if so, sets the value of the char that Ptr points to to \0, effectively truncating the string.
After setting Ptr to \0 you now have
> M y f i l e \0 g z \0
Remember that c thinks a string is done when we reach a \0, so the last rename effectively says
```
rename("myfile.gz", "myfile");
```
|
Yeah, that's what it looks like to me too. It's renaming any .gz or .Z (gzipped or Unix Compressed files) to remove the extension.
Why it would want to do that beats me. The only use I've seen for doing such things is to get around fascist email servers that don't allow compressed attachments through.
|
Does this code remove a file extension?
|
[
"",
"c++",
"c",
""
] |
How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?
Here are a few references on the subject:
* <http://www.hibernate.org/333.html>
* <http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/>
* <http://in.relation.to/Bloggers/HibernateAndSwingDemoApp>
|
Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.
It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.
**Update**
Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate.
Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.
The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.
```
MyHibernateUtils.begin();
Settings settings = DaoSettings.load();
// update setttings here
DaoSettings.save(settings);
MyHibernateUtils.commit();
```
If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.
As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().
|
Don't use a single session. For everything but the smallest applications, it will grow, collecting outdated data and become slower and slower, since the dirty check needs to check every entity in the session.
If you don't need/want lazy loading and tracking of changes by Hibernate, you can use short-lived sessions.
But if you want to benefit from the power of Hibernate use the approach I described in my blog:
<http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/>
or in the German version:
<http://blog.schauderhaft.de/2007/12/17/hibernate-sessions-in-fat-client-anwendungen/>
AFAIK it is really the same approach described in the <http://in.relation.to/Bloggers/HibernateAndSwingDemoApp> but with a recommendation how to actually scope your session:
On Session per Frame, with the exception of modal Frames which use the session of the parent Frame.
Just make sure never to combine objects from different sessions. It will cause lots of trouble.
In reply to Vladimirs update:
* The cancel actually works extremely nice with my approach: throw away the session.
* session.flush does not fix the problem of the evergrowing session when you work with a single session for the application. Of course with the approach, you describe you can work with short-lived sessions which should work ok. BUT
* you lose a lot: lazy loading only works with attached objects, automatic detection of dirty objects. If you work with detached objects (or objects that aren't entities at all) you have to do this yourself.
|
Session management using Hibernate in a Swing application
|
[
"",
"java",
"database",
"hibernate",
"swing",
"session",
""
] |
Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
|
Use [str\_split()](http://php.net/str_split):
```
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
```
The output:
```
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
```
Then of course to insert hyphens between the sets you just [implode()](http://php.net/implode) them together:
```
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
```
|
This is a bit more general:
```
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>
```
|
Most efficient way to delimit key
|
[
"",
"php",
"string",
""
] |
One of the [appropriate uses](http://www.sqlite.org/whentouse.html) for [sqlite3](http://www.sqlite.org) is "in-memory databases". This sounds like a really useful tool for my C++ applications. Does anyone have an example of how this is done in C or C++? I'm specifically looking for a canonical way to slurp several flat-files into an in-memory database, then do some joins.
|
It's actually quite easy. Just specify ':memory:' as the database filename when opening a database using the C/C++ API. It's a special constant that the engine will recognize. The same actually works for other languages such as Python or Ruby, since they typically just wrap the C/C++ API. See <http://sqlite.org/c3ref/open.html> for complete details.
|
Just open the file :memory: and that should do it (at least it does in PHP).
You mention that you want to read in several flat files and do joins on them. If it's possible to store the flat files as SQLite databases, you can work directly with both by attaching one to the other:
```
ATTACH foo.db AS foo
```
Then refer to the tables in foo like so:
```
SELECT * FROM foo.users
```
This way you can do your joins without the need for creating an in-memory database.
|
How do I create a sqllite3 in-memory database?
|
[
"",
"c++",
"c",
"database",
"sqlite",
"in-memory-database",
""
] |
Using jQuery, what's the best way to find the next form element on the page, starting from an arbitrary element? When I say form element I mean `<input>`, `<select>`, `<button>` or `<textarea>`.
In the following examples, the element with the id "this" is the arbitrary starting point, and the element with the id "next" is the one I want to find. The same answer should work for all examples.
Example 1:
```
<ul>
<li><input type="text" /></li>
<li><input id="this" type="text" /></li>
</ul>
<ul>
<li><input id="next" type="text" /></li>
</ul>
<button></button>
```
Example 2:
```
<ul>
<li><input id="this" type="text" /></li>
</ul>
<button id="next"></button>
```
Example 3:
```
<input id="this" type="text" />
<input id="next" type="text" />
```
Example 4:
```
<div>
<input id="this" type="text" />
<input type="hidden" />
<div>
<table>
<tr><td></td><td><input id="next" type="text" /></td></tr>
</table>
</div>
<button></button>
</div>
```
EDIT: The two answers provided so far both require writing a sequence number to all input elements on the page. As I mentioned in the comments of one of them, this is kind of what I'm already doing and I would much prefer have a read-only solution since this will be happening inside a plugin.
|
kudos,
What about using .index?
e.g `$(':input:eq(' + ($(':input').index(this) + 1) + ')');`
|
redsquare is absolutely right, and a great solution also, which I also used in one of my project.
I just wanted to point out that he is missing some parentheses, since the current solution concatenates the index with 1, instead of adding them together.
So the corrected solution would look like:
```
$(":input:eq(" + ($(":input").index(this) + 1) + ")");
```
Sorry about the double-post, but I couldn't find a way to comment his post...
|
Best way to find "next" form input element in jQuery?
|
[
"",
"javascript",
"jquery",
""
] |
I am working on a large project that uses the STL and have a question about your preferred way to organise your STL `#includes`.
* Do you prefer to #include each header in the source file it is used. For example, if both `foo.cpp` and `bar.cpp` require `std::string`, then both will `#include <string>`.
* Do you prefer to have a single header file that includes all the STL headers your project uses (i.e. add them to the MS 'stdafx.h' pre-compiled header).
The advantage of the first method is that the .cpp file is an independent unit and can be used in a different project without having to worry that you're missing a `#include`. The advantages of the second method is that you can take use your compilers pre-compiled header support plus you can wrap STL `#includes` in `pragmas` that disable some warnings (for example, some Boost headers will cause warnings when compiling at level 4).
Which do you prefer to use?
|
I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible.
Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So even if something gets declared via the included precompiled headers, I still include the 'regular' header, which will get skipped by the include guard mechanism and won't add anything significant to the compile times.
As precompiled headers are a compiler specific thing. Optimizing / changing precompiled headers should have no effect on the correct functioning of the code in my opinion.
The main advantage of having dependencies as low as possible is that refactoring gets easier (or rather: feasible)
Great book on all this is [Large Scale C++ Design from Lakos](https://rads.stackoverflow.com/amzn/click/com/0201633620)
|
What I do is include all STL headers I'm going to need in the entire project in my single [precompiled header](http://msdn.microsoft.com/en-us/library/szfdksca.aspx), usually the default StdAfx.h. A precompiled header is the de-facto first thing to set up in a project, including all STL-/boost-/platform headers and third party libraries.
STL & boost are neatly arranged in namespaces, so they don't ever cause any mix-ups or overlaps either.
In headers I usually use the full names, but in the source files do *using namespace x* when appropriate.
|
How do you organise your STL headers?
|
[
"",
"c++",
"stl",
"include",
""
] |
I want to parse an Apache **access.log** file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.
I am going to create a class **ApacheAccessLog**, and the only thing I can imagine now, it will be doing is '**readline**' method. Is it conventionally correct to inherit from the builtin **file** class in this case, so the class will behave just like an instance of the **file** class itself, or not? What is the best way of doing that?
|
In this case I would use *delegation* rather than *inheritance*. It means that your class should contain the file object as an attribute and invoke a `readline` method on it. You could pass a file object in the constructor of the logger class.
There are at least two reasons for this:
1. Delegation reduces coupling, for example in place of file objects you can use any other object that implements a `readline` method (*duck typing* comes handy here).
2. When inheriting from file the public interface of your class becomes unnecessarily broad. It includes all the methods defined on file even if these methods don't make sense in case of Apache log.
|
I am coming from a Java background but I am fairly confident that the same principles will apply in Python. As a rule of thumb you should **never** inherit from a class whose implementation you don't understand and control unless that class has been designed specifically for inheritance. If it has been designed in this way it should describe this clearly in its documentation.
The reason for this is that inheritance can potentially bind you to the implementation details of the class that you are inheriting from.
To use an example from Josh Bloch's book 'Effective Java'
If we were to extend the class `ArrayList` class in order to be able to count the number of items that were added to it during its life-time (not necessarily the number it currently contains) we may be tempted to write something like this.
```
public class CountingList extends ArrayList {
int counter = 0;
public void add(Object o) {
counter++;
super.add(0);
}
public void addAll(Collection c) {
count += c.size();
super.addAll(c);
}
// Etc.
}
```
Now this extension looks like it would accurately count the number of elements that were added to the list but in fact it may not. If `ArrayList` has implemented `addAll` by iterating over the `Collection` provided and calling its interface method `addAll` for each element then we will count each element added through the `addAll` method twice. Now the behaviour of our class is dependent on the implementation details of `ArrayList`.
This is of course in addition to the disadvantage of not being able to use other implementations of `List` with our `CountingList` class. Plus the disadvantages of inheriting from a concrete class that are discussed above.
It is my understanding that Python uses a similar (if not identical) method dispatch mechanism to Java and will therefore be subject to the same limitations. If someone could provide an example in Python I'm sure it would be even more useful.
|
Is it correct to inherit from built-in classes?
|
[
"",
"python",
"inheritance",
"oop",
""
] |
In C# you can use verbatim strings like this:
```
@"\\server\share\file.txt"
```
Is there something similar in JavaScript?
|
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.
I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.
What I did to solve this was as follows:
```
public void Alert(string message)
{
message = message.Replace("\\", "\\\\")
.Replace("\r\n", "\n")
.Replace("\n", "\\n")
.Replace("\t", "\\t")
.Replace("\"", "\\\"");
// and now register my JavaScript with this safe string.
}
```
|
**Template strings** do support line breaks.
```
`so you can
do this if you want`
```
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals>
It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?
> **Note:** I don't think there's a way to take an existing string and run it through expression interpolation. This makes it impossible to inject code this way since the code has to originate in the source. I don't know of an API that can do expression interpolation on-demand.
>
> **Note 2:** Template strings are a ES2015 / ES6 feature. Support in every browser except (wait for it...) IE! However, Edge does support template strings.
>
> **Note 3:** Template strings expand escape sequences, if you have a string inside a string that string will expand its escape sequences.
>
> ```
> `"A\nB"`
> ```
>
> ...will result in:
>
> ```
> "A
> B"
> ```
>
> ...which will not work with `JSON.parse` because there's now a new-line in the string literal. Might be good to know.
|
Does JavaScript support verbatim strings?
|
[
"",
"javascript",
"string",
""
] |
I know you can do it file by file.
Is there any way to do this in one step for all files in a project?
|
Do you mean using statements? First, note that they generally do no harm other that take space.
Tools like [ReSharper](http://www.jetbrains.com/resharper/) offer automated tricks to do this, however: there was a [link in the VS feed](http://blogs.msdn.com/djpark/archive/2008/08/16/organize-usings-across-your-entire-solution.aspx) a little while ago; it boils down to:
* go to Tools -> Macros -> Macros IDE...
* in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings)
* paste over with the code below
* File -> Save MyMacros, exit
Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it).
You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver.
==== code ====
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module OrganiseUsings
Public Sub RemoveAndSortAll()
On Error Resume Next
Dim sol As Solution = DTE.Solution
For i As Integer = 1 To sol.Projects.Count
Dim proj As Project = sol.Projects.Item(i)
For j As Integer = 1 To proj.ProjectItems.Count
RemoveAndSortSome(proj.ProjectItems.Item(j))
Next
Next
End Sub
Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)
On Error Resume Next
If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
window.Activate()
projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")
window.Close(vsSaveChanges.vsSaveChangesYes)
End If
End If
For i As Integer = 1 To projectItem.ProjectItems.Count
RemoveAndSortSome(projectItem.ProjectItems.Item(i))
Next
End Sub
End Module
```
|
There is no need for any plugins in VS 2017, 2019, or 2022. Click the bulb icon near any using statement and click `Solution` next to `Fix all occurrences in` part.
[](https://i.stack.imgur.com/bqi3C.png)
|
Remove unused namespaces across a whole project or solution at once
|
[
"",
"c#",
"namespaces",
""
] |
I am wondering what is the "best practice" to break long strings in C# source code. Is this string
```
"string1"+
"string2"+
"string3"
```
concatenated during compiling or in run time?
|
It's done at compile time. That's exactly equivalent to "string1string2string3".
Suppose you have:
```
string x = "string1string2string3"
string y = "string1" + "string2" + "string3"
```
The compiler will perform appropriate interning such that x and y refer to the same objects.
EDIT: There's a lot of talk about `StringBuilder` in the answers and comments. Many developers seem to believe that string concatenation should *always* be done with `StringBuilder`. That's an overgeneralisation - it's worth understanding [why `StringBuilder` is good in some situations, and not in others](http://pobox.com/~skeet/csharp/stringbuilder.html).
|
If the whitespace isn't important then you can use the @ escape character to write multi-line strings in your code.
This is useful if you have a query in your code for example:
```
string query = @"SELECT whatever
FROM tableName
WHERE column = 1";
```
This will give you a string with line breaks and tabs, but for a query that doesn't matter.
|
Best way to break long strings in C# source code
|
[
"",
"c#",
"string",
""
] |
Suppose I have the following directory layout in a Maven project:
```
src/
|-- main
| |-- bin
| | |-- run.cmd
| | `-- run.sh
| |-- etc
| | |-- common-spring.xml
| | |-- log4j.xml
| | `-- xml-spring.xml
| `-- java
| `-- com
...
```
I would like to build a zip file that, when unzipped, produces something like this:
```
assembly
|-- bin
| |-- run.cmd
| `-- run.sh
|-- etc
| |-- common-spring.xml
| |-- log4j.xml
| `-- xml-spring.xml
`-- lib
|-- dependency1.jar
|-- dependency2.jar
...
```
where `run.xx' are executable shell scripts that will call my main application and *put all dependencies on the classpath*.
Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?
|
I use the [AppAssembler plugin](http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/) to get something similar. Example:
```
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<configuration>
<programs>
<program>
<mainClass>com.acme.MainClass</mainClass>
<name>app</name>
</program>
</programs>
</configuration>
</plugin>
</plugins>
```
|
I've used the maven-assembly-plugin to acheive something similar in a project. I wanted a zip file to be built during the package phase, instead of manually calling assembly:assembly. Here's what I came up with:
/src/assemble/distribution.xml:
```
<assembly>
<id>distribution</id>
<!-- specify the output formats -->
<formats>
<format>zip</format>
</formats>
<!-- include all runtime libraries in the /lib folder of the output file -->
<dependencySets>
<dependencySet>
<outputDirectory>/lib</outputDirectory>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<fileSets>
<!-- include all *.jar files in the target directory -->
<fileSet>
<directory>target</directory>
<outputDirectory></outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
<!-- include all files in the /conf directory -->
<fileSet>
<outputDirectory></outputDirectory>
<includes>
<include>conf/**</include>
</includes>
</fileSet>
</fileSets>
</assembly>
```
/pom.xml
...
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/assemble/distribution.xml
</descriptor>
</descriptors>
</configuration>
<!-- append assembly:assembly to the package phase -->
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
```
...
|
How do I assemble a console application with Maven without unpacking all dependencies?
|
[
"",
"java",
"maven-2",
""
] |
I'm tring to build a library for simplifing late binding calls in C#, and I'm getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call
```
public IInvoker AddParameter(ref object value)
{
//List<object> _parameters = new List<object>();
_parameters.Add(value);
//List<bool> _isRef = new List<bool>();
_isRef.Add(true);
return this;
}
```
And that doesn't work with value types, because they get boxed as an object, thus they are not modified. E.g:
```
int param1 = 2;
object paramObj = param1;
//MulFiveRef method multiplies the integer passed as a reference parameter by 5:
//void MulFiveRef(ref int value) { value *= 5; }
fi.Method("MulFiveRef").AddParameter(ref paramObj);
```
That doesn't work. The late binding call is successful, and the inner List which holds the parameteres (\_parameters ) does get modified, but not the value outside the call.
Does anyone knows a simple way to overcome this limitation?
The AddParameter signature cannot be modified, as with late binding calls, you cannot know in advance the Type of the parameters (and either way you insert all the parameters for a call inside an object array prior to making the call)
Thanks in advance.
|
If the value is changing *inside the method*, you will need to declare a temp (`object`) variable to pass (`ref`) to the method, and unbox it yourself afterwards:
```
int i = 3;
//...
object obj = i;
Foo(ref obj);
i = (int)obj;
```
Note that this will not allow you to update the value after the event. Something like an event or callback might be an alternative way of passing changes back to the caller.
Note also that C# 4.0 has some tricks to help with this *only* in the context of COM calls (where `ref object` is so common [plus of course `dynamic` for late binding, as Jon notes]).
|
Your method isn't changing `value` anyway - why are you passing it by reference? It may make sense, but it's not really clear to me. Note that the sample code you've provided wouldn't compile anyway, as `ref` arguments have to be *exactly* the same type as the parameter.
(Also, are you aware that C# 4.0 and .NET 4.0 will have built-in support for late-binding? Chances are that the language-integrated version will be easier to use than a library-only one. Are you sure it's worth spending time on the library at this point in time?)
EDIT: The code you've provided really won't compile. You don't get boxing for `ref` parameters, precisely because the argument and parameter types have to be exactly the same. Here's some sample code to prove it:
```
public class Test
{
static void Main()
{
int i;
Foo(ref i); // Won't compile - error CS1502/1503
}
static void Foo(ref object x)
{
}
}
```
If your current code *is* compiling, then it's not the code you presented in the question. Perhaps you have another overload for `AddParameter` which accepts `ref int`?
|
How to modify a boxed value type inside a method
|
[
"",
"c#",
"value-type",
"late-binding",
""
] |
Given a method signature:
```
public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)
```
What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.
An example call might be:
```
AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true
```
|
Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example...
```
using System;
using System.Linq.Expressions;
class Test {
public string Foo { get; set; }
public string Bar { get; set; }
static void Main()
{
bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar),
test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar);
}
}
// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with
// generic-type-inference; if you use the doubly-generic method, you need to specify
// both arguments, which is a pain...
static class FuncTest<TSource>
{
public static bool FuncEqual<TValue>(
Expression<Func<TSource, TValue>> x,
Expression<Func<TSource, TValue>> y)
{
return FuncTest.FuncEqual<TSource, TValue>(x, y);
}
}
static class FuncTest {
public static bool FuncEqual<TSource, TValue>(
Expression<Func<TSource,TValue>> x,
Expression<Func<TSource,TValue>> y)
{
return ExpressionEqual(x, y);
}
private static bool ExpressionEqual(Expression x, Expression y)
{
// deal with the simple cases first...
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
if ( x.NodeType != y.NodeType
|| x.Type != y.Type ) return false;
switch (x.NodeType)
{
case ExpressionType.Lambda:
return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body);
case ExpressionType.MemberAccess:
MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y;
return mex.Member == mey.Member; // should really test down-stream expression
default:
throw new NotImplementedException(x.NodeType.ToString());
}
}
}
```
|
**UPDATE:** Due to interest to my solution, I have updated the code so it supports arrays, new operators and other stuff and compares the ASTs in more elegant way.
Here is an improved version of Marc's code and now **it's available as a [nuget package](https://www.nuget.org/packages/Neleus.LambdaCompare/)**:
```
public static class LambdaCompare
{
public static bool Eq<TSource, TValue>(
Expression<Func<TSource, TValue>> x,
Expression<Func<TSource, TValue>> y)
{
return ExpressionsEqual(x, y, null, null);
}
public static bool Eq<TSource1, TSource2, TValue>(
Expression<Func<TSource1, TSource2, TValue>> x,
Expression<Func<TSource1, TSource2, TValue>> y)
{
return ExpressionsEqual(x, y, null, null);
}
public static Expression<Func<Expression<Func<TSource, TValue>>, bool>> Eq<TSource, TValue>(Expression<Func<TSource, TValue>> y)
{
return x => ExpressionsEqual(x, y, null, null);
}
private static bool ExpressionsEqual(Expression x, Expression y, LambdaExpression rootX, LambdaExpression rootY)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
var valueX = TryCalculateConstant(x);
var valueY = TryCalculateConstant(y);
if (valueX.IsDefined && valueY.IsDefined)
return ValuesEqual(valueX.Value, valueY.Value);
if (x.NodeType != y.NodeType
|| x.Type != y.Type)
{
if (IsAnonymousType(x.Type) && IsAnonymousType(y.Type))
throw new NotImplementedException("Comparison of Anonymous Types is not supported");
return false;
}
if (x is LambdaExpression)
{
var lx = (LambdaExpression)x;
var ly = (LambdaExpression)y;
var paramsX = lx.Parameters;
var paramsY = ly.Parameters;
return CollectionsEqual(paramsX, paramsY, lx, ly) && ExpressionsEqual(lx.Body, ly.Body, lx, ly);
}
if (x is MemberExpression)
{
var mex = (MemberExpression)x;
var mey = (MemberExpression)y;
return Equals(mex.Member, mey.Member) && ExpressionsEqual(mex.Expression, mey.Expression, rootX, rootY);
}
if (x is BinaryExpression)
{
var bx = (BinaryExpression)x;
var by = (BinaryExpression)y;
return bx.Method == @by.Method && ExpressionsEqual(bx.Left, @by.Left, rootX, rootY) &&
ExpressionsEqual(bx.Right, @by.Right, rootX, rootY);
}
if (x is UnaryExpression)
{
var ux = (UnaryExpression)x;
var uy = (UnaryExpression)y;
return ux.Method == uy.Method && ExpressionsEqual(ux.Operand, uy.Operand, rootX, rootY);
}
if (x is ParameterExpression)
{
var px = (ParameterExpression)x;
var py = (ParameterExpression)y;
return rootX.Parameters.IndexOf(px) == rootY.Parameters.IndexOf(py);
}
if (x is MethodCallExpression)
{
var cx = (MethodCallExpression)x;
var cy = (MethodCallExpression)y;
return cx.Method == cy.Method
&& ExpressionsEqual(cx.Object, cy.Object, rootX, rootY)
&& CollectionsEqual(cx.Arguments, cy.Arguments, rootX, rootY);
}
if (x is MemberInitExpression)
{
var mix = (MemberInitExpression)x;
var miy = (MemberInitExpression)y;
return ExpressionsEqual(mix.NewExpression, miy.NewExpression, rootX, rootY)
&& MemberInitsEqual(mix.Bindings, miy.Bindings, rootX, rootY);
}
if (x is NewArrayExpression)
{
var nx = (NewArrayExpression)x;
var ny = (NewArrayExpression)y;
return CollectionsEqual(nx.Expressions, ny.Expressions, rootX, rootY);
}
if (x is NewExpression)
{
var nx = (NewExpression)x;
var ny = (NewExpression)y;
return
Equals(nx.Constructor, ny.Constructor)
&& CollectionsEqual(nx.Arguments, ny.Arguments, rootX, rootY)
&& (nx.Members == null && ny.Members == null
|| nx.Members != null && ny.Members != null && CollectionsEqual(nx.Members, ny.Members));
}
if (x is ConditionalExpression)
{
var cx = (ConditionalExpression)x;
var cy = (ConditionalExpression)y;
return
ExpressionsEqual(cx.Test, cy.Test, rootX, rootY)
&& ExpressionsEqual(cx.IfFalse, cy.IfFalse, rootX, rootY)
&& ExpressionsEqual(cx.IfTrue, cy.IfTrue, rootX, rootY);
}
throw new NotImplementedException(x.ToString());
}
private static Boolean IsAnonymousType(Type type)
{
Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();
Boolean nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
private static bool MemberInitsEqual(ICollection<MemberBinding> bx, ICollection<MemberBinding> by, LambdaExpression rootX, LambdaExpression rootY)
{
if (bx.Count != by.Count)
{
return false;
}
if (bx.Concat(by).Any(b => b.BindingType != MemberBindingType.Assignment))
throw new NotImplementedException("Only MemberBindingType.Assignment is supported");
return
bx.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i })
.Join(
by.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { XExpr = xe.Expr, XMember = xe.Member, YExpr = ye.Expr, YMember = ye.Member })
.All(o => Equals(o.XMember, o.YMember) && ExpressionsEqual(o.XExpr, o.YExpr, rootX, rootY));
}
private static bool ValuesEqual(object x, object y)
{
if (ReferenceEquals(x, y))
return true;
if (x is ICollection && y is ICollection)
return CollectionsEqual((ICollection)x, (ICollection)y);
return Equals(x, y);
}
private static ConstantValue TryCalculateConstant(Expression e)
{
if (e is ConstantExpression)
return new ConstantValue(true, ((ConstantExpression)e).Value);
if (e is MemberExpression)
{
var me = (MemberExpression)e;
var parentValue = TryCalculateConstant(me.Expression);
if (parentValue.IsDefined)
{
var result =
me.Member is FieldInfo
? ((FieldInfo)me.Member).GetValue(parentValue.Value)
: ((PropertyInfo)me.Member).GetValue(parentValue.Value);
return new ConstantValue(true, result);
}
}
if (e is NewArrayExpression)
{
var ae = ((NewArrayExpression)e);
var result = ae.Expressions.Select(TryCalculateConstant);
if (result.All(i => i.IsDefined))
return new ConstantValue(true, result.Select(i => i.Value).ToArray());
}
if (e is ConditionalExpression)
{
var ce = (ConditionalExpression)e;
var evaluatedTest = TryCalculateConstant(ce.Test);
if (evaluatedTest.IsDefined)
{
return TryCalculateConstant(Equals(evaluatedTest.Value, true) ? ce.IfTrue : ce.IfFalse);
}
}
return default(ConstantValue);
}
private static bool CollectionsEqual(IEnumerable<Expression> x, IEnumerable<Expression> y, LambdaExpression rootX, LambdaExpression rootY)
{
return x.Count() == y.Count()
&& x.Select((e, i) => new { Expr = e, Index = i })
.Join(y.Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => ExpressionsEqual(o.X, o.Y, rootX, rootY));
}
private static bool CollectionsEqual(ICollection x, ICollection y)
{
return x.Count == y.Count
&& x.Cast<object>().Select((e, i) => new { Expr = e, Index = i })
.Join(y.Cast<object>().Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => Equals(o.X, o.Y));
}
private struct ConstantValue
{
public ConstantValue(bool isDefined, object value)
: this()
{
IsDefined = isDefined;
Value = value;
}
public bool IsDefined { get; private set; }
public object Value { get; private set; }
}
}
```
Note that it does not compare full AST. Instead, it collapses constant expressions and compares their values rather than their AST.
It is useful for mocks validation when the lambda has a reference to local variable. In his case the variable is compared by its value.
Unit tests:
```
[TestClass]
public class Tests
{
[TestMethod]
public void BasicConst()
{
var f1 = GetBasicExpr1();
var f2 = GetBasicExpr2();
Assert.IsTrue(LambdaCompare.Eq(f1, f2));
}
[TestMethod]
public void PropAndMethodCall()
{
var f1 = GetPropAndMethodExpr1();
var f2 = GetPropAndMethodExpr2();
Assert.IsTrue(LambdaCompare.Eq(f1, f2));
}
[TestMethod]
public void MemberInitWithConditional()
{
var f1 = GetMemberInitExpr1();
var f2 = GetMemberInitExpr2();
Assert.IsTrue(LambdaCompare.Eq(f1, f2));
}
[TestMethod]
public void AnonymousType()
{
var f1 = GetAnonymousExpr1();
var f2 = GetAnonymousExpr2();
Assert.Inconclusive("Anonymous Types are not supported");
}
private static Expression<Func<int, string, string>> GetBasicExpr2()
{
var const2 = "some const value";
var const3 = "{0}{1}{2}{3}";
return (i, s) =>
string.Format(const3, (i + 25).ToString(CultureInfo.InvariantCulture), i + s, const2.ToUpper(), 25);
}
private static Expression<Func<int, string, string>> GetBasicExpr1()
{
var const1 = 25;
return (first, second) =>
string.Format("{0}{1}{2}{3}", (first + const1).ToString(CultureInfo.InvariantCulture), first + second,
"some const value".ToUpper(), const1);
}
private static Expression<Func<Uri, bool>> GetPropAndMethodExpr2()
{
return u => Uri.IsWellFormedUriString(u.ToString(), UriKind.Absolute);
}
private static Expression<Func<Uri, bool>> GetPropAndMethodExpr1()
{
return arg1 => Uri.IsWellFormedUriString(arg1.ToString(), UriKind.Absolute);
}
private static Expression<Func<Uri, UriBuilder>> GetMemberInitExpr2()
{
var isSecure = true;
return u => new UriBuilder(u) { Host = string.IsNullOrEmpty(u.Host) ? "abc" : "def" , Port = isSecure ? 443 : 80 };
}
private static Expression<Func<Uri, UriBuilder>> GetMemberInitExpr1()
{
var port = 443;
return x => new UriBuilder(x) { Port = port, Host = string.IsNullOrEmpty(x.Host) ? "abc" : "def" };
}
private static Expression<Func<Uri, object>> GetAnonymousExpr2()
{
return u => new { u.Host , Port = 443, Addr = u.AbsolutePath };
}
private static Expression<Func<Uri, object>> GetAnonymousExpr1()
{
return x => new { Port = 443, x.Host, Addr = x.AbsolutePath };
}
}
```
|
Most efficient way to test equality of lambda expressions
|
[
"",
"c#",
"lambda",
""
] |
I have just moved from phase 1 to phase 2 of a project. In this transition we got rid of all of the XML configuration for spring and struts2, switching to a fully annotated regime.
All of the participants are amazed at the actual effect this has on development speed. There are a number of reasons for this:
* Structured thinking about which roles are needed lead to clear understanding that we needed @StubRepository, @TestService and @NotTestService annotations to facilitate all the different run-time models that our project uses (runtime, unit test, integration test, selenium test)
* These annotations replaced a *large* number of duplicate xml definitions.
* All dependencies are fully trackable in the ide.
* Simpler to work with code because dependencies are clear
Some of these gains could probably have been realized by re-structuring the xml as well, but that would not have been a trivial task.
I honestly believe this has given somewhere around 10% boost in productivity for our 20,000 man hour project. I almost find it hard to believe.
Anyone else sharing this same experience ? What's your gain, and how do you explain it ?
|
Basically, this could be viewed as a question about config files vs. annotation.
If you experienced an amelioration in productivity boost when putting some data as annotations, that means they were not "configuration" material in the first place.
The difference between the two:
* annotation: everything is in one place and the configuration information is associated directly with the Java component. Many types of refactorings of the source code are transparent to annotations for this reason -- the annotations will always apply to the component they're attached to, even when that component is moved or renamed. For other refactorings that require new or modified annotations, everything is in the same location, assuring that the annotations are visible to the developer and increasing the likelihood that they'll remember to make the necessary changes.
* Configuration files can provide an organized view of a web of relationships that span different components of an application. Because they're separate from the actual source code, they don't interfere with the readability of the Java source code.
What you experienced is the disparition of the need to maintain config files in parallel with the source code of an application, with no obvious connection between the two.
BUT: annotations have their drawbacks: source code can become cluttered with all sorts of annotations that are irrelevant to the actual program logic, interfering with the readability of the code. And that while annotations are ideal for metadata that relates to a particular component, they're not well suited to metadata with cross-component application.
|
(I really didn't mean to respond with a bag of cliches, but XML seems to bring out the proverb collection... ;-)
I have found XML configuration (and config files in general, but that's another question) to introduce multiple levels of your question, because, "To a small boy with a hammer, everything looks like a nail." It is easy to become enthusiastic about a tool (such as XML) and start using it much more widely than it deserves, or to keep adding "just one more" feature until the result becomes too unwieldy.
Also, as the old saying goes, "Everything in programming is a trade-off."
So, to play devil's advocate, have you reached the point where you need to do maintenance or tweaks on the running system? In the new scheme of life, how often do you have to make adjustments by re-building all or part of the system, instead of being able to tweak a config file?
Finally, there's rough equivalent of the "Hawthorne effect" (see below). Sometimes a team gets a burst of excitement when they are allowed to clean up some minor issue, and they achieve a burst of productivity out of proportion to the actual improvement, triggered by the relief at getting rid of a long-standing annoyance.
Footnote:
The [Hawthorne effect](http://en.wikipedia.org/wiki/Hawthorne_effect) is named after a study of factory worker productivity relating to changes in lighting. The researchers found that increased light was followed by an increase in productivity. But then they found that ***decreased*** light was also followed by an increase in productivity. (Both increases were typically short-term.) The final conclusion was that the workers were more productive because someone was paying attention to them.
So, sometimes an otherwise trivial change triggers a boost in morale (sense of empowerment, etc.) that causes improvements in performance.
There's seldom just one factor.
|
What are your efficiency gains by removing XML in java projects?
|
[
"",
"java",
"xml",
""
] |
I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler.
I have three tables X, Y, Z defined as
```
CREATE TABLE [dbo].[X](
[ID] [bigint] NOT NULL
)
CREATE TABLE [dbo].[Y](
[ID] [nchar](10) NOT NULL
)
CREATE TABLE [dbo].[Z](
[IDX] [bigint] NOT NULL,
[IDY] [nchar](10) NOT NULL
)
```
They contain the following data
```
Table X Table Y Table Z
ID ID IDX IDY
-- -- --- ---
1 A 1 A
2 B 1 B
3 C 1 A
```
I want to create a query that produces the following result
```
Count IDX IDY
===== === ===
2 1 A
1 1 B
0 1 C
0 2 A
0 2 B
0 2 C
0 3 A
0 3 B
0 3 C
```
My initial thought was
```
SELECT COUNT(*), X.ID, Y.ID
FROM
X
CROSS JOIN Y
FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY
GROUP BY X.ID, Y.ID
```
but this turns out to be on the wrong road.
Any ideas?
|
```
SELECT
(SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID),
X.ID,
Y.ID
FROM
X,Y
```
That's your answer... why do you possibly want that query, no clue :)
|
This seems to work:
```
SELECT COUNT(*) AS CNT, IDX, IDY
FROM Z
GROUP BY IDX, IDY
UNION
SELECT 0, X.ID, Y.ID
FROM X, Y
WHERE NOT EXISTS (
SELECT * FROM Z WHERE Z.IDX = X.ID AND Z.IDY = Y.ID
)
ORDER BY CNT DESC
```
|
Trouble with SQL query with cartesian product
|
[
"",
"sql",
"t-sql",
""
] |
**Original Question**
I am writting a logging class where the goal is to be able to do this:
```
// thread one
Logger() << "Some string" << std::ios::hex << 45;
// thread two
Logger() << L"Some wide string" << std::endl;
```
Currently my Logger header looks something like this:
```
#pragma once;
#include <ostream>
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
};
template <typename T>
Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
```
Some notes about this class:
1. Cross platform compatibility is not an issue.
2. Inside of Logger.cpp there is a singleton class that takes care of creating the "real" ostream.
3. The Logger constructor and deconstructor perform the necessary locking of the singleton.
I have three problems:
* How do I make the operator<< function a friend or member so I can set out\_stream as private?
* How do I make the operator<< function work for manipulators?
* How can I add a specialization so that if T is a WCHAR\* or std::wstring that it will convert it to char\* or std::string before passing it to out\_stream? (I can do the conversion. Losing high unicode characters isn't a problem in my case.)
**Summary of things learned in answers:**
* Put template BEFORE friend instead of after.
* std::ios::hex is not a manipulator. std::hex is a manipulator.
**End Result**
```
#pragma once
#include <ostream>
#include <string>
std::string ConvertWstringToString(std::wstring wstr);
class Logger
{
public:
Logger();
~Logger();
template <typename T>
Logger& operator<< (T data) {
*out << data;
return *this;
}
Logger& operator<< (std::wstring data) {
return *this << ConvertWstringToString(data);
}
Logger& operator<< (const wchar_t* data) {
std::wstring str(data);
return *this << str;
}
private:
std::ostream* out;
};
```
|
You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator<<... syntax):
```
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
template <typename T>
friend Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
/* special treatment for std::wstring. just overload the operator! No need
* to specialize it. */
friend Logger& operator<< (Logger& logger, const std::wstring & wstr) {
/* do something here */
}
};
```
The alternative, to keep your code as it is and just make the operator<< template a friend, you add this line into your class definition:
```
template <typename T>
friend Logger& operator<< (Logger& logger, T thing);
```
For the manipulator problem, i will just give you my code i write some time ago:
```
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename Char, typename Traits = char_traits<Char> >
struct logger{
typedef std::basic_ostream<Char, Traits> ostream_type;
typedef ostream_type& (*manip_type)(ostream_type&);
logger(ostream_type& os):os(os){}
logger &operator<<(manip_type pfn) {
if(pfn == static_cast<manip_type>(std::endl)) {
time_t t = time(0);
os << " --- " << ctime(&t) << pfn;
} else
os << pfn;
return *this;
}
template<typename T>
logger &operator<<(T const& t) {
os << t;
return *this;
}
private:
ostream_type & os;
};
namespace { logger<char> clogged(cout); }
int main() { clogged << "something with log functionality" << std::endl; }
```
};
**Note that it is std::hex , but not std::ios::hex**. The latter is used as a manipulator flag for the `setf` function of streams. Note that for your example, tho, no special treatment of manipulators is required. The above special treatment of std::endl is only needed because i do stream the time in addition when std::endl is used.
|
Using a template is the right way to do it, but you just have to make sure the template is in the **header** file (`logger.h`, or whatever you called), *not* in the implementation file (`logger.cpp`). This will automatically work for any type which has `operator <<` defined with an `std::ostream`. It will also automatically work with stream manipulator objects - those are really just functions which take an `std::ostream` parameter, and `operator <<` just calls the function on the `ostream`.
You can make `operator <<` a friend function as follows:
```
template <typename T> friend Logger& operator<< (Logger& logger, T thing);
```
Specializations are easy - just use template specializations (again, in the header file):
```
template <typename T>
Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
// Template specialization - the "template <>" part is necessary
template <>
Logger& operator<< (Logger& logger, const wchar_t *wstr)
{
// convert wstr to an ANSI string and log it
}
template <>
Logger& operator<< (Logger& logger, const std::wstring & wstr)
{
// convert wstr to an ANSI string and log it
}
```
|
How to overload operator<< that doesn't take or return ostream
|
[
"",
"c++",
"templates",
"operator-overloading",
""
] |
I would like to programatically convert a Microsoft Word document into XHTML. The language of choice is PHP, so I would appreciate any suggestions with PHP.
The initial idea is trying to convert the doc file into odt, and then use the [Odt2Xhtml](http://odt2xhtml.eu.org/index_en.html) PHP class to get it into XHTML format.
Any better way to do this?
|
If you're running Linux one way to go would be to install OpenOffice on the server.
Example instructions for a 'headless' (i.e. no UI) install can be found [here](http://www.oooforum.org/forum/viewtopic.phtml?t=6691).
You could then use a nice CLI app like [unoconv](http://dag.wieers.com/home-made/unoconv/) executed via shell\_exec to do your conversions via PHP.
|
The most robust way is to [use COM to let Word save the document as HTML](http://www.joelonsoftware.com/items/2008/02/19.html).
I don't know whether Word can generate XHTML directly; if not, Google shows [plenty of options](http://www.google.com/search?q=convert+HTML+to+XHTML) for doing that conversion.
|
What is the best way of converting a Microsoft Word document into XHTML?
|
[
"",
"php",
"xhtml",
"ms-word",
""
] |
Can someone show me how to get the `top` & `left` position of a `div` or `span` element when one is not specified?
ie:
```
<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>
```
In the above, if I do:
```
document.getElementById('11a').style.top
```
The value of `55px` is returned. However, if I try that for `span` '12a', then nothing gets returned.
I have a bunch of `div`/`span`s on a page that I cannot specify the `top`/`left` properties for, but I need to display a `div` directly under that element.
|
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
```
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}
```
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
```
var x = el.offsetLeft, y = el.offsetTop;
```
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
```
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
```
|
You can call the method `getBoundingClientRect()` on a reference to the element. Then you can examine the `top`, `left`, `right` and/or `bottom` properties...
```
var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;
```
If using jQuery, you can use the more succinct code...
```
var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;
```
|
Get the position of a div/span tag
|
[
"",
"javascript",
"html",
""
] |
This article [here](http://www.petefreitag.com/articles/gctuning/) suggests to use `-XX:+UseParNewGC` "To enable a parallel young generation GC with the concurrent GC".
My confusion is that in order to enable both parallel and concurrent GC, should I
* use `-XX:+UseParNewGC` or
* use both `-XX:+UseParNewGC` *and* `-XX:+UseConcMarkSweepGC` ?
### PS
I am using JVM 6.
|
Since the document you linked was for a 1.4.2 VM that's what I'll assume you're using (JVMs 5 and 6 behave differently).
From [http://java.sun.com/docs/hotspot/gc1.4.2/](https://web.archive.org/web/20120624153924/http://java.sun.com/docs/hotspot/gc1.4.2/)
> if -XX:+UseConcMarkSweepGC is used on
> the command line then the flag
> UseParNewGC is also set to true if it
> is not otherwise explicitly set on the
> command line
So the answer is you only need to use -XX:+UseConcMarkSweepGC and it will enable the concurrent collector with the parallel young generation collector.
Edit: for Java 6, the same flag (-XX:+UseConcMarkSweepGC) enables the concurrent collector. The choice of collector you want depends on a few things, and you should test different configurations. But there are some very general guidelines. If you have a single processor, single thread machine then you should use the serial collector (default for some configurations, can be enabled explicitly for with -XX:+UseSerialGC). For multiprocessor machines where your workload is basically CPU bound, use the parallel collector. This is enabled by default if you use the -server flag, or you can enable it explicitly with -XX:+UseParallelGC. If you'd rather keep the GC pauses shorter at the expense of using more total CPU time for GC, and you have more than one CPU, you can use the concurrent collector (-XX:+UseConcMarkSweepGC). Note that the concurrent collector tends to require more RAM allocated to the JVM than the serial or parallel collectors for a given workload because some memory fragmentation can occur.
|
This blog entry has a nice breakdown of the different collectors, and which options are valid: <http://blogs.oracle.com/jonthecollector/entry/our_collectors>
|
Java Concurrent and Parallel GC
|
[
"",
"java",
"garbage-collection",
"concurrency",
""
] |
This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.
Here is what I'm doing:
```
this.propertyTypeBindingSource.DataSource = typeof(System.Type);
/* snip */
this.nameTextBox1.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyTypeBindingSource,
"Name", true));
```
Is there some trick with binding to System.Type, is it not allowed or is there any workaround? Have no problems with binding to other types.
|
Found a workaround. Made a class
```
public class StubPropertyType
{
public StubPropertyType(Type type)
{
this.StubPropertyTypeName = type.Name;
}
public string StubPropertyTypeName = string.Empty;
}
```
created a binding source
```
this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);
```
created an instance of the class and bound the textbox to it.
```
this.nameTextBox.DataBindings.Add(
new System.Windows.Forms.Binding(
"Text",
this.propertyStubBindingSource,
"StubPropertyTypeName",
true));
```
works exactly as required.
|
Indeed, there is special treatment of Type... this approach is used in the IDE etc to configure meta-data ahead of time. If you look at IDE-generated bindings, they do things like:
```
bindingSource1.DataSource = typeof(MyObject);
```
saying "when we get real data, we expect MyObject isntance(s)"; i.e. when you ask for "Name", it is looking for the name property *on MyObject* - not the Name of the Type instance. This allows grids etc to obtain their metadata without having to wait for the real data; but as a consequence you can't bind to Type "for real".
The System.ComponentModel code is identical between simple bindings and list bindings (give or take a currency manager), so simple bindings also inherit this behaviour. Equally, you can't bind to properties of a class that implements IList/IListSource, since this is interpreted in a special way.
Your extra class seems a reasonable approach.
|
Cannot bind to the property or column Name on the DataSource. Parameter name: dataMember
|
[
"",
"c#",
"asp.net",
"data-binding",
""
] |
I'm working on a Facebook FBML controls library and would like to create my FBML controls somewhat patterned like the ASP.NET WebControls library. I have a base class that handles rendering by default; here's my render method:
```
protected override void Render(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
if (UseXfbmlSemantics)
{
writer.RenderBeginTag(ElementName);
writer.EndRender();
writer.RenderEndTag();
}
else
{
writer.RenderBeginTag(ElementName);
writer.RenderEndTag();
}
}
```
What I would like is for the rendering to be modified based on UseXfbmlSemantics - if it's true, it should render, for instance:
```
<fb:name uid="10300399458"></fb:name>
```
When it's false, it should render with a self-closing tag:
```
<fb:name uid="10300399458" />
```
I can get the "true" condition to work almost correctly, but the self-closing tag seems to be incompatible with the Render- set of methods. Unfortunately if that's the case it also means that the AddAttributesToRender pattern wouldn't work, either. What it's actually producing is this:
```
<fb:name uid="10300399458">
</fb:name>
```
How can I get HtmlTextWriter (or which HtmlTextWriter do I need to use) to make it render a self-closing tag? Or, at the very least, how can I make it not render that interim space (so that the opening and closing tags are immediately next to one another)?
|
This should get you going - it will render as `<fb:name uid="00101010101"/>`. You could also override the RenderBeginTag, RenderContents, RenderEndTag. Depending on what you are doing there may be some other things going on in RenderControl that you need. You could also look into using a ControlAdapter, this may give you better separation of control functionality VS control html writing.
```
public class FbName:System.Web.UI.WebControls.WebControl
{
protected override string TagName
{
get
{
return "fb:name";
}
}
public override void RenderControl(HtmlTextWriter writer)
{
RenderBeginTag(writer);// render only the begin tag.
//base.RenderContents(writer);
//base.RenderEndTag(writer);
}
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.Write("<" + this.TagName);
writer.WriteAttribute("uid", "00101010101");
writer.Write("/>");
}
}
```
-Jason
|
Since this is the top SO question that comes up when searching for "HtmlTextWriter self closing tag", this is for anyone coming here that wants to know how to do it:
```
writer.WriteBeginTag("tag");
writer.WriteAttribute("attribute", "attribute value");
// ... add other attributes here ...
writer.Write(HtmlTextWriter.SelfClosingTagEnd);
```
|
Render Self-Closing Tag in ASP.NET custom control derived from Control
|
[
"",
"c#",
"asp.net",
"facebook",
"custom-server-controls",
""
] |
Currently, my Objective C classes use C++ objects by doing a `new` when the owner is created, and calling `delete` when it is destroyed. But is there another way? I'd like to be able to declare, say, an `auto_ptr` whose scope lasts the duration of the Objective C class' lifetime.
|
Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects).
Then you get default-like C++ scoping, however I haven't used it much and I've had problems with heavily template code (Boost).
Also I don't think anyone officially supports this besides some good souls working on GCC. So I'd recommend that you unit test anything like this, and keep note that anything could go wrong.
Nevertheless being able to use C++ in objective-C, for me as a C++ person, is a relief and the risks are worth the benefits :)
|
If you have even the slightest hope of retaining what little sanity that we as developers have left you won't do that. It is best to `delete` your C++ objects. In general, while it is safe to mix Objective-C and C++ on a line-by-line basis, do not expect the runtime to support doing something fancy like mixing lifetimes. In general, you can safely destroy your objects when your obj-c class's dealloc is called but other than that, do not expect to mix class scope and not cry.
|
Using C++ from Objective C : how to allocate/deallocate?
|
[
"",
"c++",
"objective-c",
"object",
"scope",
"auto-ptr",
""
] |
From time to time, I run into communications issue with other programmers, when we talk about NULL. Now NULL could be
a NULL pointer
the NUL character
an empty data element in some sort of database.
NUL seems to be the most confusing. It is the ASCII character 0x00.
I tend to use '\0' in my code to represent it. Some developers in my group
tend to prefer to simply use 0, and let the compiler implicitly cast it to a char.
What do you prefer to use for NUL? and why?
|
I use `'\0'` for the nul-character and `NULL` for pointers because it is clearest in both cases.
BTW, both `0` and `'\0'` are `int`s in C and either one will be converted to `char` when stored in a `char` variable.
|
I like the pre-defined *NULL* macro, as it preserves the semantic meaning, rather than some other use of the number 0.
|
How do you deal with NUL?
|
[
"",
"c++",
"c",
""
] |
I recently saw an announcement and [article](http://www.linux.com/feature/150399) outlining the release of the first [Python 3.0](http://www.python.org/download/releases/3.0/) release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.
|
Python 3 is just **not that different** from Python 2.x. In terms of syntax *per se*, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the `print` statement with the `print` function.
Most of the features of Python can be easily probed via introspection (online help, method completion, function signatures, etc.), so there's no reason why any Python IDE will require major changes to work with Python 3.0. I expect IDLE and SPE and the other open-source IDEs will be support it before the final release.
|
Komodo 5 beta 1 was released in October 2008 and has initial support for Python 3 but I don't think I'd be using it for production code yet.
Given that Python 3 is still a very early release candidate, you may have some trouble finding mature support in IDEs.
|
Are there any IDE's that support Python 3 syntax?
|
[
"",
"python",
"syntax",
"ide",
"python-3.x",
""
] |
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:
```
void IndexArray( unsigned int length, std::vector<unsigned int>& v )
{
v.resize(length);
for ( unsigned int i = 0; i < length; ++i )
{
v[i] = i;
}
}
```
But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and **not** using Boost)?
|
You can use the generate algorithm, for a more general way of filling up containers:
```
#include <iostream>
#include <algorithm>
#include <vector>
struct c_unique {
int current;
c_unique() {current=0;}
int operator()() {return ++current;}
} UniqueNumber;
int main () {
vector<int> myvector (8);
generate (myvector.begin(), myvector.end(), UniqueNumber);
cout << "\nmyvector contains:";
for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
```
This was shamelessly lifted and edited from [cplusplusreference](http://www.cplusplus.com/reference/algorithm/generate.html).
|
I usually go with `std::generate` plus a simple generator:
```
template <typename T>
struct gen {
T x;
gen(T seed) : x(seed) { }
T operator ()() { return x++; }
};
generate(a.begin(), a.end(), gen<int>(0));
```
|
How to fill a vector with non-trivial initial values?
|
[
"",
"c++",
"stl",
""
] |
Say I have an array of strings in a php array called $foo with a few hundred entries, and I have a MySQL table 'people' that has a field named 'name' with a few thousand entries. What is an efficient way to find out which strings in $foo aren't a 'name' in an entry in 'people' without submitting a query for every string in $foo?
So I want to find out what strings in $foo have not already been entered in 'people.'
Note that it is clear that all of the data will have to be on one box at one point. The goal would be doing this at the same time minimizing the number of queries and the amount of php processing.
|
```
CREATE TEMPORARY TABLE PhpArray (name varchar(50));
-- you can probably do this more efficiently
INSERT INTO PhpArray VALUES ($foo[0]), ($foo[1]), ...;
SELECT People.*
FROM People
LEFT OUTER JOIN PhpArray USING (name)
WHERE PhpArray.name IS NULL;
```
|
I'd put your $foo data in another table and do a LEFT OUTER JOIN with your names table. Otherwise, there aren't a lot of great ways to do this that don't involve iteration at some point.
|
How do I filter a php array with a MySQL table?
|
[
"",
"php",
"mysql",
""
] |
According to the [PHP manual](https://www.php.net/manual/en/function.get-magic-quotes-gpc.php), in order to make code more portable, they recommend using something like the following for escaping data:
```
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
```
I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql\_real\_escape\_string().
|
Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $\_GET/$\_POST/$\_COOKIES/$\_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.
The PHP [man page on magic quotes](http://php.net/magic_quotes) agrees:
> "This feature has been DEPRECATED as
> of PHP 5.3.0 and REMOVED as of PHP
> 5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a
> process that automagically escapes
> incoming data to the PHP script. It's
> preferred to code with magic quotes
> off and to instead escape the data at
> runtime, as needed."
|
Magic quotes were a design error. Their use is incompatible with retainnig your sanity.
I prefer:
```
if (get_magic_quotes_gpc()) {
throw new Exception("Turn magic quotes off now!");
}
```
Don't write code for compatibility with inherently broken setups. Instead defend aginst their use by having your code [FAIL FAST](http://en.wikipedia.org/wiki/Fail-fast).
|
Magic quotes in PHP
|
[
"",
"php",
"security",
"magic-quotes",
""
] |
When would you call Java's `thread.run()` instead of `thread.start()`?
|
You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.
|
Never. Calling run() directly just executes the code synchronously (in the same thread), just like a normal method call.
|
When would you call java's thread.run() instead of thread.start()?
|
[
"",
"java",
"multithreading",
"concurrency",
""
] |
Working on a project where a sequential set of methods must be run every `x` seconds. Right now I have the methods contained within another "parent method", and just sequentially call them right after another.
```
class DoTheseThings()
{
DoThis();
NowDoThat();
NowDoThis();
MoreWork();
AndImSpent();
}
```
Each method must run successfully without throwing an exception before the next step can be done. So now I wrapped each of those methods with a `while` and `try..catch`, then in the `catch` execute that method again.
```
while( !hadError )
{
try
{
DoThis();
}
catch(Exception doThisException )
{
hadError = true;
}
}
```
This seems smelly and not very dry. Is there a better way to do this so I'm not wrapping any new functionality in the same methods. Isn't some kind of Delegate collection the proper way to implement this?
Is there a more "proper" solution?
|
```
Action[] work=new Action[]{new Action(DoThis), new Action(NowDoThat),
new Action(NowDoThis), new Action(MoreWork), new Action(AndImSpent)};
int current =0;
while(current!=work.Length)
{
try
{
work[current]();
current++;
}
catch(Exception ex)
{
// log the error or whatever
// maybe sleep a while to not kill the processors if a successful execution depends on time elapsed
}
}
```
|
> Isn't some kind of Delegate collection the proper way to implement this?
Delegate is a possible way to solve this problem.
Just create a delegate something like:
> public delegate void WorkDelegate();
and put them in arraylist which you can iterate over.
|
What is the best way to execute sequential methods?
|
[
"",
"c#",
"exception",
"delegates",
""
] |
How would I be able to programmatically search and replace some text in a large number of PDF files? I would like to remove a URL that has been added to a set of files. I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains. I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.
|
Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file. That said, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF) has some search-replace capabilities and heuristics. Give [changepagestring.pl](http://search.cpan.org/dist/CAM-PDF/bin/changepagestring.pl) a try and see if it works on your PDFs.
To install:
```
$ cpan install CAM::PDF
# start a new terminal if this is your first cpan module
$ changepagestring.pl input.pdf oldtext newtext output.pdf
```
|
I have also become desperate. After 10 PDF Editor installations which all cost money, and no success:
pdftk + editor suffice:
**Replace Text in PDF Files**
* Use pdftk to uncompress PDF page streams
```
pdftk original.pdf output original.uncompressed.pdf uncompress
```
* Replace the text (sometimes this
works, sometimes it doesn't) within `original.uncompressed.pdf`
* Repair the modified (and now broken)
PDF
```
pdftk original.uncompressed.pdf output original.uncompressed.fixed.pdf
```
> (from Joel Dare)
|
How to program a text search and replace in PDF files
|
[
"",
"javascript",
"pdf",
"replace",
""
] |
I followed the commonly-linked tip for reducing an application to the system tray : <http://www.developer.com/net/csharp/article.php/3336751> Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.
Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.
I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.
Any ideas ?
Thanks
|
In your main program you probably have a line of the form:
```
Application.Run(new Form1());
```
This will force the form to be shown. You will need to create the form but *not* pass it to `Application.Run`:
```
Form1 form = new Form1();
Application.Run();
```
Note that the program will now not terminate until you call `Application.ExitThread()`. It's best to do this from a handler for the `FormClosed` event.
```
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.ExitThread();
}
```
|
this is how you do it
```
static class Program
{
[STAThread]
static void Main()
{
NotifyIcon icon = new NotifyIcon();
icon.Icon = System.Drawing.SystemIcons.Application;
icon.Click += delegate { MessageBox.Show("Bye!"); icon.Visible = false; Application.Exit(); };
icon.Visible = true;
Application.Run();
}
}
```
|
Put a program in the system tray at startup
|
[
"",
"c#",
".net",
"vb.net",
""
] |
Can I utilise the new functionality provided by the new JavaFX APIs directly from Java to the same extent as I would be able to using JavaFX Script?
Are all the underlying JavaFX APIs purely Java or JavaFX Script or a mix?
|
The JavaFX APIs are a mix of JavaFX and Java. The SDK comes with an archive src.zip which contains a part of the APIs (only the most basic classes are included, but things like javafx.scene are missing).
Calling JavaFX code from Java is not officially supported in JavaFX 1.x AFAIK. There's a [blog entry in the JavaFX blog](http://blogs.oracle.com/javafx/entry/how_to_use_javafx_in) that shows you how to do anyway it using unsupported APIs, but it's complicated and won't work this way in future versions.
There are two supported ways to use JavaFX from Java. Either you use the Scripting API to invoke JavaFX code, as shown in [this article](http://java.dzone.com/news/calling-javafx-from-java). Or, which is the most elegant solution IMHO, write the API-accessing code using JavaFX, define Java interfaces to interact with your JavaFX code from plain Java, and then implement those interfaces in JavaFX.
|
The scenegraph used in JavaFX is opensource. You can check it here (<https://scenegraph.dev.java.net>). While the site hasn't been updated to reflect the final version shipped with JavaFX 1.x, you can still use the jar that comes with the JavaFX SDK and mix scenegraph and swing nodes inside your swing application. However, you'll have some difficulty because there's no official API for this version of scenegraph.
Here's a "hello world" using the scenegraph that comes woth JavaFX 1.0. Remember to include the "Scenario.jar" in your build path.
```
import java.awt.Color;
import java.awt.Paint;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.sun.scenario.scenegraph.JSGPanel;
import com.sun.scenario.scenegraph.SGGroup;
import com.sun.scenario.scenegraph.fx.FXText;
public class HelloWorldScenario101 implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new HelloWorldScenario101());
}
public HelloWorldScenario101() {
//
}
@Override
public void run() {
this.frame = new JFrame();
this.panel = new JSGPanel();
this.text = new FXText();
this.paint = new Color(255, 0, 0, 255);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World");
frame.add(this.panel);
frame.setContentPane(this.panel);
scene = new SGGroup();
this.text.setText("Hello World");
this.text.setFillPaint(this.paint);
this.text.setLocation(new Point2D.Float(10, 10));
this.scene.add(this.text);
this.panel.setScene(scene);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JFrame frame;
private JSGPanel panel;
private SGGroup scene;
private FXText text;
private Paint paint;
}
```
|
JavaFX and Java Interoperability
|
[
"",
"java",
"api",
"interop",
"javafx",
""
] |
In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.
But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?
The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.
|
From [detecting Internet Explorer More Effectively](http://msdn.microsoft.com/en-us/library/ms537509.aspx) at msdn:
```
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 6.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
```
|
If you really want to be sure you are using IE and a specific version then you could obviously use IE's conditional tags to only run certain code within IE. It's not really that pretty but at least you can be sure that it is really IE and not some spoofed version.
```
<script>
var isIE = false;
var version = -1;
</script>
<!--[if IE 6]>
<script>
isIE = true;
version = 6
</script>
<![endif]-->
<!--[if IE 7]>
<script>
isIE = true;
version = 7
</script>
<![endif]-->
```
It's pretty self explanatory. In IE6 `isIE` is `true` and `version` is `6`, In IE7 `isIE` is `true` and `version` is `7` otherwise `isIE` is false and `version` is `-1`
Alternatively you could just roll your own solution using code plagarised from jQuery.
```
var userAgent = navigator.userAgent.toLowerCase();
var version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
var isIE = /msie/.test( userAgent ) && !/opera/.test( userAgent ),
```
|
How can I determine which version of IE a user is running in JavaScript?
|
[
"",
"javascript",
"internet-explorer",
"browser",
""
] |
If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"
```
//some logic that sets bool values
boolean X = true;
boolean Y = true;
if (X & Y){
// perform some operation
}
if (X && Y){
// perform some operation
}
```
Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?
|
As has been observed, `&` is the bitwise AND operator. Raw binary math is seeming to be less and less common over time, with an increasing number of developers not really understanding bitwise arithmetic. Which can be a pain at times.
However there are a lot of tasks that are best solved with such, in particular anything that looks at data as flags. The `&` operator is 100% necessary, and isn't going anywhere - it simply isn't used as frequently as the boolean short-circuiting `&&` operator.
For example:
```
[Flags]
enum SomeEnum { // formatted for space...
None = 0, Foo = 1, Bar = 2 // 4, 8, 16, 32, ...
}
static void Main() {
SomeEnum value = GetFlags();
bool hasFoo = (value & SomeEnum.Foo) != 0;
}
static SomeEnum GetFlags() { ... }
```
|
Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'. It make work like a logic test in some cases but it is not guaranteed to work for all logic cases. The most common use of a single & is when applying a bit-mask.
Examples (&&):
```
true && true == true
```
Example (&):
```
00101001 & 00100001 = 00100001
```
|
Is there a time when && (AndAlso) does not matter over & (And)
|
[
"",
"c#",
"boolean-logic",
""
] |
I have in my Form constructor, after the InitializeComponent the following code:
```
using (WebClient client = new WebClient())
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync("http://example.com/version.txt");
}
```
When I start my form, the UI doesn't appears till client\_DownloadDataCompleted is raised.
The client\_DownloadDataCompleted method is empty, so there's no problem there.
What I'm doing wrong?
How is supposed to do this without freezing the UI?
Thanks for your time.
Best regards.
**FULL CODE:**
**Program.cs**
```
using System;
using System.Windows.Forms;
namespace Lala
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
```
**Form1.cs**
```
using System;
using System.Net;
using System.Windows.Forms;
namespace Lala
{
public partial class Form1 : Form
{
WebClient client = new WebClient();
public Form1()
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(new Uri("http://www.google.com"));
InitializeComponent();
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
textBox1.Text += "A";
}
}
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 41);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(468, 213);
this.textBox1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
}
}
```
|
Now that we've got full code, I can say I'm definitely not seeing the problem - not quite as described, anyway.
I've got a bit of logging to indicate just before and after the DownloadDataAsync calls, and when the completed handler is fired. If I download a large file over 3G, there *is* a pause between "before" and "after" but the UI comes up ages before the file completes downloading.
I have a suspicion that the *connect* is done synchronously, but the actual download is asynchronous. That's still unfortunate, of course - and possibly punting all of that into a different thread is the way to go - but if I'm right it's at least worth knowing about.
|
Encountered the same problem, and found a solution.
Quite complex discussion here:
<http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl>
In short, the problem is web client is searching for proxy servers and hanging the app.
The following solution helps:
```
WebClient webClient = new WebClient();
webClient.Proxy = null;
... Do whatever else ...
```
|
WebClient.DownloadDataAsync is freezing my UI
|
[
"",
"c#",
".net",
"webclient",
""
] |
I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
```
|
The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies.
|
The buttons need to be created *before* the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.
As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event will know it needs to run.
Alternatively, you could place the buttons on the page statically. Just put enough there to handle whatever the search returns. If you're thinking that maybe that would be *way* too many items, then ask your self this: will your users really want to sort through that many items? Maybe you should consider paging this data, in which case static buttons aren't as big a deal any more.
|
How can I create buttons and hook up events from postback
|
[
"",
"c#",
".net",
"asp.net",
"events",
"postback",
""
] |
I am trying to set the background color of a DataGridView row to red. I tried with the following line:
dgvActiveCalls.Rows[1].DefaultCellStyle.BackColor = Color.Red;
but it doesn't work. Then just to see if something is wrong with update I tried to paint the column instead of row:
dgvActiveCalls.Columns[1].DefaultCellStyle.BackColor = Color.Red;
and it worked fine. I would be really thankful if anyone could show the way to paint the DataGridView row.
Thanks!
|
Make sure that the default style isn't being overriden by another of the styles. Interesting quirk of DGV in 2.0: Seems like the inheritence chain is almost upside down from what you'd expect. If you are dynamically adding columns, your DefaultCellStyle can be ignored and be overridden by the RowsDefaultCellStyle. Sorting can also override styles you've set.
You might want to check in which order you're setting these styles and google for some articles regarding style inheritence.
P.S. Interestingly enough, I googled to find a link to provide, and came across this blog with an almost identical explanation:
<http://yakkowarner.blogspot.com/2008/06/datagridview-style-inheritance.html>
|
I tested that on my machine and it worked fine. Are you sure that line isn't highlighted? If it's highlighted you'll see the highlighted color, not the red.
|
painting DataGridView Row
|
[
"",
"c#",
"datagridview",
""
] |
I'e been programming Java forever, but have been away from it for a while. Can anyone recommend a really good Java reference, where "really good" is defined by "Good coverage of the language, detailed coverage of recent extensions, and written for the technical reader (not a "for Dummies" sort of book)"?
|
As well as references saying what has changed in the languages (which other answers already cover better than I could) I can't recommend highly enough the [Second edition of Effective Java by Joshua Bloch](https://rads.stackoverflow.com/amzn/click/com/0321356683) - which explains the most effective ways of using the language.
|
For anything to do with concurrency, get [Java Concurrency In Practice](http://www.javaconcurrencyinpractice.com/).
As well as helping you avoid most of the many nasty pitfalls awaiting you, it gives a very good treatment of the new [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-frame.html) API memebers for Java 5 and 6.
|
RECENT Java References?
|
[
"",
"java",
"reference",
""
] |
I'm not looking for the usual answer like Web-services. I'm looking for a light solution to be run in the same machine.
Edit: I'm looking for way in Java to call .NET methods
|
I believe Java can talk to COM and .NET can expose COM interfaces. So that may be a very light weight solution that doesn't require any 3rd party. There is also the option of using sockets to communicate between the programs which wouldn't require a heavy instance of IIS to be installed on the machine.
|
I am author of [jni4net](http://jni4net.sf.net/), open source interprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.
|
How can I call .NET code from Java?
|
[
"",
"java",
".net",
"cross-platform",
""
] |
Are there limits or performance penalties on the amount of code inside of my `home.cs` form?
I am writing a database application front-end in C# in Visual Studio 2008. The way things are lining up, I am using a tab-page way of changing the info shown to the end users, instead of using new forms.
Coming from VBA/MS Access, I remember that if you go over a certain number of lines of code, it would produce an error and not compile. Will C# do this in Visual Studio 2008, or will I suffer a performance hit? I know code readability could be a problem because everything would be in one place, but I can also see that as an advantage in some situations.
|
It's not the lines of code in your .cs files that you need to be worried about with regards to performance - it's the number of controls on your form at runtime that might cause problems. If it's just a few controls on a few tabs, you will have no problems. If it's hundreds of controls on lots of tabs, you may have performance problems (not to mention usability problems - I personally hate tab controls with more than one row of tabs).
Also, I don't think tabs are appropriate if the purpose of the UI is more wizard-like where you want the user to interact with all of the tabs in succession. Tabs are meant for presenting sets of options to the user, without requiring them to see all the options at once.
Finally, if the purpose of each tab is significantly different, I find that it's easier to encapsulate each bit of functionality as a separate form. With tabs, you could at least encapsulate each bit as usercontrols, and then have each tab on your form host one instance of a usercontrol.
|
The only problem i would foresee is that in the future its going to be very hard to maintain.
Try break the logic of that main form up as much as possible into classes so that when you need add something you can actually do it without having a fit.
|
C# penalty for number of lines of code?
|
[
"",
"c#",
"performance",
"lines-of-code",
""
] |
Is there a way to find the size of a file object that is currently open?
Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.
|
```
$ ls -la chardet-1.0.1.tgz
-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz
$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('chardet-1.0.1.tgz','rb')
>>> f.seek(0, os.SEEK_END)
>>> f.tell()
179218L
```
Adding ChrisJY's idea to the example
```
>>> import os
>>> os.fstat(f.fileno()).st_size
179218L
>>>
```
**Note**: Based on the comments, `f.seek(0, os.SEEK_END)` is must before calling `f.tell()`, without which it would return a size of 0. [The reason is that `f.seek(0, os.SEEK_END)` moves the file object's position to the end of the file.](https://stackoverflow.com/questions/283707/size-of-an-open-file-object#comment53321883_283719)
|
Well, if the file object support the tell method, you can do:
```
current_size = f.tell()
```
That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file.
Otherwise, you can use the file system capabilities, i.e. `os.fstat` as suggested by others.
|
Size of an open file object
|
[
"",
"python",
"file",
"file-io",
"filesize",
"tarfile",
""
] |
What memory leak detection tools are available for use with open source C/C++ on Windows?
|
The [mem (revised)](http://teaching.idallen.com/c_programming/mem/) package is an effective and straightforward tool to detect memory buffer overflows, underflows, leaks, double-deletion, and dangling references.
[Original link to c.snippets.org, now invalid.](http://c.snippets.org/browser.php?sect=37#37)
|
I've been using VLD ([Visual Leak Detector](http://www.codeproject.com/KB/applications/visualleakdetector.aspx)) for some times, it works nicely for good code, for more complex code; it's not perfect.
|
Memory leak detection under Windows for GNU C/C++
|
[
"",
"c++",
"windows",
"open-source",
"memory-leaks",
""
] |
I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:
```
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("eire","hispaniola");
```
and thats it.
Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that.
Thank you.
|
This builds on @sgehrig's answer, but note the change in your exceptions:
```
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("the eire","the hispaniola");
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The ' . $country;
} else if (in_array($countryKey, $exceptions)) {
$country = substr($country, 4);
}
```
|
```
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The' . $country;
} else if (in_array($countryKey, $exceptions) && stripos($country, 'the ') === 0) {
$country = substr($country, 4);
}
```
|
Add / Remove the word 'The' to specific countries
|
[
"",
"php",
""
] |
I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.
For example if I have the URL: `http://localhost/proxy.php?user name=Max`
the browser will convert it to `http://localhost/proxy.php?user%20name=Max`.
But if I give the $\_GET parameters out, the key is not `user name` but `user_name` (note the underscore)!
Is there any possibility to change this behaviour?
|
From the [PHP manual](http://www.php.net/manual/en/language.variables.external.php):
> Dots in incoming variable names
>
> Typically, PHP does not alter the
> names of variables when they are
> passed into a script. However, it
> should be noted that the dot (period,
> full stop) is not a valid character in
> a PHP variable name. For the reason,
> look at it:
>
> ```
> <?php $varname.ext; /* invalid variable name */ ?>
> ```
>
> Now, what
> the parser sees is a variable named
> $varname, followed by the string
> concatenation operator, followed by
> the barestring (i.e. unquoted string
> which doesn't match any known key or
> reserved words) 'ext'. Obviously, this
> doesn't have the intended result.
>
> For this reason, it is important to
> note that PHP will automatically
> replace any dots in incoming variable
> names with underscores.
And a comment on the page:
> The full list of field-name characters that PHP converts to \_ (underscore) is the following (not just dot):
>
> ```
> chr(32) ( ) (space)
> chr(46) (.) (dot)
> chr(91) ([) (open square bracket)
> chr(128) - chr(159) (various)
> ```
>
> PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register\_globals feature.
|
I think the only possibility to get the wanted parameters, is to parse them on your own using `$_SERVER['QUERY_STRING']`:
```
$a_pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($a_pairs AS $s_pair){
$a_pair = explode('=', $s_pair);
if(count($a_pair) == 1) $a_pair[1] = '';
$a_pair[0] = urldecode($a_pair[0]);
$a_pair[1] = urldecode($a_pair[1]);
$GLOBALS['_GET'][$a_pair[0]] = $a_pair[1];
$_GET[$a_pair[0]] = $a_pair[1];
}
```
|
PHP replaces spaces with underscores
|
[
"",
"php",
""
] |
In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only?
Using **DATEDIFF(YEAR, DateOfBirth, GETDATE())** does not work as this only looks at the year part of the date. For example **DATEDIFF(YEAR, '31 December 2007', '01 January 2008')** returns 1.
|
Check out this article: [How to calculate age of a person using SQL codes](http://www.kodyaz.com/articles/calculate-age-sql-code.aspx)
Here is the code from the article:
```
DECLARE @BirthDate DATETIME
DECLARE @CurrentDate DATETIME
SELECT @CurrentDate = '20070210', @BirthDate = '19790519'
SELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) > (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END
```
|
There is another way that is a bit simpler:
```
Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
```
Because the rounding here is very granular, this is *almost* perfectly accurate. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one year too young if we A) ask for the age before 6:00 AM, B) on the person's birthday and C) their birthday is after February 28th. In my setting, this is a perfectly acceptable compromise.
|
Finding someone's age in SQL
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.
In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to \*.\*. Then, if I select a file that has the .char extension, it won't load, giving the error
> ```
> unpickle_file = cPickle.load(char_file)
> ```
>
> ValueError: could not convert string to float
However, if I create a file that doesn't have the .char extension, that file will load up just fine.
In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.
---
**Edit** Here's the save code:
```
def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
```
Here's the open code:
```
def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
```
|
Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data.
To open a file in binary mode you have to provide "b" as part of the mode string:
```
char_file = open('pickle.char', 'rb')
```
|
As mentioned by [Adam](https://stackoverflow.com/questions/283766/pickled-file-wont-load-on-maclinux#283802), the problem is likely to be the newline format of the pickle file.
Unfortunately, the real problem is actually caused on *save* rather than load. This may be recoverable if you're using text mode pickles, rather than binary. Try opening the file in universal newline mode, which will cause python to guess what the right line-endings are ie:
```
char_file=open('filename.char','rU')
```
However, if you're using a binary format (cPickle.dump(file, 1)) you may have an unrecoverably corrupted pickle (even when loading in Windows) - if you're lucky and no \r\n characters show up then it may work, but as soon as this occurs you could end up with corrupted data, as there's no way to distinguish between a "real" \r\n code and one windows has inserted on seeing just \n.
The best way to handle things to be loaded in multiple platforms is to always save in binary mode. On your windows machine, when saving the pickle use:
```
char_file = open('filename.char','wb')
cPickle.dumps(data, char_file)
```
|
Pickled file won't load on Mac/Linux
|
[
"",
"python",
"linux",
"macos",
"cross-platform",
""
] |
I know that python has a `len()` function that is used to determine the size of a string, but I was wondering why it's not a method of the string object?
|
Strings do have a length method: `__len__()`
The protocol in Python is to implement this method on objects which have a length and use the built-in [`len()`](http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-45) function, which calls it for you, similar to the way you would implement `__iter__()` and use the built-in `iter()` function (or have the method called behind the scenes for you) on objects which are iterable.
See [Emulating container types](http://www.python.org/doc/2.5.2/ref/sequence-types.html) for more information.
Here's a good read on the subject of protocols in Python: [Python and the Principle of Least Astonishment](http://lucumr.pocoo.org/2011/7/9/python-and-pola/)
|
Jim's answer to [this question](https://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python) may help; I copy it here. Quoting Guido van Rossum:
> First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwined reasons actually, both HCI:
>
> (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x\*(a+b) into x\*a + x\*b to the clumsiness of doing the same thing using a raw OO notation.
>
> (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
>
> Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
|
Why does Python code use len() function instead of a length method?
|
[
"",
"python",
""
] |
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.
My question is: **Is there a way to access this object in the default-package from a Java-class in a named package?**
|
[You can’t use](http://mindprod.com/jgloss/import.html) classes in the default package from a named package.
(*Technically* you can, as shown in Sharique Abdullah's [answer](https://stackoverflow.com/a/561183/6309) through reflection API, *but* classes from the unnamed namespace are **not in scope** in an **import declaration**)
Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:
```
import Unfinished;
```
That's [no longer allowed](https://bugs.java.com/bugdatabase/view_bug?bug_id=4989710). So to access a default package class from within a packaged class requires moving the default package class into a package of its own.
If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.
---
Update 2014: [bug 6975015](https://bugs.openjdk.java.net/browse/JDK-6975015), for JDK7 and JDK8, describe an even *stricter* prohibition against import from unnamed package.
> The `TypeName` must be the canonical name of a class type, interface type, enum type, or annotation type.
> The type must be either a member of a **named package**, or a member of a type whose outermost lexically enclosing type is a member of a **named package**, **or a compile-time error occurs**.
---
[Andreas](https://stackoverflow.com/users/5221149/andreas) points out [in the comments](https://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package/283828#comment98446842_283828):
> > "why is [the default package] there in the first place? design error?"
>
> No, it's deliberate.
> [JLS 7.4.2. Unnamed Packages](https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4.2) says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".
|
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
```
Class fooClass = Class.forName("FooBar");
Method fooMethod = fooClass.getMethod("fooMethod", String.class);
String fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), "I did it");
```
|
How to access java-classes in the default-package?
|
[
"",
"java",
"groovy",
"default-package",
""
] |
How can I get rid of:
```
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..."/>
```
Completely !
|
You need to add the EnableViewState="false" to the @Page directive in the Default.aspx file.
```
<%@ Page Language="C#" AutoEventWireup="true"
Codebehind="Default.aspx.cs" Inherits="Sample._Default"
EnableViewState="false" %>
```
Then, add the following code to the Default.aspx.cs file. This removes the hidden field from the generated HTML.
```
#region Disable ViewState
protected override void SavePageStateToPersistenceMedium(object state)
{
}
protected override object LoadPageStateFromPersistenceMedium()
{
return null;
}
#endregion
```
|
At the control level, EnableViewState="false".
At the page level, EnableViewState=false in the Page directive.
At the applicaiton level add this to .config, < pages enableViewState="false" >
|
How to get rid of View State completely in .NET
|
[
"",
"c#",
".net",
"asp.net",
""
] |
I can't figure out why the following wont work, any ideas??
```
public interface IFieldSimpleItem
{ }
public interface IFieldNormalItem : IFieldSimpleItem
{ }
public class Person
{
public virtual T Create<T>()
where T : IFieldSimpleItem
{
return default(T);
}
}
public class Bose : Person
{
public override T Create<T>()
where T : IFieldNormalItem //This is where the error is
{
return default(T);
}
}
```
The reason why I am doing this is due to the fact that if a developer inherits from Bose, Bose relies on the instance being creating being at least of `IFieldNormalItem`. Whereas the below only relies on it being `IFieldSimpleItem` but the above should force it to be at least `IFieldNormalItem`.
```
public class Person
{
public virtual IFieldSimpleItem Create()
{
return null;
}
}
public class Bose : Person
{
public override IFieldSimpleItem Create()
{
return null;
}
}
```
Cheers
Anthony
|
I'm pretty sure you're out of luck as far as using the compiler and generics to save you some runtime checks. You can't override something that doesn't already exist, and you can't have different return types to the same methods.
I can't say I completely understand your motivation, but it has technical merit.
My first attempt was using the base class having a Non-Virtual public interface, and then having another protected virtual method `CheckCreatedType` that would allow anything in the chain to inspect the type before the base class Create was called.
```
public class A
{
public IFieldSimpleItem Create()
{
IFieldSimpleItem created = InternalCreate();
CheckCreatedType(created);
return created;
}
protected virtual IFieldSimpleItem InternalCreate()
{
return new SimpleImpl();
}
protected virtual void CheckCreatedType(IFieldSimpleItem item)
{
// base class doesn't care. compiler guarantees IFieldSimpleItem
}
}
public class B : A
{
protected override IFieldSimpleItem InternalCreate()
{
// does not call base class.
return new NormalImpl();
}
protected override void CheckCreatedType(IFieldSimpleItem item)
{
base.CheckCreatedType(item);
if (!(item is IFieldNormalItem))
throw new Exception("I need a normal item.");
}
}
```
The following sticks in runtime checking at the base class. The unresolvable issue is you still have to rely on the base class method being called. A misbehaving subclass can break all checks by not calling `base.CheckCreatedType(item)`.
The alternatives are you hardcode all the checks for all subclasses inside the base class (bad), or otherwise externalize the checking.
Attempt 2: (Sub)Classes register the checks they need.
```
public class A
{
public IFieldSimpleItem Create()
{
IFieldSimpleItem created = InternalCreate();
CheckCreatedType(created);
return created;
}
protected virtual IFieldSimpleItem InternalCreate()
{
return new SimpleImpl();
}
private void CheckCreatedType(IFieldSimpleItem item)
{
Type inspect = this.GetType();
bool keepgoing = true;
while (keepgoing)
{
string name = inspect.FullName;
if (CheckDelegateMethods.ContainsKey(name))
{
var checkDelegate = CheckDelegateMethods[name];
if (!checkDelegate(item))
throw new Exception("failed check");
}
if (inspect == typeof(A))
{
keepgoing = false;
}
else
{
inspect = inspect.BaseType;
}
}
}
private static Dictionary<string,Func<IFieldSimpleItem,bool>> CheckDelegateMethods = new Dictionary<string,Func<IFieldSimpleItem,bool>>();
protected static void RegisterCheckOnType(string name, Func<IFieldSimpleItem,bool> checkMethod )
{
CheckDelegateMethods.Add(name, checkMethod);
}
}
public class B : A
{
static B()
{
RegisterCheckOnType(typeof(B).FullName, o => o is IFieldNormalItem);
}
protected override IFieldSimpleItem InternalCreate()
{
// does not call base class.
return new NormalImpl();
}
}
```
The check is done by the subclass registering a delegate to invoke in base class, but without the base class knowing all the rules upfront. Notice too that it's still the Non-Virtual public interface which allows the base class to check the results before returning them.
I'm assuming that it's a developer error that you're trying to catch. If it's applicable, you can adorn the runtime check method with `System.Diagnostics.Conditional("DEBUG")]`, allowing the Release version to skip the checks.
My knowledge of generics isn't perfect, so maybe this is unnecessary. However the checks here don't have to be for type alone: this could be adapted for other uses. e.g. the delegate passed in `Register..` doesn't have to just check the reference is a specific type'
\* Note that it's probably not good to create the dictionary on the type name as written above; this working is a little simplistic in order to illustrate the mechanism used.
|
That's not allowed because it violates Liskov Substitution Principle.
Let's say you have another interface:
```
public interface IFieldSuperItem : IFieldSimpleItem
```
You then might do this
```
Person p = new Boss();
p.Create<IFieldSuperItem>();
```
The call in second line, while compatible with the definition of Create in Person but obviously not compatible to that defined in Boss (which only work with IFieldNormalItem and its subclass).
|
"Constraints for explicit interface implementation..."
|
[
"",
"c#",
".net",
"generics",
""
] |
I'm trying to add a new node to an jQuery [SimpleTree](http://news.kg/wp-content/uploads/tree/), but all I seem to be able to get is "sTC.addNode is not a function"...
```
var simpleTreeCollection = $('.simpleTree').simpleTree({
animate:true,
drag:false,
autoclose: false,
afterClick:function(node){},
afterDblClick:function(node){},
beforeMove:function (destination, source, pos){},
afterMove:function(destination, source, pos){},
afterAjax:function() {},
afterContextMenu:function(node){}
});
simpleTreeCollection.addNode('test', 'test');
```
Any suggestions what I might be doing wrong? Is there even the possibility to add a node?
|
Maybe take a look at [jsTree](http://www.jstree.com/jsTree/examples/)
|
hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states "The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters......."
However to get you working u need to select one of the nodes first in order to add to it like this
```
//Select first child node in tree
$('#2').click();
//Add new node to selected node
simpleTreeCollection.get(0).addNode(1,'A New Node')
```
|
jQuery SimpleTree: Add a node programatically
|
[
"",
"javascript",
"jquery",
""
] |
I've decided to reimplement the datetime picker, as a standard datetime picker isn't nullable. The user wants to start with a blank field and type (not select) the date.
I've created a user control to do just that, but if the user control is near the edge of the form, it will be cut off on the form boundry. The standard datetime picker doesn't suffer from this problem.
Here is a picture showing the problem. My user control is on the left, the standard datetimepicker is on the right:
[alt text http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg](http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg)
As you can see, the standard control will display over the form AND application boundry. How do I get the month picker in my control to do the same thing?
Thanks!
|
The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.
```
/// <summary>
/// A simple popup window that can host any System.Windows.Forms.Control
/// </summary>
public class PopupWindow : System.Windows.Forms.ToolStripDropDown
{
private System.Windows.Forms.Control _content;
private System.Windows.Forms.ToolStripControlHost _host;
public PopupWindow(System.Windows.Forms.Control content)
{
//Basic setup...
this.AutoSize = false;
this.DoubleBuffered = true;
this.ResizeRedraw = true;
this._content = content;
this._host = new System.Windows.Forms.ToolStripControlHost(content);
//Positioning and Sizing
this.MinimumSize = content.MinimumSize;
this.MaximumSize = content.Size;
this.Size = content.Size;
content.Location = Point.Empty;
//Add the host to the list
this.Items.Add(this._host);
}
}
```
Usage:
```
PopupWindow popup = new PopupWindow(MyControlToHost);
popup.Show(new Point(100,100));
...
popup.Close();
```
|
The screenshots looks like a Windows Forms applications, so my answer is for winforms.
I guess the best solution would be to create a customcontrol that itself uses the datetime picker that already has the behavior.
Show a empty textbox until it gets clicked, then display the datetimepicker.
That would save you a bunch of code..
|
Make user control display outside of form boundry
|
[
"",
"c#",
"winforms",
""
] |
How do you split a string?
Lets say i have a string "dog, cat, mouse,bird"
My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.
but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?
im using asp c#
|
```
string[] tokens = text.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
yourListBox.Add(new ListItem(token[i], token[i]));
}
```
|
Have you tried [String.Split](http://msdn.microsoft.com/en-us/library/system.string.split.aspx)? You may need some post-processing to remove whitespace if you want "a, b, c" to end up as {"a", "b", "c"} but "a b, c" to end up as {"a b", "c"}.
For instance:
```
private readonly char[] Delimiters = new char[]{','};
private static string[] SplitAndTrim(string input)
{
string[] tokens = input.Split(Delimiters,
StringSplitOptions.RemoveEmptyEntries);
// Remove leading and trailing whitespace
for (int i=0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
}
return tokens;
}
```
|
How do i split a String into multiple values?
|
[
"",
"c#",
"asp.net",
"visual-studio",
"string",
"listbox",
""
] |
We have a collection of photo images sizing a few hundred gigs. A large number of the photos are visually duplicates, but with differing filesizes, resolution, compression etc.
Is it possible to use any specific image processing methods to search out and remove these duplicate images?
|
I recently wanted to accomplish this task for a PHP image gallery. I wanted to be able to generate a "fuzzy" fingerprint for an uploaded image, and check a database for any images that had the same fingerprint, indicating they were similar, and then compare them more closely to determine how similar.
I accomplished it by resizing the uploaded image to 150 pixels wide, reducing it to greyscale, rounding the value of each colour off to the nearest multiple of 16 (giving 17 possible shades of grey between 0 and 255), normalise them and store them in an array, thereby creating a "fuzzy" colour histogram, then creating an md5sum of the histogram which I could then search for in my database. This was extremely effective in narrowing down images which were very visually similar to the uploaded file.
Then to compare the uploaded file against each "similar" image in the database, I took both images, resized them to 16x16, and analysed them pixel by pixel and took the RGB value of each pixel away from the value of the corresponding pixel in the other image, adding all the values together and dividing by the number of pixels giving me an average colour deviation. Anything less than specific value was determined to be a duplicate.
The whole thing is written in PHP using the GD module, and a comparison against thousands of images takes only a few hundred milliseconds per uploaded file.
My code, and methodology is here: <http://www.catpa.ws/php-duplicate-image-finder/>
|
Try [PerceptualDiff](http://pdiff.sourceforge.net/) for comparing 2 images with the same dimensions. Allows threshholds such as considering images with only X number of pixels different to be visually indistinguishable.
If visual duplicates may have different dimensions due to scaling, or different filetypes,
you may want to make a standard format for comparisons. For example, I might use ImageMagick
to scale all images to 100x100 and save them as PNG files.
|
Removing Duplicate Images
|
[
"",
"c#",
"algorithm",
"image-processing",
""
] |
Recently, when porting some STL code to VS2008 I wanted to disable warnings generated by `std::copy` by defining the new `_SCL_SECURE_NO_WARNINGS` flag. You can do this in two ways:
* Using the **/D** compiler switch, which can be specified in the project properties. You need to ensure it is defined for both Release and Debug builds, which I often forget to do.
* By defining it macro style before you include the relevant STL headers, or, for total coverage, in stdafx.h:
`#define _SCL_SECURE_NO_WARNINGS`
Both of these methods work fine but I wondered if there was any argument for favouring one over the other?
|
The /D option is generally used when you want to define it differently on different builds (so it can be changed in the makefile)
If you will "always" want it set the same way, use #define.
|
By putting them in your project file you maintain a close association between the platform specific warnings and the platform, which seems correct to me.
If they're in the code, they're always in the code whether or not it's appropriate for the platform. You don't need it for GCC or possibly future versions of Visual C++. On the other hand, by having it in the code, it's more obvious that it's there at all. If you move (copy) the code, it'll be easier to remember to move that define with it.
Pros and Cons each way. YMMV.
|
Defining macros in Visual Studio - /D or #define?
|
[
"",
"c++",
"visual-studio",
""
] |
I have a function, `a()`, that I want to override, but also have the original `a()` be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:
```
function a() {
new_code();
original_a();
}
```
and sometimes like this:
```
function a() {
original_a();
other_new_code();
}
```
How do I get that `original_a()` from within the over-riding `a()`? Is it even possible?
Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.
|
You could do something like this:
```
var a = (function() {
var original_a = a;
if (condition) {
return function() {
new_code();
original_a();
}
} else {
return function() {
original_a();
other_new_code();
}
}
})();
```
Declaring `original_a` inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.
Like Nerdmaster mentioned in the comments, be sure to include the `()` at the end. You want to call the outer function and store the *result* (one of the two inner functions) in `a`, not store the outer function itself in `a`.
|
The [Proxy pattern](http://docs.jquery.com/Types#Proxy_Pattern) might help you:
```
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
```
> The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.
|
Overriding a JavaScript function while referencing the original
|
[
"",
"javascript",
"overriding",
"user-defined-functions",
""
] |
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a `std::vector`. I don't want to have to do the standard loop to `push_back` all the values individually, it would be nice if I could just copy it all using something similar to `memcpy`.
|
If you can construct the vector after you've gotten the array and array size, you can just say:
```
std::vector<ValueType> vec(a, a + n);
```
...assuming `a` is your array and `n` is the number of elements it contains. Otherwise, `std::copy()` w/`resize()` will do the trick.
I'd stay away from `memcpy()` unless you can be sure that the values are plain-old data (POD) types.
Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.
Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to `begin()`, and (`ptr + n`) is equivalent to `end()`.
|
There have been many answers here and just about all of them will get the job done.
However there is some misleading advice!
Here are the options:
```
vector<int> dataVec;
int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
unsigned dataArraySize = sizeof(dataArray) / sizeof(int);
// Method 1: Copy the array to the vector using back_inserter.
{
copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}
// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve
{
dataVec.reserve(dataVec.size() + dataArraySize);
copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}
// Method 3: Memcpy
{
dataVec.resize(dataVec.size() + dataArraySize);
memcpy(&dataVec[dataVec.size() - dataArraySize], &dataArray[0], dataArraySize * sizeof(int));
}
// Method 4: vector::insert
{
dataVec.insert(dataVec.end(), &dataArray[0], &dataArray[dataArraySize]);
}
// Method 5: vector + vector
{
vector<int> dataVec2(&dataArray[0], &dataArray[dataArraySize]);
dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());
}
```
**To cut a long story short Method 4, using vector::insert, is the best for bsruth's scenario.**
Here are some gory details:
*Method 1* is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.
*Method 2* is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this *might* help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). [Bjarne agrees](http://www.research.att.com/~bs/bs_faq2.html#slow-containers). Incidentally, I found that this method performed the *slowest* most of the time though I'm struggling to comprehensively explain why it was regularly *significantly* slower than method 1...
*Method 3* is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can *only be used for POD types*. I would never use this solution.
*Method 4* is the best way to go. It's meaning is clear, it's (usually) the fastest and it works for any objects. There is no downside to using this method for this application.
*Method 5* is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast-ish and clear.
Finally, you are aware that you can use vectors in place of arrays, right? Even when a function expects c-style arrays you can use vectors:
```
vector<char> v(50); // Ensure there's enough space
strcpy(&v[0], "prefer vectors to c arrays");
```
|
How do you copy the contents of an array to a std::vector in C++ without looping?
|
[
"",
"c++",
"stl",
"vector",
"copy",
""
] |
I've got the bare minimum to handle the Linux/MySQL parts of the stack, but I want to have a basic grasp of PHP before I dive in. I'll be working on WordPress plugins, in case there's anything specifically interesting for that.
PS - any recommendations regarding recommended source control/IDEs would also be great, but I guess that's a separate question.
|
When you're developing C# you should definitely take a look at [VS.Php](http://www.jcxsoftware.com "VS.Php")
|
I would recomment the [PHP manual](http://www.php.net/manual/en/) too!
|
As a C# developer who wants to do some PHP work, what [book/online articles] should I [buy/read] to introduce myself to PHP?
|
[
"",
"php",
"wordpress",
""
] |
I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF. Any ideas?
|
I just got an example to work using the [SpriteGraphics2D](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java) object from [Adobe's Flex 3](http://opensource.adobe.com/wiki/display/flexsdk/Downloads). FYI... Flex 3 is now open source.
> *(from SpriteGraphics2D javadoc)* [SpriteGraphics2D](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/graphics/g2d/SpriteGraphics2D.java) is a SWF specific implementation of Java2D's Graphics2D API. Calls to this class are converted into a TagList that can be used to construct a SWF Sprite.
I figured this out by looking at these two classes [CubicCurveTest.java](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/test/java/flash/swf/builder/types/CubicCurveTest.java) and [SpriteTranscoder.java](http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/compiler/src/java/flash/svg/SpriteTranscoder.java).
The only two jars needed to run this example are swfutils.jar and batik-awt-util.jar which can be [downloaded here](http://opensource.adobe.com/wiki/display/flexsdk/Downloads).
Here is my example code...
```
// Create the SpriteGraphics2D object
SpriteGraphics2D g = new SpriteGraphics2D(100, 100);
// Draw on to the graphics object
Font font = new Font("Serif", Font.PLAIN, 16);
g.setFont(font);
g.drawString("Test swf", 30, 30);
g.draw(new Line2D.Double(5, 5, 50, 60));
g.draw(new Line2D.Double(50, 60, 150, 40));
g.draw(new Line2D.Double(150, 40, 160, 10));
// Create a new empty movie
Movie m = new Movie();
m.version = 7;
m.bgcolor = new SetBackgroundColor(SwfUtils.colorToInt(255, 255, 255));
m.framerate = 12;
m.frames = new ArrayList(1);
m.frames.add(new Frame());
m.size = new Rect(11000, 8000);
// Get the DefineSprite from the graphics object
DefineSprite tag = g.defineSprite("swf-test");
// Place the DefineSprite on the first frame
Frame frame1 = (Frame) m.frames.get(0);
Matrix mt = new Matrix(0, 0);
frame1.controlTags.add(new PlaceObject(mt, tag, 1, null));
TagEncoder tagEncoder = new TagEncoder();
MovieEncoder movieEncoder = new MovieEncoder(tagEncoder);
movieEncoder.export(m);
//Write to file
FileOutputStream fos = new FileOutputStream(new File("/test.swf"));
tagEncoder.writeTo(fos);
```
|
Mm, I know some libraries outputting Flash content, like or [Ming](http://www.libming.org/ "Ming"), or even [Haxe](http://haxe.org/), a language which can be "translated" into JavaScript, Flash or PHP code... But I know no Java library.
Searching a bit (I am curious), I found a commercial [Java Graph Library](http://big.faceless.org/products/graph/index.jsp "Java Graph Library"), probably closed source, a Flash player in Java, libraries to manipulate ActionScript source code or [bytecode](http://www.badgers-in-foil.co.uk/projects/jactionscript/ "ActionScript bytecode")... Ah, the latter points to [JavaSWF2](http://www.anotherbigidea.com/javaswf/ "JavaSWF2") which is supposed to be able to generate SWF. I found also a [DrawSWF](http://drawswf.sourceforge.net/ "DrawSWF") which uses... JavaSWF2 library as back-end!
PS.: Also found [Transform SWF](http://www.flagstonesoftware.com/transform/index.html "Transform SWF"). Looks promising.
|
Save Java2D to SWF (flash)
|
[
"",
"java",
"flash",
""
] |
what's the best/proper way of interacting between several windows in C# app?
Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various windows (through delegates). However, as passing one or two delegates was not a problem, I started thinking what if my other windows would need 10 delegates to interact properly with main window? Are delegates good solution? How to pass them in good way - through constructor, properties? Or maybe the need of using that many delegates is some serious design flaw itself?
|
You need to split the Model from the view by a Controller. Put an object that will be able to have both form reference and that will be able to manage the shared information.
An other solution is to send the reference of the formX to the formY this way they can communicate.
|
We use a custom built forms manager that uses the subject/observer pattern.
Every form that is opended is reported to the FormsManager, the FromsManager makes itself an observer of the form.
It also makes the form an observer of the FormsManager.
So you end up with every form observing the FormsManager and the FormsManager observing every form. Each form can then communicate to any other form via the FormsManager without each form having to be aware of all the others.
|
Interactions between windows
|
[
"",
"c#",
"delegates",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.