Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Given a sorted vector with a number of values, as in the following example:
```
std::vector<double> f;
f.pushback(10);
f.pushback(100);
f.pushback(1000);
f.pushback(10000);
```
I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the value "45", I'd like this to return "10" and "100".
I was looking at lower\_bound and upper\_bound, but they don't do what I want. Can you help?
EDIT: I've decided to post my own anser, as it is somewhat a composite of all the helpful answers that I got in this thread. I've voted up those answers which I thought were most helpful.
Thanks everyone,
Dave | I'm going to post my own anser, and vote anyone up that helped me to reach it, since this is what I'll use in the end, and you've all helped me reach this conclusion. Comments are welcome.
```
std::pair<value_type, value_type> GetDivisions(const value_type& from) const
{
if (m_divisions.empty())
throw 0; // Can't help you if we're empty.
std::vector<value_type>::const_iterator it =
std::lower_bound(m_divisions.begin(), m_divisions.end(), from);
if (it == m_divisions.end())
return std::make_pair(m_divisions.back(), m_divisions.back());
else if (it == m_divisions.begin())
return std::make_pair(m_divisions.front(), m_divisions.front());
else
return std::make_pair(*(it - 1), *(it));
}
``` | You can use STL's lower\_bound to get want you want in a few lines of code. lower\_bound uses binary search under the hood, so your runtime is O(log n).
```
double val = 45;
double lower, upper;
std::vector<double>::iterator it;
it = lower_bound(f.begin(), f.end(), val);
if (it == f.begin()) upper = *it; // no smaller value than val in vector
else if (it == f.end()) lower = *(it-1); // no bigger value than val in vector
else {
lower = *(it-1);
upper = *it;
}
``` | Find nearest points in a vector | [
"",
"c++",
"stl",
""
] |
Can anyone find a constant in the .NET framework that defines the number of days in a week (7)?
```
DateTime.DaysInAWeek // Something like this???
```
Of course I can define my own, but I'd rather not if it's somewhere in there already.
## Update:
I am looking for this because I need to allow the user to select a week (by date, rather than week number) from a list in a DropDownList. | You could probably use [System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.daynames.aspx).Length. | I think it's ok to harcode this one. I don't think it will change any soon.
*Edit: I depends where you want to use this constant. Inside the some calendar related algorithm it is obvious what 7 means. On the other hand sometimes named constant make code much more readable.* | System constant for the number of days in a week (7) | [
"",
"c#",
".net",
"datetime",
"date",
""
] |
I know very little about JavaScript but despite this I'm trying to cobble something together on my wordpress blog. It's not working, and I don't know how to resolve it, and hey, that's what StackOverflow is for, right?
Firstly, the error message is:
```
Error: element.dispatchEvent is not a function
Source File: http://.../wp-includes/js/prototype.js?ver=1.6
Line: 3936
```
It happens on page load. My page load handler is registered thusly:
```
Event.observe(window, 'load', show_dates_as_local_time);
```
The error goes away if I disable some other plugins, and this (plus googling) led me to conclude that it was a conflict between prototype and jQuery (which is used by some of the other plugins).
Secondly I'm following the wordpress recommended practice of using [`wp_enqeue_script`](http://codex.wordpress.org/Function_Reference/wp_enqueue_script) to add a dependency from my JavaScript to the Prototype library, as follows:
```
add_action( 'wp_print_scripts', 'depo_theme_add_javascript' );
function depo_theme_add_javascript() {
wp_enqueue_script('friendly_dates', 'javascript/friendly_dates.js', array('prototype'));
}
```
Now I'm also aware that there are some potential conflicts between jQuery and Prototype which are resolved using the jQuery `noConflicts` method. I've tried calling that from various places but no good. I don't *think* this is the problem because a) the `noConflict` function relates solely to the `$` variable, which doesn't seem to be the problem here, and b) I would *expect* wordpress to sort it out for me because it can...
Lastly, using the Venkman debugger I've determined that the `element` referenced in the error message is indeed an `HTMLDocument` but also does lack a `dispatchEvent`. Not sure how this could happen, given it's a standard DOM method? | Thanks for the suggestions all. In the end I think Kent's explanation was the closest, which basically amounted to "Prototype is broken". (Sorry if I'm summarizing you incorrectly :)
As for the `jQuery.noConflict` option - I already mentioned this in the question. It makes a difference *when* you run this method, and I have very little control over that. As I said, I have tried running it in a couple of different places (specifically the page header and also from my script file), to no effect. So, much as we'd all like it to be, "just use `noConflict`" is *not* an answer to this question, at least not without additional information.
Besides, `jQuery.noConflict` *seems* to be about the `$` variable, and the code around the error point does not deal with that variable at all. Of course they could be related indirectly, I haven't tracked it down.
So basically I ended up rewriting the script using jQuery instead of Prototype, which actually had its own problems. Anyway I've published the whole [war story on my blog](http://girtby.net/archives/2009/01/07/monkeying-with-javascript/), should you be interested. | There is a nasty trick many libraries do that I've taken a distinct liking to, and it looks like prototype is one of these.
Mootools does this, If I am right, and it involves overloading many of the prototypes on the basic classes, monkey patching them.
And likewise, I similarly encountered strange behaviour when mootools and jQuery were present, usually jQuery dying because it was calling some object method which had been somehow overloaded/monkey patched by Mootools.
Also, mysteriously, taking mootools out of the script usage list, resulted in *everything* running much faster, which I concluded was due to less object pollution.
Now I could be wrong, but I concluded from my experience such libraries just simply don't like to co-exist with each other, and seeing how mootools code seemed to me to degrade speed at which normal things were done, I sucked up and ported all mootools based code to jQuery ( A time consuming deal I assure you ), and the result, was code that was *fast* *and* didn't have weird errors that were unexplainable.
I recommend you consider migration as at least **One** of your options.
**One More thing, when writing:**
I tend to use this syntax with all my jQuery driven code, for a bit of safe encapsulation in the event somebody breaks '$' somehow.
**Runtime Code**
This waits for document.ready before executing:
```
jQuery(function($){
code_with_$_here;
});
```
**jQuery Plugins**
```
(function($){
code_with_$_here;
})(jQuery);
```
Using these will make it easier for people *using* any jQuery you happen to write to be able to use it without much of a conflict issue.
This will basically leave them to make sure their code isn't doing anything really magical. | prototype and jQuery peaceful co-existence? | [
"",
"javascript",
"jquery",
"wordpress",
"prototypejs",
""
] |
I was taking a look at <http://www.zenfolio.com/zf/features.aspx> and I can't figure out how they are doing the accordion style expand and collapse when you click on the orange links. I have been using the Web Developer Toolbar add-on for firefox, but I have not been able to find anything in the source of the page like JavaScript that would be doing the following. If anyone knows how they are doing it, that would be very helpful.
This is actually unrelated, but if all you answers are good, who do I give the answer too? | They're setting the .display CSS property on an internal DIV from 'none' to '', which renders it.
It's a bit tricky, as the JS seems to be in here that's doing it:
<http://www.zenfolio.com/zf/script/en-US/mozilla5/windows/5AN2EHZJSZSGS/sitehome.js>
But that's basically how everyone does this. It's in there, somewhere.
EDIT: Here it is, it looks like:
```
//... (bunch of junk)
zf_Features.prototype._entry_onclick = function(e, index)
{
var cellNode = this.dom().getElementsByTagName("H3")[index].parentNode;
while (cellNode.tagName != "TD") cellNode = cellNode.parentNode;
if (this._current != null) this.dom(this._current).className = "desc";
if ("i" + index != this._current)
{
cellNode.className = "desc open";
cellNode.id = this.id + "-i" + index;
this._current = "i" + index;
}
else this._current = null;
zf_frame.recalcLayout();
return false;
};
```
Basically, what they're doing is a really roundabout and confusing way of making the div inside of TD's with a class "desc" change to the class "desc open", which reveals its contents. So it's a really obtuse roundabout way to do the same thing everyone does (that is, handling onclick to change the display property of a hidden div to non-hidden).
EDIT 2:
lol, while I was trying to format it, others found it too. =) You're faster than I ;) | It is being done with JavaScript.
When you click a link, the parent td's class changes from 'desc' to 'desc open'. Basically, the expanded text is always there but hidden (display: none;). When it gets the css class of 'open' the text is no longer being hidden (display: block;).
If you look in the sitehome.js and sitehome.css file you can get an idea about how they are doing that.
btw I used FireBug to get that info. Even though there is some feature duplication with Web Developer Toolbar it's worth the install. | How are they doing the accordion style dropdown on the following website? | [
"",
"javascript",
"css",
""
] |
(Let me give you some context)
I am currently designing an application that is supposed to generate a printable A4 page based on some data.
Naturally, the device independent pixels of WPF (96 pixels/inch) are not a very natural unit of measurement in the paper world. Something like millimetres would be more appropriate. So I got my calculator out and arrived at a scaling factor of something around 3.779.
It turns out that simply slapping everything that's supposed to go on the page in a `ScaleTransform` has one nasty side effect: **Font sizes are scaled too** (naturally). This, however, is not what I intended. I would like 12pt Arial to render like 12pt Arial would render normally.
Is there any other way to **change the coordinate system without having to call into extensions** or whatever to convert each and every coordinate, length, thickness and so on?
- or -
Is there any way to **map font sizes on-the-fly**, being DependencyProperties? Via a custom control that wraps all the paper content, maybe? | For the outlined requirements you do not need to do anything special at all, just go ahead and use centimeters as unit of measurement for the WPF elements themselves (i.e. without any transform) - the very nature of WPF device independence allows you to to the following:
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="29.7cm" Width="21cm" FontSize="16pt">
<Grid>
<TextBlock Text="Sample" Height="1in" Width="1in" FontSize="12pt"
HorizontalAlignment="Center" VerticalAlignment="Center"
TextAlignment="Center"/>
</Grid>
</Window>
```
That is: you'll get a A4 window specified in '`cm`' with a centered square TextBox specified in '`in`' and a font specified in '`pt`'. All these will scale properly by whatever transform you might apply additionally, if need be (e.g. via a zoom slider for the users view port), respecting their relative sizes regardless of being specified with different units each (i.e. mixed usage at will).
Available units are `px` (default), `in`, `cm` and `pt`, see for example [FrameworkElement.Height](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.height.aspx) for details on their specification. | You can also set sizes in points (FontSize="10pt"), in inches (FontSize="10in") or in centimeters (FontSize="10cm"). Of course the real size depends on the DPI setting of Windows and the DPI of your monitor or printer in this case. | How to use a different coordinate system in WPF? (scaling only) | [
"",
"c#",
"wpf",
"font-size",
"dpi",
""
] |
The following code generates warning C4250. My question is, what's the best solution to it?
```
class A
{
virtual void func1();
}
class B : public A
{
}
class C : public A
{
virtual void func1();
}
class D : public B, public C
{
}
int main()
{
D d;
d.func1(); // Causes warning
}
```
According to what I've read it should be possible to do this:
```
class D : public B, public C
{
using B::func1();
}
```
But, this doesn't actually do anything. The way I've currently solved it is:
```
class D : public B, public C
{
virtual void func1() { B::func1(); }
}
```
What's everyone's view on this? | I had the same warning for the following code:
```
class Interface
{
public:
virtual void A() = 0;
};
class Implementation : public virtual Interface
{
public:
virtual void A() {};
};
class ExtendedInterface : public virtual Interface
{
virtual void B() = 0;
};
class ExtendedImplementation : public ExtendedInterface , public Implementation
{
public:
virtual void B() {};
};
```
This [bug report](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101259) for Visual C++ 2005 in msdn suggests that this is a known bug that was considered not important enough to fix... They suggest to disable the warning in this case by using a pragma. I think it is safe also in your case, but you should use virtual inheritance as shown in the answer by Gal Goldman. | Did you try to inherit public virtual from class A? I think it should solve it.
```
class B :public virtual A;
class C :public virtual A;
class D : public virtual B, public virtual C;
```
The virtual inheritance suppose to solve the ambiguity. | Visual Studio Compiler warning C4250 ('class1' : inherits 'class2::member' via dominance) | [
"",
"c++",
"visual-studio-2008",
"warnings",
"multiple-inheritance",
""
] |
I am asp.net-MVC using the BeginForm syntax in my source ciew page and I was told if you want the form to submit you have to have the submit Button at the end of the using statement. I don't want to use a Button to call the desired Action I have an Actionlink set up like so:
```
<%=Html.ActionLink("" + CreateMore, "Create", "", new { @class = "Create" })%>
```
and I want the form to submit when this actionlink is clicked since they are both going to the same action.. and I don't want to be able to see a Submit button:
```
<input type="submit" />
```
because the link looks better | I would once again turn to jQuery to handle this task
```
$(function(){
$('input:submit').hide(); //hide the submit button
$('#submitLinkID').click(function(){ // bind the link's click event
$('input:submit').click(); //click the hidden button
return false; //return false to stop the link from doing anything
});
});
``` | What is the question?
style="display:none;" would hide the button. You aren't indicating where you are running into a problem. | Hide Submit Button for form | [
"",
"c#",
"asp.net-mvc",
"forms",
""
] |
Is there a way to test code coverage within visual studio if I'm using MSTest? Or do I have to buy NCover?
Is the NCover Enterprise worth the money or are the old betas good enough if Microsoft doesn't provide built in tools to do code coverage?
EDIT:
Description of VS Products and which ones include code coverage
<https://www.visualstudio.com/vs/compare/>
TestDriven.NET (<http://testdriven.net/>) can be used if your VS version doesn't support it. | Yes, you can find code coverage information from within Visual Studio, provided that you have a version of Visual Studio that provides that functionality, such as the Team System.
When setting up the unit tests in VS.NET, a localtestrun.testrunconfig file will be created and added as part of the solution. Double-click this file and find the option Code Coverage option on the left of the dialog. Select the assemblies for which you want to collect code coverage information and then re-run the unit tests. Code coverage information will be collected and is available. To get the code coverage information open the test results window and click on the code coverage results button, which will open an alternative window with the results. | MSTest includes code coverage, at least it does in the version of VS I have. However, you need to enable the instrumentation in the testrunconfig, which is just ugly and a major PITA.
A much easier option is to use [TestDriven.NET](http://testdriven.net/), which can automate coverage, even for MSTest. And since it uses the MSTest core, you still get all the VS goodness such as colorization (red/blue lines for covered code). See [here](http://weblogs.asp.net/nunitaddin/archive/2006/11/08/Driving-MSTest-and-Team-Coverage-using-TestDriven.NET.aspx) (including a screencast), or since an image says a thousand words:
[](https://i.stack.imgur.com/i5kXe.gif "team coverage")
(source: [mutantdesign.co.uk](http://www.mutantdesign.co.uk/weblog/images/DrivingMSTestandTeamCoverageusingTes.NET_F424/MSTestAndTeamCoverage_thumb1.gif)) | MSTest Code Coverage | [
"",
"c#",
".net",
"testing",
"tdd",
"code-coverage",
""
] |
It is my understanding that the `java.regex` package does not have support for named groups (<http://www.regular-expressions.info/named.html>) so can anyone point me towards a third-party library that does?
I've looked at [jregex](http://jregex.sourceforge.net/) but its last release was in 2002 and it didn't work for me (admittedly I only tried briefly) under java5. | (**Update**: **August 2011**)
As [geofflane](https://stackoverflow.com/users/50260/geofflane) mentions in [his answer](https://stackoverflow.com/questions/415580/regex-named-groups-in-java/7033467#7033467), [Java 7 now support named groups](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29).
[tchrist](https://stackoverflow.com/users/471272/tchrist) points out in the comment that the support is limited.
He **details the limitations in his great answer "[Java Regex Helper](https://stackoverflow.com/questions/5767627/java-regex-helper/5771326#5771326)"**
Java 7 regex named group support was presented back in [**September 2010** in Oracle's blog](https://web.archive.org/web/20160702052728/http://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7).
In the official release of Java 7, the constructs to support the named capturing group are:
> * `(?<name>capturing text)` to define a named group "name"
* `\k<name>` to backreference a named group "name"
* `${name}` to reference to captured group in Matcher's replacement string
* [`Matcher.group(String name)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29) to return the captured input subsequence by the given "named group".
---
**Other alternatives for pre-Java 7** were:
* [Google named-regex](http://code.google.com/p/named-regexp/) (see [John Hardy](https://stackoverflow.com/users/134642/john-hardy)'s [answer](https://stackoverflow.com/questions/415580/regex-named-groups-in-java/1095737#1095737))
[Gábor Lipták](https://stackoverflow.com/users/337621/gabor-liptak) mentions (November 2012) that this project might not be active (with [several outstanding bugs](http://code.google.com/p/named-regexp/issues/list)), and its [GitHub fork](https://github.com/tony19/named-regexp) could be considered instead.
* [jregex](http://jregex.sourceforge.net/) (See [Brian Clozel](https://stackoverflow.com/users/22982/brian-clozel)'s [answer](https://stackoverflow.com/questions/415580/regex-named-groups-in-java/3782345#3782345))
---
(**Original answer**: **Jan 2009**, with the next two links now broken)
You can not refer to named group, unless you code your own version of Regex...
That is precisely what [Gorbush2 did in this thread](http://x86.sun.com/thread.jspa?threadID=785370&messageID=4463652).
[**Regex2**](http://gorbush.narod.ru/files/regex2.zip)
(limited implementation, as pointed out again by [tchrist](https://stackoverflow.com/users/471272/tchrist), as it looks only for ASCII identifiers. tchrist details the limitation as:
> only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.
Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in [Regexp Power](http://www.perl.com/pub/2003/06/06/regexps.html), [PCRE specs](http://www.pcre.org/pcre.txt) and [Matching Strings with Balanced Parentheses](http://perl.plover.com/yak/regex/samples/slide083.html) slide)
Example:
String:
```
"TEST 123"
```
RegExp:
```
"(?<login>\\w+) (?<id>\\d+)"
```
Access
```
matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
```
Replace
```
matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
```
---
(extract from the implementation)
```
public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}
``` | For people coming to this late: Java 7 adds named groups. [Matcher.group(String groupName) documentation.](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29) | Regex Named Groups in Java | [
"",
"java",
"regex",
""
] |
I'm coding some c# against Active Directory and have tried endlessly to get this to work to no avail. The following code works and the code that follows it does not:
The code below is using "WinNT://" + Environment.MachineName + ",Computer" to make the connection and works fine.
```
DirectoryEntry localMachine = new DirectoryEntry
("WinNT://" + Environment.MachineName + ",Computer");
DirectoryEntry admGroup = localMachine.Children.Find
("Administrators", "group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
output.RenderBeginTag("p");
output.Write(member.Name.ToString());
output.RenderBeginTag("p");
}
base.Render(output);
```
I'm now trying to change the line:
```
"WinNT://" + Environment.MachineName + ",Computer"
```
to
```
"LDAP://MyDomainControllerName"
```
but it seems no matter what value I try in place of the value 'MyDomainControllerName' it wont work.
To get the 'MyDomainControllerName' value I right clicked on MyComputer and copied the computer name value as suggested elsewhere but this didn't work.
---
When I try using the LDAP://RootDSE option above it results in the following error:
The Active Directory object located at the path LDAP://RootDSE is not a container
Is this a problem with the member methods as you mention? | When connecting to AD using the .NET Framework, you can use "serverless" binding or you can specify a server to use everytime (server bound).
Here's an example of using both:
```
// serverless
DirectoryEntry rootConfig = new DirectoryEntry("LDAP://dc=domainname,dc=com");
// server bound
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://domainControllerName/dc=domainName,dc=com");
```
I think where you were going astray is you forgot to include the FQDN for your domain on the end. Hope this helps. | Yes- RootDSE is not a container - but it holds a number of interesting properties which you can query for - e.g. the name of your domain controller(s).
You can check these out by using code like this:
```
DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE");
if (deRoot != null)
{
Console.WriteLine("Default naming context: " + deRoot.Properties["defaultNamingContext"].Value);
Console.WriteLine("Server name: " + deRoot.Properties["serverName"].Value);
Console.WriteLine("DNS host name: " + deRoot.Properties["dnsHostName"].Value);
Console.WriteLine();
Console.WriteLine("Additional properties:");
foreach (string propName in deRoot.Properties.PropertyNames)
Console.Write(propName + ", ");
Console.WriteLine();
}
```
Or save yourself the trouble and go grab my "[Beavertail ADSI Browser](http://adsi.mvps.org/adsi/CSharp/beavertail.html)" in C# source code - shows in detail how to connect to RootDSE and what it offers. | c# against Active Directory over LDAP | [
"",
"c#",
"active-directory",
"ldap",
""
] |
Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object? | The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random. | The other answers to this insist that it can't be done. And they're right, according to the spec -- but there *is* a trick that will let you do it.
Create only a *single* static variable, of a class or struct that contains all the other things you would normally make static variables, like so:
```
class StaticVariables {
public:
StaticVariables(): pvar1(new Var1Type), pvar2(new Var2Type) { };
~StaticVariables();
Var1Type *pvar1;
Var2Type *pvar2;
};
static StaticVariables svars;
```
You can create the variables in whatever order you need to, and more importantly, *destroy* them in whatever order you need to, in the constructor and destructor for `StaticVariables`. To make this completely transparent, you can create static references to the variables too, like so:
```
static Var1Type &var1(*svars.var1);
```
Voilà -- total control. :-) That said, this is extra work, and generally unnecessary. But when it *is* necessary, it's very useful to know about it. | Destruction order of static objects in C++ | [
"",
"c++",
"static",
"destruction",
""
] |
If I have a table that (among other columns) has two DATETIME columns, how would I select the **most recent** date from those two columns.
Example:
```
ID Date1 Date2
1 1/1/2008 2/1/2008
2 2/1/2008 1/1/2008
3 1/10/2008 1/10/2008
```
If I wanted my results to look like
```
ID MostRecentDate
1 2/1/2008
2 2/1/2008
3 1/10/2008
```
Is there a simple way of doing this that I am obviously overlooking? I know I can do subqueries and case statements or even write a function in sql server to handle it, but I had it in my head that there was a max-compare type function already built in that I am just forgetting about. | CASE is IMHO your best option:
```
SELECT ID,
CASE WHEN Date1 > Date2 THEN Date1
ELSE Date2
END AS MostRecentDate
FROM Table
```
---
If one of the columns is nullable just need to enclose in [`COALESCE`](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql):
```
.. COALESCE(Date1, '1/1/1973') > COALESCE(Date2, '1/1/1973')
``` | From **SQL Server 2012** on, it's possible to use the shortcut [`IIF`](https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql) to `CASE` expression though the latter is SQL Standard:
```
SELECT ID,
IIF(DateColA > DateColB, DateColA, DateColB) AS MostRecentDate
FROM theTable
``` | Selecting most recent date between two columns | [
"",
"sql",
"database",
"sql-server-2005",
""
] |
I have a file that I can get to with the UNC \mypath\myfile. I retrieve the path with c# and assign it to a link. The browser opens the file inside itself (ie display in the browser) without problem. But, when I try and save to \mypath\myfile I am prompted to save it locally. If I view the file outside of the browser (IE 7) I can edit and save as expected, again, via the UNC.
What I trying to do is use iframe to display the file from my UNC (file:///\mypath\myfile), which does work, but now I can't edit it. Outside the browser I can.
Is there anyway to save a PDF when displaying it inside the browser? I also tried a button to use the save method on the pdf, but it did not work.
Thank you.
I am using IE 7 and Adobe Professional 7.1.0. | When you open a file via a web browser the web browser downloads the file locally, then sends a local file path to the application that opens it. Even in the case you are using a UNC in your href Adobe does not get that UNC path to save back to, it is getting a local machine path. Keep in mind the browser does the same thing even if the UNC is a local machine path.
I don't think that the behavior you want is possible. | Saving a PDF in your browser (through File-Save As in IE etc) or Save A Copy in the Adobe system will always prompt you to save it locally. You could navigate manually to your UNC path, but this is browser behaviour, not server behaviour. | Is there any way to make a PDF savable from inside the browser? | [
"",
"c#",
"pdf",
""
] |
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?
```
int remaining = (end > start)
? end-start
: bufferSize - start + end;
``` | If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this:
```
int remaining = (end - start) + (-((int) (end <= start)) & bufferSize);
```
But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, which is much more readable. | Hmmm....
```
int remaining = (end - start + bufferSize) % bufferSize;
```
13 tokens, do I win? | Simplified algorithm for calculating remaining space in a circular buffer? | [
"",
"c++",
"circular-buffer",
""
] |
I'm a beginner (self-learning) programmer learning C++, and recently I decided to implement a binary-coded decimal (BCD) class as an exercise, and so I could handle very large numbers on [Project Euler](http://www.projecteuler.net). I'd like to do it as basically as possible, starting properly from scratch.
I started off using an array of ints, where every digit of the input number was saved as a separate int. I know that each BCD digit can be encoded with only 4 bits, so I thought using a whole int for this was a bit overkill. I'm now using an array of bitset<4>'s.
1. Is using a library class like this overkill as well?
2. Would you consider it cheating?
3. Is there a better way to do this?
EDIT: The primary reason for this is as an exercise - I wouldn't want to use a library like GMP because the whole point is making the class myself. Is there a way of making sure that I only use 4 bits for each decimal digit? | Just one note, using an array of `bitset<4>`'s is going to require the same amount of space as an array of long's. bitset is usually implemented by having an array of word sized integers be the backing store for the bits, so that bitwise operations can use bitwise word operations, not byte ones, so more gets done at a time.
Also, I question your motivation. BCD is usually used as a packed representation of a string of digits when sending them between systems. There isn't really anything to do with arithmetic usually. What you really want is an arbitrary sized integer arithmetic library like [GMP](http://gmplib.org/). | > Is using a library class like this overkill as well?
I would benchmark it against an array of ints to see which one performs better. If an array of bitset<4> is faster, then no it's not overkill. Every little bit helps on some of the PE problems
> Would you consider it cheating?
No, not at all.
> Is there a better way to do this?
Like Greg Rogers suggested, an arbitrary precision library is probably a better choice, unless you just want to learn from rolling your own. There's something to learn from both methods (using a library vs. writing a library). I'm lazy, so I usually use Python. | How best to implement BCD as an exercise? | [
"",
"c++",
"bitsets",
""
] |
I have a table that contains maybe 10k to 100k rows and I need varying sets of up to 1 or 2 thousand rows, but often enough a lot less. I want these queries to be as fast as possible and I would like to know which approach is generally smarter:
1. Always query for exactly the rows I need with a WHERE clause that's different all the time.
2. Load the whole table into a cache in memory inside my app and search there, syncing the cache regularly
3. Always query the whole table (without WHERE clause), let the SQL server handle the cache (it's always the same query so it can cache the result) and filter the output as needed
I'd like to be agnostic of a specific DB engine for now. | I firmly believe option 1 should be preferred in an initial situation.
When you encounter performance problems, you can look on how you could optimize it using caching. (Pre optimization is the root of all evil, Dijkstra once said).
Also, remember that if you would choose option 3, you'll be sending the complete table-contents over the network as well. This also has an impact on performance . | with 10K to 100K rows, number 1 is the clear winner to me. If it was <1K I might say keep it cached in the application, but with this many rows, let the DB do what it was designed to do. With the proper indexes, number 1 would be the best bet.
If you were pulling the same set of data over and over each time then caching the results might be a better bet too, but when you are going to have a different where all the time, it would be best to let the DB take care of it.
Like I said though, just make sure you index well on all the appropriate fields. | Any SQL database: When is it better to fetch a whole table instead of querying for particular rows? | [
"",
"sql",
"database",
""
] |
Just wondering if anyone knew off the top of their heads if there was much difference in doing the following:
```
String wibble = "<blah> blah blah </blah>.... <wibble> blah wibble blah </wibble> some more test here";
int i = wibble.lastIndexOf(">");
int j = wibble.lastIndexOf('>');
``` | Opinions are great but data are better. I wrote a quick benchmark:
## Test Code
```
public static void main(String[] args)
{
System.out.println("Starting perfo test");
final long NUM_TESTS = 100000000L;
String wibble = "<blah> blah blah </blah>.... <wibble>"
+ " blah wibble blah </wibble> some more test here";
int x = -1;
Stopwatch sw = new Stopwatch();
System.out.println("--perfo test with " + NUM_TESTS + " iterations--");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf(">");
sw.stop();
System.out.println("String first pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf('>');
sw.stop();
System.out.println("Char first pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf('>');
sw.stop();
System.out.println("Char second pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf(">");
sw.stop();
System.out.println("String second pass: " + sw + " seconds");
//Compiler warning said x was never read locally.. this is to
//ensure the compiler doesn't optimize "x" away..
System.out.println(x);
}
```
## Output
```
Starting perfo test
--perfo test with 100000000 iterations--
String first pass: 8.750 seconds
Char first pass: 6.500 seconds
Char second pass: 6.437 seconds
String second pass: 8.610 seconds
63
```
## Conclusion
The version with a char is about 25% faster, but both versions execute very quickly so it probably won't ever be a bottleneck in your code. | You can actually look into the source code of String class. It seems lastIndex(char) and lastIndex(String) were actually written separately. There should also be an overhead with String class. So char version might be a little bit faster, but I doubt there will be a case with any significant performance difference.
<http://www.docjar.com/html/api/java/lang/String.java.html> | String.lastIndexOf() is there a difference between a char and a string with a single character? | [
"",
"java",
"performance",
"optimization",
""
] |
I'm developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect standard output from the console to a TextBox in my program.
I have no problem executing the program from my application, but I don't know how to redirect the output to my application. I need to capture output while the program is running using events.
The console program isn't meant to stop running until my application stops and the text changes constantly at random intervals. What I'm attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the TextBox.
I am using C# to code the program and using the .NET framework for development. The original application is not a .NET program.
EDIT:
Here's example code of what I'm trying to do. In my final app, I'll replace Console.WriteLine with code to update the TextBox. I tried to set a breakpoint in my event handler, and it isn't even reached.
```
void Method()
{
var p = new Process();
var path = @"C:\ConsoleApp.exe";
p.StartInfo.FileName = path;
p.StartInfo.UseShellExecute = false;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(">>> {0}", e.Data);
}
``` | This works for me:
```
void RunWithRedirect(string cmdPath)
{
var proc = new Process();
proc.StartInfo.FileName = cmdPath;
// set up output redirection
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.EnableRaisingEvents = true;
proc.StartInfo.CreateNoWindow = true;
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
}
``` | You can use the following code
```
MemoryStream mem = new MemoryStream(1000);
StreamWriter writer = new StreamWriter(mem);
Console.SetOut(writer);
Assembly assembly = Assembly.LoadFrom(@"C:\ConsoleApp.exe");
assembly.EntryPoint.Invoke(null, null);
writer.Close();
string s = Encoding.Default.GetString(mem.ToArray());
mem.Close();
``` | Redirect console output to textbox in separate program | [
"",
"c#",
".net",
"winforms",
"textbox",
"console",
""
] |
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6. | As of v6, Java SE ships with JAXB. [`javax.xml.bind.DatatypeConverter`](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html) has static methods that make this easy. See [`parseBase64Binary()`](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html#parseBase64Binary(java.lang.String)) and [`printBase64Binary()`](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html#printBase64Binary%28byte%5B%5D%29).
**UPDATE**: JAXB is no longer shipped with Java (since Java 11). If JAXB is required for your project, you will need to configure the relevant libraries via your dependency management system, for example Maven. If you require the compiler (`xjc.exe`) you also need to download that separately. | As of **Java 8**, there is an officially supported API for Base64 encoding and decoding.
In time this will probably become the default choice.
The API includes the class [`java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) and its nested classes. It supports three different flavors: basic, URL safe, and MIME.
Sample code using the "basic" encoding:
```
import java.util.Base64;
byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
```
The [documentation for `java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams). | Decode Base64 data in Java | [
"",
"java",
"base64",
""
] |
I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code;
```
class graphics:
def __init__(self, Fullscreen = False, Width = 640, Height = 480):
print "Graphics Init"
SCREEN_SIZE = (Width, Height)
pygame.init()
if Fullscreen:
self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32)
print "Fullscreen Initialized"
else:
self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
print "Non-Fullscreen Initialized"
```
What I need to do is reference the screen attribute, which I can set with self.screen and be readable within that class...but from another class I have to set
```
screen = ?
```
under
```
class graphics:
```
What does that question mark need to be? I've tried 0, None, ""...nothing seems to work, I have no idea what data type that pygame call would be. :S | You rarely, if ever, reference attributes of a class. You reference attributes of an object.
(Also, class names should be uppercase: `Graphics`).
```
class Graphics:
SCREEN_SIZE = (640, 480)
def __init__(self, Fullscreen = False, Width = 640, Height = 480):
print "Graphics Init"
self.SCREEN_SIZE = (Width, Height)
pygame.init()
if Fullscreen:
self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32)
print "Fullscreen Initialized"
else:
self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
print "Non-Fullscreen Initialized"
```
Here's an example of getting or setting an attribute of an object.
```
g= Graphics() # create an object
# access the object's instance variables
print "screen", g.screen
g.screen= pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32)
```
Note that we created an object (`g`) from our class (`Graphics`). We don't reference the class very often at all. Almost the only time a class name is used is to create object instances (`Graphics()`). We rarely say `Graphics.this` or `Graphics.that` to refer to attributes of the class itself. | I'm thinking that a short explanation of the difference between class and instance attributes in Python might be helpful to you.
When you write code like so:
```
class Graphics:
screen_size = (1024, 768)
```
The class `Graphics` is actually an object itself -- a class object. Because you defined `screen_size` inside of it, `screen_size` is an attribute of the `Graphics` object. You can see this in the following:
```
assert Graphics.screen_size == (1024, 768)
```
In Python, these class objects can be used like functions -- just use the invocation syntax:
```
g = Graphics()
```
`g` is called an "instance" of the class `Graphics`. When you create instances of a class, all attribute lookups that don't match attributes of the instance look at the attributes of the class object next. That's why this lookup works:
```
assert g.screen_size == (1024, 768)
```
If we add an attribute to the *instance* with the same name, however, the lookup on the instance will succeed, and it won't have to go looking to the class object. You basically "mask" the class object's value with a value set directly on the instance. Note that this *doesn't* change the value of the attribute in the class object:
```
g.screen_size = (1400, 1050)
assert g.screen_size == (1400, 1050)
assert Graphics.screen_size == (1024, 768)
```
So, what you're doing in your `__init__` method is *exactly* what we did above: setting an attribute of the *instance*, `self`.
```
class Graphics:
screen_size = (1024, 768)
def __init__(self):
self.screen_size = (1400, 1050)
g = Graphics()
assert Graphics.screen_size == (1024, 768)
assert g.screen_size == (1400, 1050)
```
The value `Graphics.screen_size` can be used anywhere after this class definition, as shown with the first assert statement in the above snippet.
Edit: And don't forget to check out [the Python Tutorial's section on classes](http://docs.python.org/tutorial/classes.html), which covers all this and more. | How do you make a class attribute that isn't a standard data type? | [
"",
"python",
"pygame",
""
] |
How much of a performance benefit is there by selecting only required field in query instead of querying the entire row? For example, if I have a row of 10 fields but only need 5 fields in the display, is it worth querying only those 5? what is the performance benefit with this limitation vs the risk of having to go back and add fields in the sql query later if needed? | It's not just the extra data aspect that you need to consider. Selecting all columns will negate the usefulness of covering indexes, since a bookmark lookup into the clustered index (or table) will be required. | It depends on how many rows are selected, and how much memory do those extra fields consume. It can run much slower if several text/blobs fields are present for example, or many rows are selected.
How is adding fields later a risk? modifying queries to fit changing requirements is a natural part of the development process. | Performance benefit when SQL query is limited vs calling entire row? | [
"",
"sql",
"linq-to-sql",
""
] |
> Edit again:
> I think I get it now. All I need to do then is use the current class colon the class I want to be able to access? Person : Student, or person : teacher
> Is that correct?
I'm currently trying to learn the ins and outs of object oriented programming. Currently I have a new object that's something like the following:
```
class student
{
int grade; //0 - 100 as opposed to the characters A, B, C, etc.
string teacher; //For the teacher of the class the student is in.
}
class teacher
{
int courseAverage;
string name;
//teacher.name would correspond to the teacher in the student class.
}
class Program
{
student Jim;
Jim = new student();
teacher John;
John = new teacher();
}
static void grades()
{
Jim.grade = 100;
}
static void teacher()
{
Jim.teacher = "John Smith";
}
static void average()
{
int average; //For the sake of simplicity I'll leave the average at an int.
average = (Jim.grade + Sue.grade + Sally.grade + Robert.grade) / 4;
/*A loop would be set before the average variable to
ensure that only students of John would be counted in this.*/
}
static void teacheraverage()
{
John.courseAverage = average;//from the average method.
}
```
> EDIT:
>
> What I would like to do is modify the information from another class. However, I would like to modify the information from the Jim student in a method from within the program class. A method to compute the average of grades for the students who have the given teacher.
>
> Also, the only reason I use static in these is because that is the only way I have managed to access variables across methods. I tried using static methods to use the methods across classes with no success. Is there another way to do this?
I would like to use the Jim student in multiple methods. One that will set Jim's grade, and another that will set the teacher. I would like to use different methods in this case so that I can learn how it is done.
Okay, it looks like my understanding wasn't correct. I am going to try the methods within the class approach. | You're still missing the essential point: a *class* associates the data *with its methods.* So the method that sets Jim's teacher is part of the Student class, as is the method that sets Jim's grade.
Think of it in natural language first. "Jim is a student; students have names, stident ID numbers, and classes. Classes have teachers and classrooms. Students receive grades for each class at the end of the term."
So we have a class Student. Student, when you create an object from it, needs the students name and student ID, so the "constructor" needs to be something with a name string and a student ID -- call it a String too -- to initialize it. I don't know C#, so I'll make a pseudocde with braces...
```
class Student {
String name;
String studentID;
Course crsList = List<Course>; // "list of courses."
Student(String name, String studentID ){
// Make a new student, the "constructor"
this.name = name;
this.studentID = studentID;
}
addCourse(Course c){
// Add a course to the student's list
this.crsList.append(c); // Adds c to end of crsList
}
}
```
This says "A Student has a name and ID, and we can add classes to their collection of classes."
```
class Teacher {
String name;
Course crsList = List<Course>;
Teacher(String name){
this.name = name;
}
// ... more methods here.
}
```
But we observe that teachers and students are both kinds of people, so we "refactor" this to put the common piece together
```
class Person {
String name;
Person(String name){
this.name = name;
}
// ... more methods
}
```
Now we change Teacher and Student so we say
```
class Student : Person {
String studentID;
Student(String name, String studentID){
// Now we need to initialize the Person part
super(name);
// and the special Student part
this.studentID = studentID;
}
}
```
which now says "a Student is a kind of Person who has an additional student ID, and who we can add classes to."
You'd go on to define "addClass" for Teach, *but as part of the Teacher class*. Why? Because adding a class for a teacher means something different than adding one for a student. You'd add a method to Student that takes a Course and a Grade, finds the Course and assigns he grade somehow. (Pop quiz: is a Grade part of a Course or part of a Student?) | Since you're using C#, and assuming you're using .NET 3.5, your class would probably be looking something like this:
```
public class Student
{
public int Grade { get; set; }
public string Teacher { get; set; }
}
```
Grade and Teacher are automatic properties, which are roughly equivalent to getters and setters in Java, which would be methods. Properties in C# are essentially shortcuts to get and set local members of a class.
Your usage of the above class would looks something like this:
```
public class Program
{
// creates a new Student object with the properties Grade and Teacher set.
Student s = new Student() { Grade = 100, Teacher = "John Smith" }
Console.Write(s.Grade); // outputs 100
Console.Write(s.Teacher); // outputs John Smith
}
```
Is this what you're looking for? | Using Objects across methods | [
"",
"c#",
"methods",
"oop",
""
] |
I have an application which makes decisions based on part of URL:
```
if ( isset($this->params['url']['url']) ) {
$url = $this->params['url']['url'];
$url = explode('/',$url);
$id = $this->Provider->getProviderID($url[0]);
$this->providerName = $url[0]; //set the provider name
return $id;
}
```
This happens to be in a cake app so $this->params['url'] contains an element of URL. I then use the element of the URL so decide which data to use in the rest of my app. My question is...
whats the best way to secure this input so that people can't pass in anything nasty?
thanks, | Other comments here are correct, in AppController's beforeFilter validate the provider against the providers in your db.
However, if all URLs should be prefixed with a provider string, you are going about extracting it from the URL the wrong way by looking in $this->params['url'].
This kind of problem is exactly what the router class, and it's ability to pass params to an action is for. Check out the manual page in the cookbook <http://book.cakephp.org/view/46/Routes-Configuration>. You might try something like:
```
Router::connect('/:provider/:controller/:action');
```
You'll also see in the manual the ability to validate the provider param in the route itself by a regex - if you have a small definite list of known providers, you can hard code these in the route regex.
By setting up a route that captures this part of the URL it becomes instantly available in $this->params['provider'], but even better than that is the fact that the html helper link() method automatically builds correctly formatted URLs, e.g.
```
$html->link('label', array(
'controller' => 'xxx',
'action' => 'yyy',
'provider' => 'zzz'
));
```
This returns a link like /zzz/xxx/yyy | the parameter will be a providername - alphanumeric string. i think the answer is basically to to use ctype\_alpha() in combination with a check that the providername is a valid one, based on other application logic.
thanks for the replies | PHP - securing parameters passed in the URL | [
"",
"php",
"security",
"validation",
"cakephp",
""
] |
I need to run a callable at a specific time of day. One way to do it is to calculate the timediff between now and the desired time , and to use the executor.scheduleAtFixedRate .
Have a better idea?
`executor.scheduleAtFixedRate(command, TIMEDIFF(now,run_time), period, TimeUnit.SECONDS))` | For this kind of thing, just go ahead and install [Quartz](http://www.quartz-scheduler.org/). EJB has some support for this kind of thing but really you just want Quartz for scheduled tasks.
That being said, if you insist on doing it yourself (and I'd recommend not), use the [`ScheduledThreadPoolExecutor`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html).
```
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(4);
ScheduledFuture<?> future =
executor.scheduleAtFixedRate(runnable, 1, 24, TimeUnit.HOUR);
```
which will run the `Runnable` every day with an initial delay of one hour.
Or:
```
Timer timer = new Timer();
final Callable c = callable;
TimerTask task = new TimerTask() {
public void run() {
c.call();
}
}
t.scheduleAtFixedRate(task, firstExecuteDate, 86400000); // every day
```
`Timer` has a somewhat simpler interface and was introduced in 1.3 (the other is 1.5) but a single thread executes all tasks whereas the first one allows you to configure that. Plus `ScheduledExecutorService` has nicer shutdown (and other) methods. | You can user [JDK Timer](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html) and dont need to calculate the time difference:
```
Timer timer = new Timer();
Date executionDate = new Date();
long period = 24 * 60 * 60 * 1000;
timer.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
// the task
}
},
executionDate,
period);
``` | How to schedule a Callable to run on a specific time? | [
"",
"java",
"scheduling",
"callable",
""
] |
The ruby folks have [Ferret](https://github.com/dbalmain/ferret). Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching. | [Whoosh](http://pypi.python.org/pypi/Whoosh/) is a new project which is similar to lucene, but is pure python. | The only one pure-python (not involving even C extension) search solution I know of is [Nucular](http://nucular.sourceforge.net/). It's slow (much slower than PyLucene) and unstable yet.
We moved from PyLucene-based home baked search and indexing to [Solr](http://lucene.apache.org/solr/) but YMMV. | Is there a pure Python Lucene? | [
"",
"python",
"full-text-search",
"lucene",
"ferret",
""
] |
I have been looking at OpenLaszlo and observed that scripting in the client is implemented in JavaScript. Does this mean it is possible to use libraries like JQuery and PrototypeJS ? | jQuery and Prototype rely heavily on the browser's DOM API, not just JavaScript. I am not very familiar with OpenLaszlo, but if it doesn't provide a DOM for manipulating the document to be output, then libraries oriented around abstracting cross-browser DOM incompatibilities will be less useful. Aptana's [Jaxer](http://www.jaxer.org/) web server claims to allow you to manipulate the DOM before it is sent to the client, even with event listeners and animations. It may be worth a look. | Directions on using JQuery with other Libraries:
<http://docs.jquery.com/Using_jQuery_with_Other_Libraries> | Can OpenLaszlo Use JavaScript Libraries like JQuery and PrototypeJS? | [
"",
"javascript",
"jquery",
"prototypejs",
"openlaszlo",
""
] |
Does anybody know any fine open source cube browser?
Ideally, it would be something built with plain javascript.
Does it even exists?
I'm planing to use it with classic asp agains a SQL database. | You can look at [Pentaho Mondrian](http://mondrian.pentaho.org/) (including [JPivot](http://jpivot.sourceforge.net)), or at [Eclipse BIRT](http://eclipse.org/birt)
With these, you get some kind of flexible reporting tools on the most popular databases, and it includes functionality to browse OLAP cubes too. | If you're looking for something lightweight, give [CubesViewer](https://github.com/jjmontesl/cubesviewer) a try:
It's mostly Javascript, backed up by Cubes OLAP server.
*(Disclaimer, I'm the main developer :-))* | Browsing OLAP cubes | [
"",
"javascript",
"database",
"widget",
"olap",
"cube",
""
] |
I'd like to split strings like these
```
'foofo21'
'bar432'
'foobar12345'
```
into
```
['foofo', '21']
['bar', '432']
['foobar', '12345']
```
Does somebody know an easy and simple way to do this in python? | I would approach this by using `re.match` in the following way:
```
import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
items = match.groups()
print(items)
>> ("foofo", "21")
``` | ```
def mysplit(s):
head = s.rstrip('0123456789')
tail = s[len(head):]
return head, tail
```
```
>>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
``` | How to split strings into text and number? | [
"",
"python",
"string",
"split",
""
] |
In Java, can Class.forName ever return null, or will it always throw a ClassNotFoundException or NoClassDefFoundError if the class can't be located? | Java Docs says it will throw ClassNotFoundException if the class cannot be found so I'd say it never returns null. | Since null is not mentioned anywhere in the documentation for this method and because there doesn't seem to be any situation in which it would make sense for the method to return null instead of throwing an exception, I think it's pretty safe to assume that it never returns null.
It won't throw a NoClassDefFoundError, but it may throw ClassNotFoundException. | In Java, can Class.forName ever return null? | [
"",
"java",
"classloader",
""
] |
Say you have these two methods:
Number 1:
```
void AddPerson(Person person)
{
// Validate person
if(person.Name != null && IsValidDate(person.BirthDate)
DB.AddPersonToDatabase(person);
}
```
Number 2:
```
void AddPerson(string name, DateTime birthDate)
{
Person p = new Person(name, birthDate);
DB.AddPersonToDatabase(person);
}
```
Which of the two methods is the best one? I know the first one is more correct OO-wise, but I feel the second is more readable, and you don't have to make sure the object is valid as the parameters make sure of this. I just don't like to having to validate the objects anywhere I pass them as parameters. Are there other approaches?
EDIT:
Thx for all the answers. To clarify, validating in the constructor and a IsValid method is of course a good approach, but in my code the valid state of the person is often dependant of the context and could vary from method to method. This could of course be a sign of bad design.
The code is just a example to describe the problem. | The first shouldn't have to validate person.Name and person.BirthDate - they should be validated automatically by the `Person` constructor. In other words, if you're passed a Person, you should know that it's valid.
On the other hand, you'd have to check that `person` isn't a null reference.
It's sometimes worth having convenience methods like the second version to avoid having to explicitly call the constructor quite as often though. It should usually just call the `Person` constructor and then delegate the work to the first form. | The first one has the advantage of allowing you to change the Person definition without breaking existing code, only recompilation is needed. You may think the second one is more readable, but the first one is more maintainable, your choice. | OO style parameters vs type parameters | [
"",
"c#",
"oop",
"methods",
""
] |
How do I increment a step value to be processed when the page loads? For example, in the code below the viewstate variable is not incremented until after Page\_Load, due to the ASP.NET page lifecycle.
```
protected void Page_Load(object sender, EventArgs e)
{
switch ((int)ViewState["step"])
{
//do something different for each step
}
}
protected void btnIncrementStep_Click(object sender, EventArgs e)
{
//when the button is clicked, this does not fire
//until after page_load finishes
ViewState["step"] = (int)ViewState["step"] + 1;
}
``` | Just move the switch statement into an event that happens later. E.g. LoadComplete() or PreRender(). PreRender is probably a bit late, depending on what you want to do. | There's no way around this. Page\_Load event will always happen before any control events get fired. If you need to do something after the control event, use Page\_PreRender.
[ASP.Net Page Lifecycle Image](http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg) | How do I increment a step value to be processed when the page loads in ASP.NET? | [
"",
"c#",
"asp.net",
"postback",
""
] |
In c (or maybe c++) , what's the difference between
```
char myarr[16]={0x00};
```
and
```
char myarr[16];
memset(myarr, '\0', sizeof(myarr));
```
??
edit: I ask this because in vc++ 2005 the result is the same..
edit more :
and
```
char myarr[16]={0x00,};
```
?
maybe can get more comprehensive answer and not ambiguous as some answers below refer to this kind of code,ie.
put comma just before closing curly braces. Also the result is the same in vc++ 2005. | The important difference is that the first default initializes the array in an element-specific manner: Pointers will receive a *null pointer value*, which doesn't need to be 0x00 (as in all-bits-zero), booleans will be *false*. If the element type is a class type that's not a so-called *POD* (plain old data-type), then you can only do the first one, because the second one only works for the simplest cases (where you don't have *virtual functions*, user defined constructors and so on). In contrast, the second way using the memset sets all elements of the array to all-bits-zero. That is not always that what you want. If your array has pointers for example, they won't be set to null-pointers necessarily.
The first will default initialize the elements of the array, except for the first one, which is set to 0 explicitly. If the array is local and on the stack (that is, not a static), the compiler internally often does a memset to clear the array out. If the array is non-local or static, the first version can be *considerably more efficient*. The compiler can put the initializers already, at compile time, into the generated assembler code, making it require no runtime code at all. Alternatively, the array can be laid out on a section that is automatically zero'd out (also for pointers, if they have a all-bits-zero representation) when the program starts in a fast manner (i.e page-wise).
The second does a memset explicitly over the whole array. Optimizing compilers will usually replace a memset for smaller regions with inline machine code that just loops using labels and branches.
Here is assembler-code generated for the first case. My gcc stuff isn't much optimized, so we got a real call to memset (16 bytes at the stack-top are always allocated, even if we got no locals. $n is a register number):
```
void f(void) {
int a[16] = { 42 };
}
sub $29, $29, 88 ; create stack-frame, 88 bytes
stw $31, $29, 84 ; save return address
add $4, $29, 16 ; 1st argument is destination, the array.
add $5, $0, 0 ; 2nd argument is value to fill
add $6, $0, 64 ; 3rd argument is size to fill: 4byte * 16
jal memset ; call memset
add $2, $0, 42 ; set first element, a[0], to 42
stw $2, $29, 16 ;
ldw $31, $29, 84 ; restore return address
add $29, $29, 88 ; destroy stack-frame
jr $31 ; return to caller
```
The gory details from the C++ Standard. The first case above will default-initialize remaining elements.
`8.5`:
> To zero-initialize storage for an object of type T means:
>
> * if T is a scalar type, the storage is set to the value of 0 (zero) *converted to T*;
> * if T is a non-union class type, the storage for each nonstatic data member and each base-class subobject is zero-initialized;
> * if T is a union type, the storage for its first data member is zero-initialized;
> * if T is an array type, the storage for each element is zero-initialized;
> * if T is a reference type, no initialization is performed.
>
> To default-initialize an object of type T means:
>
> * if T is a non-POD class type, the default constructor for T is called
> * if T is an array type, each element is default-initialized;
> * otherwise, the storage for the object is zero-initialized.
`8.5.1`:
> If there are fewer initializers in the list than there are members in the aggregate,
> then each member not explicitly initialized shall be *default-initialized* (8.5). | ISO/IEC 9899:TC3 6.7.8, paragraph 21:
> If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Arrays with static storage duration are initialized to `0`, so the C99 spec guarantees the not explicitly initialized array elements to be set to `0` as well.
---
In my first edit to this post, I spouted some nonsense about using compound literals to assign to an array after initialization. That does not work. If you really want to use compound literals to set an array's values, you have to do something like this:
```
#define count(ARRAY) (sizeof(ARRAY)/sizeof(*ARRAY))
int foo[16];
memcpy(foo, ((int [count(foo)]){ 1, 2, 3 }), sizeof(foo));
```
With some macro magic and the non-standard `__typeof__` operator, this can be considerably shortened:
```
#define set_array(ARRAY, ...) \
memcpy(ARRAY, ((__typeof__(ARRAY)){ __VA_ARGS__ }), sizeof(ARRAY))
int foo[16];
set_array(foo, 1, 2, 3);
``` | Difference in initializing and zeroing an array in c/c++? | [
"",
"c++",
"c",
"arrays",
""
] |
In a Java project (SWT desktop app), I want to inform the user about events through animated notification box (actually, it's not required to be animated). Something like MSN or any other IM client.
There is [JToaster](http://jtoaster.sourceforge.net/) for Swing, but I wonder if there isn't any other implementation based on SWT.
Thanks! | The [MyLyn](http://www.eclipse.org/mylyn) plugin for Eclipse does this. Since it's open source, maybe you can check the MyLyn code to see how it's done there? | If you want to create SWT-based System notifications, this is the best resource to start with:
<http://hexapixel.com/2009/06/30/creating-a-notification-popup-widget>
The author creates real System notifications which are stackable and fade out nicely. | SWT Notification animated box (a.k.a toaster) needed | [
"",
"java",
"user-interface",
"swt",
"desktop",
"desktop-application",
""
] |
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python? | `open` and `start` are command-interpreter things for Mac OS/X and Windows respectively, to do this.
To call them from Python, you can either use `subprocess` module or `os.system()`.
Here are considerations on which package to use:
1. You can call them via `os.system`, which works, but...
**Escaping:** `os.system` only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. `A:\abc\def\a.txt`), or else these need to be escaped. There is `shlex.quote` for Unix-like systems, but nothing really standard for Windows. Maybe see also [python, windows : parsing command lines with shlex](https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex)
* MacOS/X: `os.system("open " + shlex.quote(filename))`
* Windows: `os.system("start " + filename)` where properly speaking `filename` should be escaped, too.
2. You can also call them via `subprocess` module, but...
For Python 2.7 and newer, simply use
```
subprocess.check_call(['open', filename])
```
In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile
```
subprocess.run(['open', filename], check=True)
```
If you need to be compatible all the way back to Python 2.4, you can use `subprocess.call()` and implement your own error checking:
```
try:
retcode = subprocess.call("open " + filename, shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
```
Now, what are the advantages of using `subprocess`?
* **Security:** In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type `'filename ; rm -rf /'`" problem, and **if** the file name can be corrupted, using `subprocess.call` gives us little additional protection.
* **Error handling:** It doesn't actually give us any more error detection, we're still depending on the `retcode` in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).
* **Spawns a (non-blocking) subprocess**: We don't need to wait for the child process, since we're by problem statement starting a separate process.
To the objection "But `subprocess` is preferred." However, `os.system()` is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using `os.system()` is therefore also a correct answer.
A marked **disadvantage** is that the Windows `start` command *requires* you to pass in `shell=True` which negates most of the benefits of using `subprocess`. | Use the `subprocess` module available on Python 2.4+, not `os.system()`, so you don't have to deal with shell escaping.
```
import subprocess, os, platform
if platform.system() == 'Darwin': # macOS
subprocess.call(('open', filepath))
elif platform.system() == 'Windows': # Windows
os.startfile(filepath)
else: # linux variants
subprocess.call(('xdg-open', filepath))
```
The double parentheses are because `subprocess.call()` wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a `gnome-open` command that does the same thing, but `xdg-open` is the Free Desktop Foundation standard and works across Linux desktop environments. | Open document with default OS application in Python, both in Windows and Mac OS | [
"",
"python",
"windows",
"macos",
""
] |
I have a `HashMap` (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected?
If I do `map.clear()` and those objects that were in the table are not referenced anywhere else, will they get garbage collected?
What is the fastest way, to actually remove all entries from the table, but also destroy those objects. | Yes, if the collection is the last place these objects are referenced they are eligible for garbage collection after they have been removed from the collection. And no, you can not destroy these objects forcefully. The garbage collector will handle them when it feels like it. | Note that [WeakHashMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/WeakHashMap.html) allows you to place objects in it and have them eligible for garbage collection as soon as there are no more references to the key (not the value) outside the map - the map entry will disappear at this point.
In general you should not worry about *when* objects are garbage collected - the JVM decides this, and it knows a lot more about its memory needs and possible delays than you. What you *should* worry about is to make sure that objects you don't need anymore are *eligible* for garbage collection. | Removing objects from Java Collections | [
"",
"java",
"collections",
""
] |
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:
```
img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
```
Any ideas? Or other libraries that I could be using? | ```
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')
```
<http://www.emilas.com/jpeg/> | There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags.
```
image = Image.open('test.jpg')
exif = image.info['exif']
# Your picture process here
image = image.rotate(90)
image.save('test_rotated.jpg', 'JPEG', exif=exif)
```
As you can see, the save function can take the exif argument which permits to copy the raw exif data in the new image when saving. You don't actually need any other lib if that's all you want to do. I can't seem to find any documentation on the save options and I don't even know if that's specific to Pillow or working with PIL too. (If someone has some kind of link, I would enjoy if they posted it in the comments) | Resize image in Python without losing EXIF data | [
"",
"python",
"image-processing",
"python-imaging-library",
"exif",
""
] |
I need a simple function which will take a FileInfo and a destination\_directory\_name as input, get the file path from the fileinfo and replicate it in the destination\_directory\_name passed as the second parameter.
for ex. filepath is "d:\recordings\location1\client1\job1\file1.ext
the function should create the directories in the destination\_directory\_name if they dont exist and copy the file after creating the directories. | I'm using the following method for that purpose:
```
public static void CreateDirectory(DirectoryInfo directory)
{
if (!directory.Parent.Exists)
CreateDirectory(directory.Parent);
directory.Create();
}
```
Use it in this way:
```
// path is your file path
string directory = Path.GetDirectoryName(path);
CreateDirectory(new DirectoryInfo(directory));
``` | System.IO.Directory.CreateDirectory can be used to create the final directory, it will also automatically create all folders in the path if they do not exist.
```
//Will create all three directories (if they do not already exist).
System.IO.Directory.CreateDirectory("C:\\First\\Second\\Third")
``` | c# - Function to replicate the folder structure in the file path | [
"",
"c#",
"filesystems",
".net",
"system.io.directory",
""
] |
This is an attempt to rephrase a question I asked earlier. I'd like to know why C++ seems to be the language of choice for certain thick client apps. The easiest example I can think of is video games and my favorite app VirtualBox.
Please don't close this post I'm just trying to understand why this is the case. | As a profesional game dev working on AAA titles I can tell you. Reason number 1 is C++ and C will compile and run on any platform say a PS3 or an NDS. Next platform makers only provide robust C libraries to interface with hardware. The reason behind this is C and C++ are free, and not owned by one corporation, and because they were designed for close to the metal low level programming. This means game devs need to know C/C++ which forms a feedback loop. However many devs nowadays make their toolsets in C# or Java, but that's because performance isn't critical.
Now this posture might seem fanatic to most web developers, but games need to process entire slices of complex simulations and rendering upto 60 times per second, few web apps are bound to stay within that latency rate, so the needs are different.And same reason few web services are produced with C++.
However high level AI, and gameplay( the rules ) are scripted because of the development speed increase and ability to fine tune the game. Also because this amounts to about roughly 15% of the resources, so we can splurge here, and let the designers do their job. Also note that coding a fexible rule system would take about the same resources anyways even if done in C++. Oh and not all platforms allow Jit code which would be nice :)
And of course as mentioned memory control, if you use even 1 byte more memory than provided by the hardware, it doesn't slow down like a PC. It crashes. So we love our naked pointers, custom allocators and RAII. | There are lots of potential reasons:
* Speed increases either perceived or real.
* Previous knowledge. There are a lot of people out there that have been programming C++ for 20+ years. Not so with C#.
* Existing code. It is true that .Net has a lot of capability wrapped up in the framework. Even then it still doesn't compare to the decades of libraries that exist for C++.
* Cross platform development. C++ is much easier to port.
* Determinism. I will shamelessly steal from ctacke's answer. He sums it up best, but being able to determine exactly what happens when at a very low level can be very necessary for programming something like a game that is time critical. | What advantage does C++ have over .NET when it comes to to game development and apps like VirtualBox | [
"",
".net",
"c++",
""
] |
Common question but I could use an "english" explanation.
Is it like Java where
```
Cat myCat
```
actually is a pointer to `Cat`?
Should I really create copy constructors in C#?
---
I understand we are passing by value, but now my question is are we passing by pointer value or full copy of the object?
If it's the latter, isn't that too expensive performance/memory wise? Is that when you have to use the ref keyword? | As @rstevens answered, if it is a class, myCat is a reference. But if you pass myCat to a method call, then the reference itself is passed by value - i.e. the parameter itself will reference the same object, but it's a completely new reference, so if you assign it to null, or create a new object, the old myCat reference will still point to the original object.
```
SomeMethod(myCat);
void SomeMethod(Cat cat)
{
cat.Miau(); //will make the original myCat object to miau
cat = null; //only cat is set to null, myCat still points to the original object
}
```
Jon Skeet has a good [article](https://jonskeet.uk/csharp/parameters.html) about it. | Remember that a pointer is not exactly the same as a reference, but you can just about think of it that way if you want.
I swear I saw another SO question on this not 10 minutes ago, but I can't find the link now. In the other question I saw, they were talking about passing arguments by ref vs by value, and it came down to this:
> By default in .Net, you don't pass objects by reference. You pass references to objects by value.
The difference is subtle but important, especially if, for example, you want to assign to your passed object in the method. | C# pass by value/ref? | [
"",
"c#",
""
] |
I do not quite understand the difference between a C# reference and a pointer. They both point to a place in memory don't they? The only difference I can figure out is that pointers are not as clever, cannot point to anything on the heap, are exempt from garbage collection, and can only reference structs or base types.
One of the reasons I ask is that there is a perception that people need to understand pointers well (from C, I guess) to be a good programmer. A lot of people who learn higher level languages miss this out and therefore have this weakness.
I just don't get what is so complex about a pointer? It is basically just a reference to a place in memory is it not? It can return its location and interact with the object in that location directly?
Have I missed a massive point? | C# references can, and will be relocated by garbage collector but normal pointers are static. This is why we use `fixed` keyword when acquiring a pointer to an array element, to prevent it from getting moved.
EDIT: Conceptually, yes. They are more or less the same. | There is a slight, yet extremely important, distinction between a pointer and a reference. A pointer points to a place in memory while a reference points to an object in memory. Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at.
Take for example the following code
```
int* p1 = GetAPointer();
```
This is type safe in the sense that GetAPointer must return a type compatible with int\*. Yet there is still no guarantee that \*p1 will actually point to an int. It could be a char, double or just a pointer into random memory.
A reference however points to a specific object. Objects can be moved around in memory but the reference cannot be invalidated (unless you use unsafe code). References are much safer in this respect than pointers.
```
string str = GetAString();
```
In this case str has one of two state 1) it points to no object and hence is null or 2) it points to a valid string. That's it. The CLR guarantees this to be the case. It cannot and will not for a pointer. | What is the difference between a C# Reference and a Pointer? | [
"",
"c#",
"pointers",
"reference",
""
] |
I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that? | Not quite. Creating a `Request` object does not actually send the request, and Request objects have no `Read()` method. (Also: `read()` is lowercase.) All you need to do is pass the `Request` as the first argument to `urlopen()` and that will give you your response.
```
import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()
``` | I normally use:
```
import urllib2
request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive"
}
request = urllib2.Request("https://thewebsite.com", headers=request_headers)
response = urllib2.urlopen(request).read()
print(response)
``` | How do I send a custom header with urllib2 in a HTTP Request? | [
"",
"python",
"header",
"urllib2",
""
] |
I'm building a wepage in php using MySQL as my database.
Which way is faster?
1. 2 requests to MySQL with the folling query.
SELECT points FROM data;
SELECT sum(points) FROM data;
2. 1 request to MySQL. Hold the result in a temporary array and calcuale the sum in php.
$data = SELECT points FROM data;
EDIT -- the data is about 200-500 rows | It's really going to depend on a lot of different factors. I would recommend trying both methods and seeing which one is faster. | Since Phill and Kibbee have answered this pretty effectively, I'd like to point out that premature optimization is a Bad Thing (TM). Write what's simplest for you and profile, profile, profile. | php and MySQL: 2 requests or 1 request? | [
"",
"php",
"mysql",
""
] |
I have a WCF service that I call from a windows service.
The WCF service runs a SSIS package, and that package can take a while to complete and I don't want my windows service to have to wait around for it to finish.
How can I make my WCF service call asynchronous? (or is it asynchronous by default?) | All your needs will be satisfied in the following articles from MSDN:
[Implementing an Async Service Operation](http://msdn.microsoft.com/en-us/library/ms731177.aspx)
[Calling WCF Service Async](http://msdn.microsoft.com/en-us/library/ms730059.aspx)
[Designing Service Contracts](http://msdn.microsoft.com/en-us/library/ms733070.aspx) | On Visual Studio 2010, on the `Add Service Reference > click Advanced button > check the Generate Asynchronous Operations` checkbox.
After doing so, the Async operations will be added and be available for your use. | How to make a call to my WCF service asynchronous? | [
"",
"c#",
".net",
"wcf",
"windows-services",
""
] |
I have a function that accepts an anonymous function as an argument and sets it to a variable (scoped) for reference. I then try to execute another function with that reference but it obviously fails since that function is out of scope.
I was wondering if anyone knew of a simple way of passing the anonymous function straight through as an anonymous function, avoiding the scoping issue?
**EDIT**: To clarify, the el element is defined after the function is isolated from the arguments list. Additionally, the el element is a part of the arguments list as well. Were this code to be used by only me, I would likely have used a two argument list with the second argument being an array or hash object but unfortunately this code is going to be used by some folks who are less familiar with JS or even coding for that matter.
Thanks for the help!
Here is the relevant portion of my code:
```
locate : function(){
if ((!arguments)||(!arguments.length)) return;
arguments = [].splice.call(arguments,0); //This just converts arguments into an array
for (var i=0;i<arguments.length;i++){
if (typeof(arguments[i])=='function'){
var tf = arguments.splice(i,1);
break;
};
};
if (!tf) return;
JAS.Globals.eventListen('click',el,tf);
}
```
This is abbreviated so just trust that el is defined.
JAS.Globals.eventListen is just an intelligent addEventListener. | ```
var tf = arguments.splice(i,1)
```
This returns an array into tf. Is eventListen expecting an array? If not use:-
```
var tf = arguments.splice(i,1)[0]
```
Since you don't seem to have any other uses for your other arguments why are you using splice anyway? | You can do:
```
for (var i=0;i<arguments.length;i++){
if (typeof(arguments[i])=='function'){
JAS.Globals.eventListen('click',el,arguments[i]);
break;
}
}
```
or if you need to assign the event after the loop for some reason:
```
var tf;
for (var i=0;i<arguments.length;i++){
if (typeof(arguments[i])=='function'){
tf = arguments[i];
break;
}
}
if (!tf) return;
JAS.Globals.eventListen('click',el,tf);
``` | Pass anonymous function by value in javascript? | [
"",
"javascript",
"anonymous-function",
"byval",
""
] |
What's the best/easiest way to run periodic tasks (like a daemon thread) on a tomcat/jetty server? How do I start the thread? Is there a simple mechanism or is this a bad idea at all? | It's okay and effective to stash a java.util.Timer (or better yet ScheduledExecutor) instance in your ServeletContext. Create it in a Servlet's init() call and all your servlets can add TimerTasks to it. | If want to keep everything on java side, give a look to [Quartz](http://www.quartz-scheduler.org/).
It handles failover and fine grained repartition of jobs, with the same flexibility of cron jobs. | run periodic tasks on server in the background | [
"",
"java",
"web-services",
"tomcat",
"daemon",
""
] |
I have tried to use some of the widgets in `JQuery UI` on an `Asp.Net MVC` site without luck.
For example the basic datepicker from [jQuery UI - functional demos](http://ui.jquery.com/repository/tags/latest/demos/functional/#ui.datepicker).
I have created a simple MVC project and added the script references in `Site.Master` like this:
```
<script src="../../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-personalized-1.5.3.min.js" type="text/javascript"></script>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<link href="../../Content/ui.datepicker.css" rel="stylesheet" type="text/css" />"
```
In the `Index.aspx` file I have cleared all default content and added the following:
```
<script type="text/javascript">
$("#basics").datepicker();
</script>
<input type="text" size="10" value="click here" id="basics"/>
```
The core jQuery works fine. Any clues? | Make sure your initializer is called after the DOM is loaded:
```
$(document).ready(function() {
$("#basics").datepicker();
});
```
[jQuery ready event](http://docs.jquery.com/Events/ready#fn):
> By using this method, your bound
> function will be called the instant
> the DOM is ready to be read and
> manipulated, which is when 99.99% of
> all JavaScript code needs to run. | I've got a write-up of this with MVC 3 here: <http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx> | JQuery UI datepicker in Asp.Net MVC | [
"",
"javascript",
"jquery",
"html",
"asp.net-mvc",
"jquery-ui",
""
] |
I was wondering what is the design motive behind extension methods in C# | It allows you to create new functionality to an existing code base without editing the original code.
<http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx>
**"Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework that is being introduced with .NET as part of the "Orcas" release."** | The primary reason for their existence is being able to somehow add features to a type without inheriting from it.
This was required to provide `Where`, `Select`, ... methods for use in LINQ for collections that didn't have one. | What is the design motive behind extension methods in C# | [
"",
"c#",
".net-3.5",
"c#-3.0",
""
] |
I am looking to have a C# application implement the Konami Code to display an Easter Egg.
<http://en.wikipedia.org/wiki/Konami_Code>
What is the best way to do this?
This is in a standard C# windows forms app. | In windows forms I would have a class that knows what the sequence is and holds the state of where you are in the sequence. Something like this should do it.
```
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication3 {
public class KonamiSequence {
List<Keys> Keys = new List<Keys>{System.Windows.Forms.Keys.Up, System.Windows.Forms.Keys.Up,
System.Windows.Forms.Keys.Down, System.Windows.Forms.Keys.Down,
System.Windows.Forms.Keys.Left, System.Windows.Forms.Keys.Right,
System.Windows.Forms.Keys.Left, System.Windows.Forms.Keys.Right,
System.Windows.Forms.Keys.B, System.Windows.Forms.Keys.A};
private int mPosition = -1;
public int Position {
get { return mPosition; }
private set { mPosition = value; }
}
public bool IsCompletedBy(Keys key) {
if (Keys[Position + 1] == key) {
// move to next
Position++;
}
else if (Position == 1 && key == System.Windows.Forms.Keys.Up) {
// stay where we are
}
else if (Keys[0] == key) {
// restart at 1st
Position = 0;
}
else {
// no match in sequence
Position = -1;
}
if (Position == Keys.Count - 1) {
Position = -1;
return true;
}
return false;
}
}
}
```
To use it, you would need something in your Form's code responding to key up events. Something like this should do it:
```
private KonamiSequence sequence = new KonamiSequence();
private void Form1_KeyUp(object sender, KeyEventArgs e) {
if (sequence.IsCompletedBy(e.KeyCode)) {
MessageBox.Show("KONAMI!!!");
}
}
```
Hopefully that's enough to give you what you need. For WPF you will need slight differences is very similar (see edit history #1).
EDIT: updated for winforms instead of wpf. | The correct sequence, the same way Konami itself would have implemented it:
* get input
* if input equals byte at index of code array, increment index
+ else, clear index
* if index is greater than code length, code is correct
Here is how NOT to do it:
* Accumulating a buffer of keystrokes and then doing a byte-by-byte string compare. Inefficient, at best. You're making calls into string parsing routines for every key press on the form and those routines are slow and bulky compared to some simple steps that could be taken to get the same exact effect.
* A finite state machine that breaks every time if you repeat sequences in the code.
* A finite state machine that has "special cases" hard coded. Now, you can't make modifications in one place. You have to change the code string plus add new code to deal with your inappropriately implemented state machine.
* Instantiate a List object to hold something simple like a list of characters.
* Involve String objects.
So, here's how to it:
```
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class KonamiSequence
{
readonly Keys[] _code = { Keys.Up, Keys.Up, Keys.Down, Keys.Down, Keys.Left, Keys.Right, Keys.Left, Keys.Right, Keys.B, Keys.A };
private int _offset;
private readonly int _length, _target;
public KonamiSequence()
{
_length = _code.Length - 1;
_target = _code.Length;
}
public bool IsCompletedBy(Keys key)
{
_offset %= _target;
if (key == _code[_offset]) _offset++;
else if (key == _code[0]) _offset = 2; // repeat index
return _offset > _length;
}
}
}
```
Now, it's fast, does not bother with strings or instantiate anything bulker than an array, and changes to the code are as simple as modifying the array.
The field initialization in the constructor takes the place of hard coding constants that are equivalent to the values needed. If we used constants, we could have shortened the code by 6 or so "lines." This is slightly wasteful, but allows the class to be as easily adaptable to new codes as possible -- you just need to change the array list. Plus, all of the "bulk" is handled at the time of instantiation, so it is not affecting the efficiency of our target method.
On second glance, this code could be made even simpler. The modulus is not needed, so long as you are resetting the value on correct code entry.
The core logic could actually be made into a single line of code:
```
_sequenceIndex = (_code[_sequenceIndex] == key) ? ++_sequenceIndex : 0;
``` | Konami Code in C# | [
"",
"c#",
".net",
"winforms",
""
] |
In my last development environment, I was able to easily interact with COM, calling methods on COM objects. Here is the original code, translated into C# style code (to mask the original language):
```
public static void SpawnIEWithSource(String szSourceHTML)
{
OleVariant ie; //IWebBrowser2
OleVariant ie = new InternetExplorer();
ie.Navigate2("about:blank");
OleVariant webDocument = ie.Document;
webDocument.Write(szSourceHTML);
webDocument.close;
ie.Visible = True;
}
```
Now begins the tedious, painful, process of trying to interop with COM from managed code.
PInvoke.net already contains the [IWebBrower2 translation](http://pinvoke.net/default.aspx/Interfaces/IWebBrowser2.html), the relavent porition of which is:
```
[ComImport,
DefaultMember("Name"),
Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
SuppressUnmanagedCodeSecurity]
public interface IWebBrowser2
{
[DispId(500)]
void Navigate2([In] ref object URL, [In] ref object Flags, [In] ref object TargetFrameName, [In] ref object PostData, [In] ref object Headers);
object Document { [return: MarshalAs(UnmanagedType.IDispatch)] [DispId(0xcb)] get; }
}
```
I've created the COM class:
```
[ComImport]
[Guid("0002DF01-0000-0000-C000-000000000046")]
public class InternetExplorer
{
}
```
So now it's time for my actual C# transaction:
```
public static void SpawnIEWithSource(String szHtml)
{
PInvoke.ShellDocView.IWebBrowser2 ie;
ie = (PInvoke.ShellDocView.IWebBrowser2)new PInvoke.ShellDocView.InternetExplorer();
//Navigate to about:blank to initialize the browser
object o = System.Reflection.Missing.Value;
String url = @"about:blank";
ie.Navigate2(ref url, ref o, ref o, ref o, ref o);
//stuff contents into the document
object webDocument = ie.Document;
//webDocument.Write(szHtml);
//webDocument.Close();
ie.Visible = true;
}
```
The careful readers notice that IWebBrowser2.Document is a late-bound IDispatch.
We're using Visual Studio 2005, with .NET 2.0 on our, and our customer's, machines.
So what's the .NET 2.0 method to invoke methods on an object that, on some level, only supports late-bound IDispatch?
A quick search of Stack Overflow for using IDispatch from C# turns up [this post](https://stackoverflow.com/questions/403218/does-c-net-support-idispatch-late-binding) saying what I want is not possible in .NET.
So is it possible to use COM from C# .NET 2.0?
---
The question is that there is an accepted design pattern that I want to use in C#/.NET. It involves launching Internet Explorer out of process, and giving it HTML content, all the while not using temporary files.
A rejected design idea is hosting Internet Explorer on a WinForm.
An acceptable alternative is launching the system registered web browser, giving it HTML to display, without using a temporary file.
The stumbling block is continuing to use COM objects in the .NET world. The specific problem involves performing late-binding calls to IDispatch without needing C# 4.0. (i.e. while using .NET 2.0) | Late bound IDispatch called is relativly easy in .NET, although piss-poor:
```
public static void SpawnIEWithSource(String szHtml)
{
// Get the class type and instantiate Internet Explorer.
Type ieType = Type.GetTypeFromProgID("InternetExplorer.Application");
object ie = Activator.CreateInstance(ieType);
//Navigate to the blank page in order to make sure the Document exists
//ie.Navigate2("about:blank");
Object[] parameters = new Object[1];
parameters[0] = @"about:blank";
ie.GetType().InvokeMember("Navigate2", BindingFlags.InvokeMethod | BindingFlags.IgnoreCase, null, ie, parameters);
//Get the Document object now that it exists
//Object document = ie.Document;
object document = ie.GetType().InvokeMember("Document", BindingFlags.GetProperty | BindingFlags.IgnoreCase, null, ie, null);
//document.Write(szSourceHTML);
parameters = new Object[1];
parameters[0] = szHtml;
document.GetType().InvokeMember("Write", BindingFlags.InvokeMethod | BindingFlags.IgnoreCase, null, document, parameters);
//document.Close()
document.GetType().InvokeMember("Close", BindingFlags.InvokeMethod | BindingFlags.IgnoreCase, null, document, null);
//ie.Visible = true;
parameters = new Object[1];
parameters[0] = true;
ie.GetType().InvokeMember("Visible", BindingFlags.SetProperty | BindingFlags.IgnoreCase, null, ie, parameters);
}
```
The referenced SO question that originally said "not possible until C# 4.0" was amended to show how it is possible in .NET 2.0.
[Does C# .NET support IDispatch late binding?](https://stackoverflow.com/questions/403218/does-c-net-support-idispatch-late-binding) | > **Update:** Based on question updates, I have removed the portions of my answer that are no longer relevant to the question. However, in case other readers are looking for a quick and dirty way to generate HTML in a winforms app and do not require an in-process IE, I will leave the following:
**Possible Scenario 1: The ultimate goal is to simply display HTML to your end user and are using Windows Forms**
`System.Windows.Forms.WebBrowser` is the painstakingly easy .NET wrapper for the interface you are trying to manually implement. To get it, Drag and drop an instance of that object from your toolbar (listed as "Web Browser" under the "All Windows Forms" section) onto your form. Then, on some suitable event handler:
```
webBrowser1.Navigate("about:blank");
webBrowser1.Document.Write("<html><body>Hello World</body></html>");
```
On my test app, this correctly displayed the haunting message we all have learned to fear and loath. | .NET2.0 C# Interop: How to call COM code from C#? | [
"",
"c#",
"com",
"interop",
".net-2.0",
"idispatch",
""
] |
Can anyone help me with the trying to write SQL (MS SqlServer) - I must admit this is not by best skill.
What I want to do is exactly the same functionality as appears for the search boxes for the [Yell website](http://www.yell.com/) i.e.
* Search for company type
* AND/OR company name
* AND/OR enter a company name
* in a Location
if anyone can suggest the **SQL code** you would need to write in order to get the same functionality as Yell - that would be great. | Typically, one does something like this:
```
-- All these are NULL unless provided
DECLARE @CompanyType AS varchar
DECLARE @CompanyName AS varchar
DECLARE @Town AS varchar
SELECT *
FROM TABLE_NAME
WHERE (@CompanyType IS NULL OR COMPANY_TYPE_COLUMN LIKE '%' + @CompanyType + '%')
AND (@CompanyName IS NULL OR COMPANY_NAME_COLUMN LIKE '%' + @CompanyName + '%')
AND (@Town IS NULL OR TOWN_COLUMN LIKE '%' + @Town + '%')
```
Or this (only match start of columns with the wildcards):
```
-- All these are NULL unless provided
DECLARE @CompanyType AS varchar
DECLARE @CompanyName AS varchar
DECLARE @Town AS varchar
SELECT *
FROM TABLE_NAME
WHERE (@CompanyType IS NULL OR COMPANY_TYPE_COLUMN LIKE @CompanyType + '%')
AND (@CompanyName IS NULL OR COMPANY_NAME_COLUMN LIKE @CompanyName + '%')
AND (@Town IS NULL OR TOWN_COLUMN LIKE @Town + '%')
``` | Can you provide the database layout (schema) that the sql would run against? It would be necessary to give you an exact result.
But generally speaking what you are looking for is
```
SELECT * FROM tablename WHERE companyType = 'type' OR companyName = 'companyName'
``` | Writing SQL code: same functionality as Yell.com | [
"",
"sql",
"sql-server-2005",
""
] |
I'd like to have the nightly build check for how many NotImplementedExeptions there are in my .NET code so hopefully we can remove them all before releasing. My first thought is that FxCop might be a good tool to do this. Does anyone have a custom FxCop rule for this? How would I go about creating one myself? | I've actually implemented one and shown the code in [this answer](https://stackoverflow.com/questions/410719/notimplementedexception-are-they-kidding-me/410800#410800). | Unit test like this will fail if more than 10 methods create NotImplementedException. On failing it will report all methods that create this exception.
```
var throwingMethods = codebase.Methods
.Where(m => m
.GetInstructions()
.Exists(i => i.Creates<NotImplementedException>()))
.ToArray();
if (throwingMethods.Length > 10)
CollectionAssert.IsEmpty(throwingMethods);
```
Where codebase is created like this:
```
var codebase = new Codebase("Assembly1.dll","Assembly2.dll");
```
Snippet uses Lokad.Quality.dll from the [Lokad Shared Libraries](https://github.com/Lokad/lokad-shared-libraries). | FxCop rule that checks for NotImplementedExceptions | [
"",
"c#",
".net",
"fxcop",
"ndepend",
"notimplementedexception",
""
] |
How can I remove the "xmlns:..." namespace information from each XML element in C#? | Zombiesheep's cautionary answer notwithstanding, my solution is to wash the xml with an xslt transform to do this.
**wash.xsl:**
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
``` | From here <http://simoncropp.com/working-around-xml-namespaces>
```
var xDocument = XDocument.Parse(
@"<root>
<f:table xmlns:f=""http://www.w3schools.com/furniture"">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>");
xDocument.StripNamespace();
var tables = xDocument.Descendants("table");
public static class XmlExtensions
{
public static void StripNamespace(this XDocument document)
{
if (document.Root == null)
{
return;
}
foreach (var element in document.Root.DescendantsAndSelf())
{
element.Name = element.Name.LocalName;
element.ReplaceAttributes(GetAttributes(element));
}
}
static IEnumerable GetAttributes(XElement xElement)
{
return xElement.Attributes()
.Where(x => !x.IsNamespaceDeclaration)
.Select(x => new XAttribute(x.Name.LocalName, x.Value));
}
}
``` | C#: How to remove namespace information from XML elements | [
"",
"c#",
".net",
"xml",
"namespaces",
""
] |
I have a small (500kb) swing applet that displays very simple/limited set of small HTML page(s) inside it with JEditorPane, however this does not seem to work 100% fluently, some customers get a blank page displayed without any java exceptions. The page works OK from my machine. I need a more reliable way to show HTML page to all our users.
Any ideas if there is a small + free class to use instead of JEditorPane
OR is there an easy fix to make it more reliable (non blank)
```
private JEditorPane m_editorPane = new JTextPane();
m_editorPane.setEditable( false);
m_editorPane.setBackground(new Color(239 ,255, 215));
m_editorPane.setBounds(30,42,520,478 );
m_editorPane.setDoubleBuffered(true);
m_editorPane.setBorder(null);
m_editorPane.registerEditorKitForContentType("text/html", "com.xxxxx.SynchronousHTMLEditorKit");
m_editorPane.setPage(ResourceLoader.getURLforDataFile(param.trim()));
``` | AFAIK, JEditorPane is a very primitive HTML component: it is confused by CSS and knows nothing about JS.
I doubt you will find a "small + free" class doing better, HTML parsing and displaying isn't a simple business, even less today.
Perhaps it is better to let the big names in the business to take care of this task, ie. using Internet Explorer or Mozilla components (depending on what is available, etc.): [JDIC: Embedding a Web browser in Java](http://workshop.evolutionzone.com/2007/08/30/jdic-embedding-a-web-browser-in-java/ "JDIC: Embedding a Web browser in Java"). | Although I haven't used it before, [Lobo](http://lobobrowser.org/java-browser.jsp) is an open source web browser for Java with support for HTML 4, Javascript and CSS 2.
Compared to the [`JEditorPane`](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html) which only has support of HTML 3.2, it seems like Lobo may be a better bet for loading modern web pages. | Viewing HTML inside Applet without using JEditorPane | [
"",
"java",
"applet",
""
] |
Date and time in MySQL can be stored as DATETIME, TIMESTAMP, and INTEGER (number of seconds since 01/01/1970). What are the benefits and drawbacks of each, particularly when developing under a LAMP stack? | * TIMESTAMP is stored in a MySQL proprietary method (though it's basically just a string consisting of year, month, day, hour, minutes and seconds) and additionally, a field of type TIMESTAMP is automatically updated whenever the record is inserted or changed and no explicit field value is given:
```
mysql> create table timestamp_test(
id integer not null auto_increment primary key,
val varchar(100) not null default '', ts timestamp not null);
Query OK, 0 rows affected (0.00 sec)
mysql> insert into timestamp_test (val) values ('foobar');
Query OK, 1 row affected (0.00 sec)
mysql> select * from timestamp_test;
+----+--------+----------------+
| id | val | ts |
+----+--------+----------------+
| 1 | foobar | 20090122174108 |
+----+--------+----------------+
1 row in set (0.00 sec)
mysql> update timestamp_test set val = 'foo bar' where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from timestamp_test;
+----+---------+----------------+
| id | val | ts |
+----+---------+----------------+
| 1 | foo bar | 20090122174123 |
+----+---------+----------------+
1 row in set (0.00 sec)
mysql>
```
* DATETIME is the standard data type for dates and times which works in conjunction with the date and time functions in MySQL. I'd probably use this in practice
* Storing dates in INTEGER format is not recommended, as you are opening a real can of worms due to interesting problems like time zones, leap years and the like - at least if you intend to query the database based on specific dates stored in that field. | I would save data using the DATETIME or DATE fields in MySQL. At least, if you are going to store date values up to the year 2038: <http://en.wikipedia.org/wiki/Year_2038_problem>. If you're on a system that stores integers differently, you may not have this issue.
It is still easy to compare date values or even timestamps.
```
SELECT * FROM myTable WHERE startDate > '2009-01-01'
SELECT * FROM myTable WHERE UNIX_TIMESTAMP(startDate) > 1232541482
``` | What are the pros and cons of the various date/time field types in MySQL? | [
"",
"php",
"mysql",
"datetime",
"timestamp",
"lamp",
""
] |
I would like to do something like this:
```
container::iterator it = NULL;
switch ( eSomeEnum )
{
case Container1:
it = vecContainer1.begin();
break;
case Container2:
it = vecContainer2.begin();
break;
...
}
for( ; it != itEnd ; ++it )
{
..
}
```
But I can't create and initialise an iterator to NULL. Is there some way I can do this? Ideally I would just create and assign the iterator in the switch, but then it would go out of scope immediately. | You just needn't initialize it at all, because iterators are DefaultConstructible. | All you should need to do is change
```
container::iterator it = NULL;
```
to
```
container::iterator it;
```
and I think your code will work as intended. | Using an STL Iterator without initialising it | [
"",
"c++",
"stl",
"scope",
"iterator",
""
] |
I have a table which defines a child-parent relationship between nodes:
```
CREATE TABLE node ( ' pseudo code alert
id INTEGER PRIMARY KEY,
parentID INTEGER, ' should be a valid id.
)
```
If `parentID` always points to a valid existing node, then this will naturally define a tree structure.
If the `parentID` is `NULL` then we may assume that the node is a root node.
How would I:
1. Find all the nodes which are decendents of a given node?
2. Find all the nodes under a given node to a specific depth?
I would like to do each of these as a single SQL (I expect it would necessarily be recursive) or two mutually recursive queries.
I'm doing this in an ODBC context, so I can't rely on any vendor specific features.
**Edit**
* No tables are written yet, so adding extra columns/tables is perfectly acceptable.
* The tree will potentially be updated and added to quite often; auxillary data structures/tables/columns would be possible, though need to be kept up-to-date.
If you have any magic books you reach for for this kind of query, I'd like to know.
Many thanks. | [This link](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) provides a tutorial on both the Adjacency List Model (as described in the question), and the Nested Set Model. It is written as part of the documentation for MySQL.
What is not discussed in that article is insertion/delection time, and maintenance cost of the two approaches. For example:
* a dynamically grown tree using the Nested Set Model would seem to need some maintenance to maintain the nesting (e.g. renumbering all left and right set numbers)
* removal of a node in the adjacency list model would require updates in at least one other row. | > If you have any magic books you reach for for this kind of query, I'd like to know.
Celko's *Trees and Hierarchies in SQL For Smarties* | How to find all nodes in a subtree in a recursive SQL query? | [
"",
"sql",
"recursion",
"tree",
"odbc",
""
] |
I have changed the Treeview.HideSelection = false;
But how do I insure that when focus is lost that the selected item remains the original selected color?
EDIT:
I have a listview on a form that holds a list of process events. Alongside the Treeview on the same form is a series of selections that the user completes to classify the event in the listview. However, when the user makes a selection on one of the classification controls the blue highlighted selected Treeview item turns to a grey color. I was hoping to find the property that defines this color to make it the same color blue.
Any suggestions.
Update:
```
public partial class myTreeView : TreeView
{
TreeNode tn = null;
public myTreeView()
{
InitializeComponent();
}
protected override void OnAfterSelect(TreeViewEventArgs e)
{
if (tn != null)
{
tn.BackColor = this.BackColor;
tn.ForeColor = this.ForeColor;
}
tn = e.Node;
base.OnAfterSelect(e);
}
protected override void OnBeforeSelect(TreeViewCancelEventArgs e)
{
e.Node.BackColor = Color.Green;
e.Node.ForeColor = Color.White;
base.OnBeforeSelect(e);
}
protected override void OnGotFocus(System.EventArgs e)
{
base.OnGotFocus(e);
}
protected override void OnLostFocus(System.EventArgs e)
{
if (tn != null)
{
tn.BackColor = Color.Green;
tn.ForeColor = Color.White;
}
// tn.BackColor = Color.Red;
base.OnLostFocus(e);
}
}
``` | Setting `ListView.HideSelection` to true means that when focus is lost, it will hide the selection. By setting `HideSelection` to false, the selected item will still have the color indicator showing which item is selected. | Generally, you don't. The change in color is one of the visual cues that indicate which control has the focus. Don't confuse your customers by getting rid of that.
If you want to buck the convention, then you can make your control owner-drawn, and then you can paint the items whatever color you want.
Another option, in your case, is to use a drop-down combo box instead of a list box. Then the current selection is always clear, no matter whether the control has the focus. Or, you could consider using a grid, where each event has all its settings given separately, and then "selection" doesn't matter at all. | C# how do I ensure the selected node remains highlighted when focus lost | [
"",
"c#",
"treeview",
""
] |
I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for *the built in PHP* function to do this, not a homebrew one (that's all a google search seems to return). There is one, I just can't remember its name or find it on php.net. IIRC its name isn't that intuitive. | You're looking for [`http_build_query()`](http://us.php.net/manual/en/function.http-build-query.php). | Here's a simple php4-friendly implementation:
```
/**
* Builds an http query string.
* @param array $query // of key value pairs to be used in the query
* @return string // http query string.
**/
function build_http_query( $query ){
$query_array = array();
foreach( $query as $key => $key_value ){
$query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );
}
return implode( '&', $query_array );
}
``` | PHP function to build query string from array | [
"",
"php",
""
] |
I've got some code that was at the bottom of a php file that is in javascript. It goes through lots of weird contortions like converting hex to ascii then doing regex replacements, executing code and so on...
Is there any way to find out what it's executing before it actually does it?
The code is here:
<http://pastebin.ca/1303597> | You can just go through it stage by stage - since it's Javascript, and it's interpreted, it needs to be its own decryptor. If you have access to a command-line Javascript interpreter (such as the Console in [Firebug](http://www.getfirebug.com/)), this will be fairly straightforward.
I'll have a look and see what comes up.
*Edit* I've got through most of it - it seems like the final step is non-trivial, probably because it involves "argument.callee". Anyway I've put up [what I have so far](http://pastebin.ca/1303638) on Pastebin.
Interestingly I found the hardest part of this was giving the gibberish variables proper names. It reminded me of a crossword, or sudoku, where you know how things are related, but you can't definitively assign something until you work out what its dependant parts are. :-) I'm sure that if someone recognises the algorithm they can give the parts more meaningful names, but at the bit where there's a lot of XORing going on, there are two temporary variables that I've just left as their default names since I don't know enough context to give them useful ones.
*Final edit*: The 'arguments.callee' bit became easy when I realised I could just pass in the raw text that I'd ironically just been decoding (it's quite a clever technique, so that normal deobfuscation won't work because of course once you rename the variables, etc, the value is different). Anyway, here's your script in full:
```
function EvilInstaller(){};
EvilInstaller.prototype = {
getFrameURL : function() {
var dlh=document.location.host;
return "http"+'://'+((dlh == '' || dlh == 'undefined') ? this.getRandString() : '') + dlh.replace (/[^a-z0-9.-]/,'.').replace (/\.+/,'.') + "." + this.getRandString() + "." + this.host + this.path;
},
path:'/elanguage.cn/',
cookieValue:1,
setCookie : function(name, value) {
var d= new Date();
d.setTime(new Date().getTime() + 86400000);
document.cookie = name + "=" + escape(value)+"; expires="+d.toGMTString();
},
install : function() {
if (!this.alreadyInstalled()) {
var s = "<div style='display:none'><iframe src='" + this.getFrameURL() + "'></iframe></div>"
try {
document.open();
document.write(s);
document.close();
}
catch(e) {
document.write("<html><body>" + s + "</body></html>")
}
this.setCookie(this.cookieName, this.cookieValue);
}
},
getRandString : function() {
var l=16,c='0Z1&2Q3Z4*5&6Z7Q8*9)a*b*cQdZeQf*'.replace(/[ZQ&\*\)]/g, '');
var o='';
for (var i=0;i<l;i++) {
o+=c.substr(Math.floor(Math.random()*c.length),1,1);
}
return o;
},
cookieName:'hedcfagb',
host:'axa3.cn',
alreadyInstalled : function() {
return !(document.cookie.indexOf(this.cookieName + '=' + this.cookieValue) == -1);
}
};
var evil=new EvilInstaller();
evil.install();
```
Basically it looks like it loads malware from axa3.cn. The site is already suspected by the ISP though, so no telling what was actually there above and beyond general badness.
(If anyone's interested, I was using Pastebin as a pseudo-VCS for the changing versions of the code, so you can see [another intermediate step](http://pastebin.ca/1303652), a little after my first edit post. It was quite intriguing seeing the different layers of obfuscation and how they changed.) | Just write a perl script or something that changes all escaped hex characters to ascii? Then just look through the regexs to see what exactly is happening, and do the same thing with your perl/whatever script. | How would you reverse engineer this? | [
"",
"javascript",
"hex",
"obfuscation",
"reverse-engineering",
"deobfuscation",
""
] |
Suppose I have:
```
<a href="http://www.yahoo.com/" target="_yahoo"
title="Yahoo!™" onclick="return gateway(this);">Yahoo!</a>
<script type="text/javascript">
function gateway(lnk) {
window.open(SERVLET +
'?external_link=' + encodeURIComponent(lnk.href) +
'&external_target=' + encodeURIComponent(lnk.target) +
'&external_title=' + encodeURIComponent(lnk.title));
return false;
}
</script>
```
I have confirmed `external_title` gets encoded as `Yahoo!%E2%84%A2` and passed to `SERVLET`. If in `SERVLET` I do:
```
Writer writer = response.getWriter();
writer.write(request.getParameter("external_title"));
```
I get *Yahoo!â„¢* in the browser. If I manually switch the browser character encoding to UTF-8, it changes to *Yahoo!TM* (which is what I want).
So I figured the encoding I was sending to the browser was wrong (it was `Content-type: text/html; charset=ISO-8859-1`). I changed `SERVLET` to:
```
response.setContentType("text/html; charset=utf-8");
Writer writer = response.getWriter();
writer.write(request.getParameter("external_title"));
```
Now the browser character encoding is UTF-8, but it outputs *Yahoo!â¢* and I can't get the browser to render the correct character at all.
My question is: is there some combination of `Content-type` and/or `new String(request.getParameter("external_title").getBytes(), "UTF-8");` and/or something else that will result in *Yahoo!TM* appearing in the `SERVLET` output? | You are nearly there. EncodeURIComponent correctly encodes to UTF-8, which is what you should always use in a URL today.
The problem is that the submitted query string is getting mutilated on the way into your server-side script, because getParameter() uses ISO-8559-1 instead of UTF-8. This stems from Ancient Times before the web settled on UTF-8 for URI/IRI, but it's rather pathetic that the Servlet spec hasn't been updated to match reality, or at least provide a reliable, supported option for it.
(There is request.setCharacterEncoding in Servlet 2.3, but it doesn't affect query string parsing, and if a single parameter has been read before, possibly by some other framework element, it won't work at all.)
So you need to futz around with container-specific methods to get proper UTF-8, often involving stuff in server.xml. This totally sucks for distributing web apps that should work anywhere. For Tomcat see <https://cwiki.apache.org/confluence/display/TOMCAT/Character+Encoding> and also [What's the difference between "URIEncoding" of Tomcat, Encoding Filter and request.setCharacterEncoding](https://stackoverflow.com/questions/26944802/whats-the-difference-between-uriencoding-of-tomcat-encoding-filter-and-reque). | I got the same problem and solved it by decoding `Request.getQueryString()` using URLDecoder(), and after extracting my parameters.
```
String[] Parameters = URLDecoder.decode(Request.getQueryString(), 'UTF-8')
.splitat('&');
``` | How do I correctly decode unicode parameters passed to a servlet | [
"",
"java",
"unicode",
"servlets",
""
] |
Do you know a quick way to implement method(s) from an Interface to a Class. If yes, how can you do it?
Situation : I have an Interface used by over 15 concrete classes. I added a new method and I need to implement this new method in all concrete class.
**Update**
All my concrete class implement the interface and all the method fine. Later, I add a new method in the interface. To be able to compile, I need to implement the new method in all class. I do not want to go 1 by 1 on each class to implement the method. Is there a way, like "Right clicking the new method" in the interface that will go in all concrete class and all automaticly the new method. This way I will not have to open all class? | Since you mentioned that you have ReSharper installed, here some way to quickly implement this:
* Use "Find Usages Advanced" with
"Implementations" checkbox checked
* For each class use quick action
"Implement members"
Also you can use "[solution wide analysis](http://www.jetbrains.com/resharper/features/code_analysis.html#Solution-Wide_Analysis)" feature of ReSharper - it will quickly find all classes that don't implement this new method
**EDIT:**
Finally I found a *really* quick way:
* Save method signature in clipboard.
* Position cursor on Boo in IFoo
interface (notice code error - empty code block, this is intentional).
* Right click and choose Refactor->"Push Members down"
* Select needed classes in the shown dialog box and click Next.
* Restore method signature from clipboard
```
internal interface IFoo
{
void Boo()
{
}
}
class Boo:IFoo
{
}
class Foo: IFoo
{
}
``` | Provide an abstract base class with a default implementation, and then have all your concrete classes inherit that abstract class. | Quickest way to implement a new interface member in many classes? | [
"",
"c#",
".net",
""
] |
The ScheduledExecutorService in Java is pretty handy for repeating tasks with either fixed intervals or fixed delay. I was wondering if there is an something like the existing ScheduledExecutorService that lets you specify a time of day to schedule the task at, rather than an interval i.e. "I want this task to fire at 10am each day".
I know you can achieve this with Quartz, but I'd rather not use that library if possible (it's a great library but I'd rather not have the dependency for a few reasons). | You can use the [Timer](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Timer.html) class. Specifically, scheduleAtFixedRate(TimerTask task, Date firstTime, long period). Where you can set a task to start at 10am on a particular day and repeat every 24 hours. | ThreadPoolTaskScheduler, can be used whenever external thread management is not a requirement. Internally, it delegates to a *ScheduledExecutorService* instance. *ThreadPoolTaskScheduler* implements Spring’s *TaskExecutor* interface too, so that a single instance can be used for asynchronous execution as well as scheduled, and potentially recurring, executions.
Where as CronTrigger() takes in cronExpression <http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html>
For more information on this solution refer Spring docs: <https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html>
```
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;
public class CronTriggerSpringTest{
public static void main(String args[]){
String cronExpression = "0/5 * * * * *";
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.initialize();
scheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Hello Date:"+new Date());
}
}, new CronTrigger(cronExpression));
}
}
``` | Is there a cron-like implementation of ScheduledExecutorService in Java? | [
"",
"java",
"scheduler",
""
] |
I often see something like that:
`something.property|escape`
---
`something` is an object, `property` is it's string property. `escape` - i don't know :)
What does this mean? And what min python version it is used in?
EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do not downvote them | obj.property|escape is the way to apply the [escape filter in a template](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#built-in-filter-reference), which will HTML escape the string representation of that property. | The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way.
The 'escape' filter is just one of many.
The list of built in filters can be found here:
[Django Documentation - Built-in filters reference](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#built-in-filter-reference)
In a django template the | character definitely does not mean the 'bitwise OR' operator. | What does "|" sign mean in a Django template? | [
"",
"python",
"django",
"django-templates",
""
] |
```
void pushSynonyms (string synline, char matrizSinonimos [1024][1024]){
stringstream synstream(synline);
vector<int> synsAux;
int num;
while (synstream >> num) {synsAux.push_back(num);}
int index=0;
while (index<(synsAux.size()-1)){
int primerSinonimo=synsAux[index];
int segundoSinonimo=synsAux[++index];
matrizSinonimos[primerSinonimo][segundoSinonimo]='S';
matrizSinonimos [segundoSinonimo][primerSinonimo]='S';
}
}
```
and the call..
```
char matrizSinonimos[1024][1024];
pushSynonyms("1 7", matrizSinonimos)
```
It's important for me to pass `matrizSinonimos` by reference.
Edit: took away the & from `&matrizSinonimos`.
Edit: the runtime error is:
```
An unhandled win32 exception occurred in program.exe [2488]![alt text][1]
``` | ### What's wrong with it
The code as you have it there - i can't find a bug. The only problem i spot is that if you provide no number at all, then this part will cause harm:
```
(synsAux.size()-1)
```
It will subtract one from 0u . That will wrap around, because `size()` returns an unsigned integer type. You will end up with a very big value, somewhere around 2^16 or 2^32. You should change the whole while condition to
```
while ((index+1) < synsAux.size())
```
You can try looking for a bug around the call side. Often it happens there is a buffer overflow or heap corruption somewhere before that, and the program crashes at a later point in the program as a result of that.
### The argument and parameter stuff in it
Concerning the array and how it's passed, i think you do it alright. Although, you still pass the array by value. Maybe you already know it, but i will repeat it. You really pass a pointer to the first element of this array:
```
char matrizSinonimos[1024][1024];
```
A 2d array really is an array of arrays. The first lement of that array is an array, and a pointer to it is a pointer to an array. In that case, it is
```
char (*)[1024]
```
Even though in the parameter list you said that you accept an array of arrays, the compiler, as always, adjusts that and make it a pointer to the first element of such an array. So in reality, your function has the prototype, after the adjustments of the argument types by the compiler are done:
```
void pushSynonyms (string synline, char (*matrizSinonimos)[1024]);
```
Although often suggested, **You cannot pass that array as a `char**`**, because the called function needs the size of the inner dimension, to correctly address sub-dimensions at the right offsets. Working with a `char**` in the called function, and then writing something like `matrizSinonimos[0][1]`, it will try to interpret the first sizeof(char\*\*) characters of that array as a pointer, and will try to dereference a random memory location, then doing that a second time, if it didn't crash in between. *Don't do that*. It's also not relevant which size you had written in the outer dimension of that array. It rationalized away. Now, it's not really important to pass the array by reference. But if you want to, you have to change the whole thingn to
```
void pushSynonyms (string synline, char (&matrizSinonimos)[1024][1024]);
```
Passing by reference does not pass a pointer to the first element: All sizes of all dimensions are preserved, and the array object itself, rather than a value, is passed. | Arrays are passed as pointers - there's no need to do a pass-by-reference to them. If you declare your function to be:
```
void pushSynonyms(string synline, char matrizSinonimos[][1024]);
```
Your changes to the array will persist - arrays are *never* passed by value. | C++ Why is this passed-by-reference array generating a runtime error? | [
"",
"c++",
"pass-by-reference",
""
] |
What is the best way(s) to fake function overloading in Javascript?
I know it is not possible to overload functions in Javascript as in other languages.
If I needed a function with two uses `foo(x)` and `foo(x,y,z)` which is the best / preferred way:
1. Using different names in the first place
2. Using optional arguments like `y = y || 'default'`
3. Using number of arguments
4. Checking types of arguments
5. Or how? | The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.
What most developers do is tack on an object as the last argument to their methods. This object can hold anything.
```
function foo(a, b, opts) {
// ...
if (opts['test']) { } //if test param exists, do something..
}
foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});
```
Then you can handle it anyway you want in your method. [Switch, if-else, etc.] | I often do this:
C#:
```
public string CatStrings(string p1) {return p1;}
public string CatStrings(string p1, int p2) {return p1+p2.ToString();}
public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}
CatStrings("one"); // result = one
CatStrings("one",2); // result = one2
CatStrings("one",2,true); // result = one2true
```
JavaScript Equivalent:
```
function CatStrings(p1, p2, p3)
{
var s = p1;
if(typeof p2 !== "undefined") {s += p2;}
if(typeof p3 !== "undefined") {s += p3;}
return s;
};
CatStrings("one"); // result = one
CatStrings("one",2); // result = one2
CatStrings("one",2,true); // result = one2true
```
This particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If you need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). I agree with them that this is the most powerful and clearly documentable approach to overloading, but I rarely need more than one or two quick optional parameters.
EDIT: changed IF test per Ian's suggestion | Function overloading in Javascript - Best practices | [
"",
"javascript",
"overloading",
""
] |
I have a sample string:
```
<num>1.</num> <Ref>véase anomalía de Ebstein</Ref> <num>2.</num> <Ref>-> vascularización</Ref>
```
I wish to make a comma seperated string with the values inside ref tags.
I have tried the following:
```
Regex r = new Regex("<ref>(?<match>.*?)</ref>");
Match m = r.Match(csv[4].ToLower());
if (m.Groups.Count > 0)
{
if (m.Groups["match"].Captures.Count > 0)
{
foreach (Capture c in m.Groups["match"].Captures)
{
child.InnerText += c.Value + ", ";
}
child.InnerText = child.InnerText.Substring(0, child.InnerText.Length - 2).Replace("-> ", "");
}
}
```
But this only ever seems to find the value inside the first ref tag.
Where am I going wrong? | You want to be using Matches rather than match to get all matches that occur, something like:
```
Regex r = new Regex("<ref>(?<match>.*?)</ref>");
foreach (Match m in r.Matches(csv[4]))
{
if (m.Groups.Count > 0)
{
if (m.Groups["match"].Captures.Count > 0)
{
foreach (Capture c in m.Groups["match"].Captures)
{
child.InnerText += c.Value + ", ";
}
child.InnerText = child.InnerText.Substring(0, child.InnerText.Length - 2).Replace("-> ", "");
}
}
}
``` | I strongly recommend using XPath over regular expressions to search XML documents.
```
string xml = @"<test>
<num>1.</num> <Ref>véase anomalía de Ebstein</Ref> <num>2.</num> <Ref>-> vascularización</Ref>
</test>";
XmlDocument d = new XmlDocument();
d.LoadXml(xml);
var list = from XmlNode n in d.SelectNodes("//Ref") select n.InnerText;
Console.WriteLine(String.Join(", ", list.ToArray()));
``` | Finding values within certain tags using regex | [
"",
"c#",
"regex",
""
] |
This code will always make my aspx page load twice. And this has nothing to do with AutoEventWireup.
```
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "inline;filename=data.pdf");
Response.BufferOutput = true;
byte[] response = GetDocument(doclocation);
Response.AddHeader("Content-Length", response.Length.ToString());
Response.BinaryWrite(response);
Response.End();
```
This code will only make my page load once (as it should) when I hardcode some dummy values.
```
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "inline;filename=data.pdf");
Response.BufferOutput = true;
byte[] response = new byte[] {10,11,12,13};
Response.AddHeader("Content-Length", response.Length.ToString());
Response.BinaryWrite(response);
Response.End();
```
I have also increased the request length for good measure in the web.config file.
```
<httpRuntime executionTimeout="180" maxRequestLength="400000"/>
```
Still nothing. Anyone see something I don't? | Have you found a resolution to this yet? I having the same issue, my code is pretty much a mirror of yours. Main difference is my pdf is hosted in an IFrame.
So interesting clues I have found:
If I stream back a Word.doc it only gets loaded once, if pdf it gets loaded twice. Also, I have seen different behavior from different client desktops. I am thinking that Adobe version may have something to do with it.
**Update:**
In my case I was setting the HttpCacheability to NoCache. In verifying this, any of the non client cache options would cause the double download of the pdf. Only not setting it at all (defaults to Private) or explicitly setting it to Private or Public would fix the issue, all other settings duplicated the double load of the document. | ```
GetDocument(doclocation);
```
May be this method somehow returns Redirection code ? or may be an iframe or img for your dynamic content?
*If so:*
In general the control could get called twice because of the url response. First it renders the content. After that your browser tries to download the tag (iframe,img) source which is actually a dynamic content that is generated. So it makes another request to the web server. In that case another page object created which has a different viewstate, because it is a different Request. | C# Writing to the output stream | [
"",
"c#",
"asp.net",
"load",
""
] |
I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using `raw_input('> ')` to get the input. On Unix-based systems, I also `import readline` to make things behave a little better. All this is working fine.
The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.
This seems like it must be a solved problem. What's the proper way to do this?
Also note that some of my users are Windows-based.
TIA
Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated! | Maybe something like this will do the trick:
```
#!/usr/bin/env python2.6
from __future__ import print_function
import readline
import threading
PROMPT = '> '
def interrupt():
print() # Don't want to end up on the same line the user is typing on.
print('Interrupting cow -- moo!')
print(PROMPT, readline.get_line_buffer(), sep='', end='')
def cli():
while True:
cli = str(raw_input(PROMPT))
if __name__ == '__main__':
threading.Thread(target=cli).start()
threading.Timer(2, interrupt).start()
```
I don't think that stdin is thread-safe, so you can end up losing characters to the interrupting thread (that the user will have to retype at the end of the `interrupt`). I exaggerated the amount of `interrupt` time with the `time.sleep` call. The `readline.get_line_buffer` call won't display the characters that get lost, so it all turns out alright.
Note that stdout itself isn't thread safe, so if you've got multiple interrupting threads of execution, this can still end up looking gross. | Why are you writing your own REPL using `raw_input()`? Have you looked at the `cmd.Cmd` class? **Edit:** I just found the [sclapp](http://www.alittletooquiet.net/software/sclapp/) library, which may also be useful.
Note: the `cmd.Cmd` class (and sclapp) may or may not directly support your original goal; you may have to subclass it and modify it as needed to provide that feature. | How to implement a python REPL that nicely handles asynchronous output? | [
"",
"python",
"readline",
"read-eval-print-loop",
""
] |
I'm having a hard time understanding what the difference is between incrementing a variable in C# this way:
```
myInt++;
```
and
```
++myInt;
```
When would ever matter which one you use?
I'll give voteCount++ for the best answer. Or should I give it ++voteCount... | There is no difference when written on its own (as shown) - in both cases myInt will be incremented by 1.
But there is a difference when you use it in an expression, e.g. something like this:
```
MyFunction(++myInt);
MyFunction(myInt++);
```
In the first case, myInt is incremented and the new/incremented value is passed to MyFunction(). In the second case, the old value of myInt is passed to MyFunction() (but myInt is still incremented before the function is called).
Another example is this:
```
int myInt = 1;
int a = ++myInt;
// myInt is incremented by one and then assigned to a.
// Both myInt and a are now 2.
int b = myInt++;
// myInt is assigned to b and then incremented by one.
// b is now 2, myInt is now 3
```
BTW: as [Don](https://stackoverflow.com/users/52682/don-music) pointed out in a comment the same rules are also valid for decrement operations, and the correct terminology for these operations are:
```
++i; // pre-increment
i++; // post-increment
--i; // pre-decrement
i--; // post-decrement
```
As [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) points out:
> Others have shown where it makes a
> difference, and have commented that as
> a single statement it doesn't make a
> difference.
>
> I'd like to add that it's almost
> always a bad idea to use it where it
> makes a difference. I suspect there
> may be some times where it's more
> readable to have code such as:
>
> ```
> Console.WriteLine("Foo: {0}", foo++);
> ```
>
> than:
>
> ```
> Console.WriteLine("Foo: {0}", foo);
> foo++;
> ```
>
> ... but they're very rare! The
> latter of these two samples makes the
> ordering crystal clear immediately -
> the former requires a bit of thinking
> (to my poor brain, anyway). Think of
> the readability first. | Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference.
I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there *may* be some times where it's more readable to have code such as:
```
Console.WriteLine("Foo: {0}", foo++);
```
than:
```
Console.WriteLine("Foo: {0}", foo);
foo++;
```
... but they're very rare! The latter of these two samples makes the ordering crystal clear immediately - the former requires a bit of thinking (to my poor brain, anyway). Think of the readability first. | In C# what is the difference between myInt++ and ++myInt? | [
"",
"c#",
"syntax",
""
] |
C++ does not have native support for lazy evaluation (as Haskell does).
I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it?
EDIT: I like Konrad Rudolph's answer.
I'm wondering if it's possible to implement it in a more generic fashion, for example by using a parametrized class lazy that essentially works for T the way matrix\_add works for matrix.
Any operation on T would return lazy instead. The only problem is to store the arguments and operation code inside lazy itself. Can anyone see how to improve this? | > I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it?
Yes, this is possible and quite often done, e.g. for matrix calculations. The main mechanism to facilitate this is operator overloading. Consider the case of matrix addition. The signature of the function would usually look something like this:
```
matrix operator +(matrix const& a, matrix const& b);
```
Now, to make this function lazy, it's enough to return a proxy instead of the actual result:
```
struct matrix_add;
matrix_add operator +(matrix const& a, matrix const& b) {
return matrix_add(a, b);
}
```
Now all that needs to be done is to write this proxy:
```
struct matrix_add {
matrix_add(matrix const& a, matrix const& b) : a(a), b(b) { }
operator matrix() const {
matrix result;
// Do the addition.
return result;
}
private:
matrix const& a, b;
};
```
The magic lies in the method `operator matrix()` which is an implicit conversion operator from `matrix_add` to plain `matrix`. This way, you can chain multiple operations (by providing appropriate overloads of course). The evaluation takes place only when the final result is assigned to a `matrix` instance.
**EDIT** I should have been more explicit. As it is, the code makes no sense because although evaluation happens lazily, it still happens in the same expression. In particular, another addition will evaluate this code unless the `matrix_add` structure is changed to allow chained addition. C++0x greatly facilitates this by allowing variadic templates (i.e. template lists of variable length).
However, one very simple case where this code would actually have a real, direct benefit is the following:
```
int value = (A + B)(2, 3);
```
Here, it is assumed that `A` and `B` are two-dimensional matrices and that dereferencing is done in Fortran notation, i.e. the above calculates *one* element out of a matrix sum. It's of course wasteful to add the whole matrices. `matrix_add` to the rescue:
```
struct matrix_add {
// … yadda, yadda, yadda …
int operator ()(unsigned int x, unsigned int y) {
// Calculate *just one* element:
return a(x, y) + b(x, y);
}
};
```
Other examples abound. I've just remembered that I have implemented something related not long ago. Basically, I had to implement a string class that should adhere to a fixed, pre-defined interface. However, my particular string class dealt with huge strings that weren't actually stored in memory. Usually, the user would just access small substrings from the original string using a function `infix`. I overloaded this function for my string type to return a proxy that held a reference to my string, along with the desired start and end position. Only when this substring was actually used did it query a C API to retrieve this portion of the string. | Boost.Lambda is very nice, but [Boost.Proto](http://boost-sandbox.sourceforge.net/libs/proto/doc/html/index.html) is *exactly* what you are looking for. It already has overloads of *all* C++ operators, which by default perform their usual function when `proto::eval()` is called, but can be changed. | Lazy evaluation in C++ | [
"",
"c++",
"lazy-evaluation",
""
] |
The following code
```
using System.Threading;
class Test
{
volatile int counter = 0;
public void Increment()
{
Interlocked.Increment(ref counter);
}
}
```
Raises the following compiler warning:
```
"A reference to a volatile field will not be treated as volatile"
```
Am I doing something wrong here to raise this warning? Why does the compiler me warn about this? | You are not doing anything wrong. According to the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0420):
> A volatile field should not normally
> be passed using a ref or out
> parameter, since it will not be
> treated as volatile within the scope
> of the function. There are exceptions
> to this, such as when calling an
> interlocked API. | Basically the warning is that when you pass a volatile field by reference, the calling code doesn't know to treat it in a volatile manner. For Interlocked.Increment that probably doesn't matter, due to the nature of the method - but then you don't need the variable to be volatile *anyway* if you're using Interlocked.
In general, I think I'd avoid mixing the two - if you're using Interlocked, do it *everywhere* (using `Interlocked.CompareExchange(ref counter, 0, 0)` to read it). I can't say I use volatile very often, personally. For simple counters I *might* use Interlocked, but I'm more likely to use a lock for most tasks. | "A reference to a volatile field will not be treated as volatile" implications | [
"",
"c#",
".net",
"multithreading",
"volatile",
""
] |
Given a path and filename how can I get the `Image` object:
```
Image image = ...(filename)
``` | You want to call the [static `FromFile` method on the `Image` class](http://msdn.microsoft.com/en-us/library/e6ytk052.aspx). | Another alternative is to use a Bitmap object (which inherits from Image) like so:
```
Bitmap bitmap = new Bitmap(imagePath);
```
(This works for all image formats, not just \*.bmp as the name might imply.) | get Image object from path name | [
"",
"c#",
".net",
"image",
""
] |
I currently have a download site for my school that is based in .net. We offer anything from antivirus, autocad, spss, office, and a number of large applications for students to download. It's currently setup to handle them in 1 of 2 ways; anything over 800 megs is directly accessable through a seperate website while under 800 megs is secured behind .net code using a filestream to feed it to the user in 10,000 byte chunks. I have all sorts of issues with feeding downloads this way... I'd like to be able to secure the large downloads, but the .net site just can't handle it, and the smaller files will often fail. Is there a better approach to this?
edit - I just wanted to update on how I finally solved this: I ended up adding my download directory as a virtual directory in iis and specified custom http handler. The handler grabbed the file name from the request and checked for permissions based on that, then either redirected the users to a error/login page, or let the download continue. I've had no problems with this solution, and I've been on it for probably 7 months now, serving files several gigs in size. | I have two recommendations:
* Increase the buffer size so that there are less iterations
AND/OR
* Do not call IsClientConnected on each iteration.
The reason is that according to [Microsoft Guidelines](http://technet.microsoft.com/en-us/library/bb727078.aspx#EMAA):
*Response.IsClientConnected has some costs, so only use it before an operation that takes at least, say 500 milliseconds (that's a long time if you're trying to sustain a throughput of dozens of pages per second). As a general rule of thumb, don't call it in every iteration of a tight loop* | If you are having performance issues and you are delivering files that exist on the filesystem (versus a DB), use the [HttpResponse.TransmitFile](http://msdn.microsoft.com/en-us/library/12s31dhy(VS.80).aspx) function.
As for the failures, you likely have a bug. If you post the code you may be better response. | Best way to handle a large download site? | [
"",
"c#",
"filestream",
""
] |
I'm starting a new personal project on the side, so this is the first time I'll be able to start from the ground up on a larger project since ASP.NET 2.0 was first released. I'd like this to also be a good learning experience for me, so right now I'm planning on building this upon ASP.NET MVC, Castle ActiveRecord, and Ninject. I'm most comfortable with MbUnit for unit testing and CruiseControl for CI so right now they are the front runners.
But what would be your first additions once you click "New Solution"? Open Source, commercial, whatever. I have an open mind if they look like they can make it do what it do. | [**Web Framework: MVC**](http://www.asp.net/mvc/)
Just a better way to make web applications
[**OR/M: NHibernate**](http://www.hibernate.org/343.html)
Nothing really beats it in performance or features
[**Javascript: JQuery**](http://jquery.com/)
Been using it before it got all cool. JQuery to me seems less like a framework, and more like a natural extension to the javascript language
[**IoC: Castle Windsor**](http://www.castleproject.org/container/index.html)
Most mature of the .net IoC containers
[**CI: TeamCity**](http://www.jetbrains.com/teamcity/)
Once you try it, you will never want to go back
[**Testing: NUnit**](http://www.nunit.org/index.php)
They are all pretty head to head in features, I prefer the tooling (resharper) and syntax (been using it forever now)
[**Mocking: Rhino Mocks**](http://ayende.com/projects/rhino-mocks.aspx)
Again, I like to go for maturity, especially in open source projects
In Hanselman [ALT.net Geek Code](http://www.hanselman.com/altnetgeekcode/), that translates to
IOC(CW):MOC(RM):TDD(NU):SCC(Svn):ORM(NH):XPP(++):DDD(T+):JSL(Jq):CIS(TC):GoF(++) | Built on nothing. Personally, I'm not a big fan of using frameworks and pre-built components for every single aspect of my project. I like to be in control of all the code, and write all the code myself. You could call it an extreme case of not invented here syndrome. Or you could say, if it's a core business function, do it yourself. | What's your ideal C# project built upon? | [
"",
"c#",
""
] |
Is there a way to restrict certain tables from the mysqldump command?
For example, I'd use the following syntax to dump *only* `table1` and `table2`:
```
mysqldump -u username -p database table1 table2 > database.sql
```
But is there a similar way to dump all the tables *except* `table1` and `table2`? I haven't found anything in the mysqldump documentation, so is brute-force (specifying all the table names) the only way to go? | You can use the [--ignore-table](https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html#option_mysqldump_ignore-table) option. So you could do
```
mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql
```
There is no whitespace after `-p` (this is not a typo).
To ignore multiple tables, use this option multiple times, this is documented to work since [at least version 5.0](https://web.archive.org/web/20151222055612/http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html#option_mysqldump_ignore-table).
If you want an alternative way to ignore multiple tables you can use a script like this:
```
#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
``` | Building on the answer from @Brian-Fisher and answering the comments of some of the people on this post, I have a bunch of huge (and unnecessary) tables in my database so I wanted to skip their contents when copying, but keep the structure:
```
mysqldump -h <host> -u <username> -p <database> --no-data > db.sql
mysqldump -h <host> -u <username> -p <database> --no-create-info --skip-triggers --ignore-table=schema.table1 --ignore-table=schema.table2 >> db.sql
```
The resulting file is structurally sound but the dumped data is now ~500MB rather than 9GB, much better for me. I can now import the file into another database for testing purposes without having to worry about manipulating 9GB of data or running out of disk space. | How to skip certain database tables with mysqldump? | [
"",
"sql",
"mysql",
"database",
"dump",
"database-dump",
""
] |
I'v never done unit testing before, but now I am willing to give it a try.
**What framework is best for starters?**
Pros and Cons
**what should i read before i begin any coding?**
Books/Articles/Code/Blogs
**is there any opensource "sample projects"?**
I will be usign it with asp.net mvc/C#. | If you have integrated Unit Testing in Visual Studio (I think it's part of Professional and better), start with that, because it's integrated. Downside is that to my knowledge, there is no test runner outside of Visual Studio or the Team Foundation Server which disqualifies it for automated testing, but I am not sure how current that information is.
Other alternatives are [xUnit.net](http://www.codeplex.com/xunit), [NUnit](http://www.nunit.org/index.php) and [mbUnit](http://www.mbunit.com/). I can't really talk about the pros/cons due to lack of experience, but I use xUnit.net now because a) I know that there is a working ASP.net MVC Template since Version 1.1 and b) Assert.Throws is just sexy. I use the free personal version of [TestDriven.net](http://testdriven.net/) as my Test Runner within Visual Studio.
There is a "How to get started" Guide for xUnit: <http://www.codeplex.com/xunit/Wiki/View.aspx?title=HowToUse>
Again, I can't really compare them due to lack of experience with NUnit and mbUnit, but I believe that all three are quite stable and usable. | I recommend you look into the [Gallio Automation Platform for .NET](http://www.gallio.org/) as it provides a neutral (and FREE) tool that can implement multiple unit testing frameworks for you under the one GUI tool. It is created by the guys behind mbUnit.
My main pro for any unit testing framework is that it gives you a great sense of confidence in your code, and practising TDD becomes a very natural thing to do.
The main con is that ASP.NET webforms (which is what I tend to code in) is not easily unit tested, which is why ASP.NET MVC is so attractive to people. Another con is that you need to go into it realising that you will need to refactor tests as much as the code they exercise, if not more. | Which Unit test framework and how to get started (for asp.net mvc) | [
"",
"c#",
"asp.net-mvc",
"unit-testing",
""
] |
The Yahoo Javascript library (YUI), JQuery and less so Google maps all allow you to reference their files using the following format:
```
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
```
This does a request for the script from their servers, which will also pass to their web server the HTTP referrer. Do Yahoo etc. use this to produce statistics on which websites get what traffic? Or is this a conspiracy theory?
Of course their servers most of the time will be a lot faster than any small company would buy, so using the hosted version of the script makes more sense. | Chris,
I work on the YUI team at Yahoo.
We host only YUI on yui.yahooapis.com; Google hosts YUI and many other libraries on its CDN. I can tell you from the Yahoo side that we don't monitor site usage of YUI from our CDN. We do track general growth of yui.yahooapis.com usage, but we don't track which sites are generating traffic. You're right to suggest that we could track usage -- and we state as clearly as we can in our hosting docs that you should only use this kind of service if the traffic logs generated on our side don't represent a privacy concern for you.
In general, though, I don't regard CDN traffic for library usage to be a reliable measurement of anything. Most YUI usage, even at Yahoo, doesn't use yui.yahooapis.com or Google's equivalent, and I'm sure the same is true for other libraries. And even when a site is using YUI from our servers, we wouldn't have comprehensive traffic data of the kind you'd get from Google Analytics or Yahoo Analytics -- because not all pages would use YUI or the CDN uniformly.
Given the advantages of the hosted service -- including SSL from Google and YUI combo-handling from Yahoo -- I see the CDN as being a big win for most implementers, with little downside.
-Eric | Of course they produce statistics - at minimum they need to know how many resources they spend on hosting these scripts. And it's also nice to know who uses your code.
I don't think it's a bad thing.
And using a hosted version makes even more sense because your visitors might have the script already cached after visiting another site. | Hosted Yui, Google maps, JQuery - an easy way of monitoring website usage? | [
"",
"javascript",
"jquery",
"yui",
""
] |
I have a data structure that represents C# code like this:
```
class Namespace:
string Name;
List<Class> Classes;
class Class:
string Name;
List<Property> Properties;
List<Method> Methods;
List<Method> Constructors;
List<Field> Fields;
List<Class> InnerClasses;
Class Parent;
List<Interface> Implements;
```
... which I'm building using a simple lexer/parser combination. I need to traverse the tree and apply a large set of rules (more than 3000). Rules run when encountering different (and quite complex) patterns in the tree. For example, there's a rule that runs when a class only implements interfaces in the same assembly.
My original naïve implementation iterates over each rule and then each rule traverses the tree looking for its specific pattern. Of course, this takes quite a lot of time, even with a small amount of source code.
I suppose this could be likened to how antivirus software works, recognizing complex patterns on a large body of binary code.
How would you suggest one implement this kind of software?
EDT: Just like to add: No, I'm not re-implementing FxCop.
Thanks | You could try to aggregate your 3000 rules. Some of the 3000, I would guess assume another member of the 3000. Say rule 12 checks 'a class implements an interface'. Rule 85 might be
'a class only implements interfaces in the same assembly'. If rule 12 fails, no need to run rule 85 at all.
This approach (alpha-beta pruning) would either need you to restructure your algorithm to search the class tree, looking for all rules patterns at the same time. Or to stash a record that a previous rule pass has identified that the current rule pass is irrelevant.
COMMENT: I have a nub level account so i can't comment directly. Can you give an example of maybe 2 more rules? I am currently thinking your algorithm is 0(n\*n) (following copied from a big 0 notation post)
O(n\*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort
O(n\*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can. | I'd consider creating some sort of representation for pattern/context, then creating a hash map from pattern to set of actions. Without knowing more of your requirements, it's hard to be more specific, but as an example, the string `"Namespace/Class"` could be a key to a set of actions that depend on knowing the namespace and a single class that it contains, `"Class/Interface"` could a key to the set of actions that deal with a single class and a single interface it implements, etc.
The tree traversal algorithm could keep track of its own context (parent node, current node, etc.), form a key based on where it is in the tree, retrieve the action set for that key, and then fire all of those actions, giving each an argument structure that provided the actual nodes corresponding to the key pattern.
This amounts to creating a special-purpose rules engine which deals with rules of the form "If I have a class `C`, and it implements an interface `I`, then do ... with `C` and `I`". | How would you implement?: Lots of rules over a tree in C# | [
"",
"c#",
"tree",
"design-patterns",
"rules",
"traversal",
""
] |
I've written a class with a single static method that copies property values from one object to another. It doesn't care what type each object is, only that they have identical properties. It does what I need, so I'm not engineering it further, but what improvements would you make?
Here's the code:
```
public class ShallowCopy
{
public static void Copy<From, To>(From from, To to)
where To : class
where From : class
{
Type toType = to.GetType();
foreach (var propertyInfo in from.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
{
toType.GetProperty(propertyInfo.Name).SetValue(to, propertyInfo.GetValue(from, null), null);
}
}
}
```
I'm using it as follows:
```
EmployeeDTO dto = GetEmployeeDTO();
Employee employee = new Employee();
ShallowCopy.Copy(dto, employee);
``` | Are your DTOs serializable? I would expect so, in which case:
```
MemberInfo[] sm = FormatterServices.GetSerializableMembers(typeof(From));
object[] data = FormatterServices.GetObjectData(from, sm);
FormatterServices.PopulateObjectMembers(to, sm, data);
```
But note that I don't really agree with this general approach. I would prefer a strong contract for copying on your DTOs that each DTO implements. | * Change your type parameter names to comply with naming conventions, e.g. TFrom and TTo, or TSource and TDest (or TDestination).
* Do most of your work in a generic type instead of in just a generic method. That allows you to cache the properties, as well as allowing type inference. Type inference is important on the "TFrom" parameter, as it will allow anonymous types to be used.
* You could potentially make it blindingly fast by dynamically generating code to do the property copying and keeping it in a delegate which is valid for the "from" type. Or potentially generate it for every from/to pair, which would mean the actual copying wouldn't need to use reflection at all! (Preparing the code would be a one-time hit per pair of types, but hopefully you wouldn't have too many pairs.) | How would you improve this shallow copying class? | [
"",
"c#",
"reflection",
"shallow-copy",
""
] |
In a visual studio C++ project, would MFC be faster than using the CLR? I'd specificily be using 2008.
Oh and the reason I ask is because I have experience with .NET but not so much with MFC. I understand what MFC is but have never really used it much. | If you are talking about a Visual C++ project with /clr enabled, then definitely one without /clr will be faster. However, a Visual C++ project without /clr can be outrun by a Visual C# project in some cases(some cases: not all of them) mainly because of the optimizations that can be done at the CLR layer. | If you're referring to dev time, if you have experience with .NET and the runtime environment requirements are not a concern, you're probably better off doing a CLR project of some sort. MFC has a fairly steep learning curve, and .NET experience is fairly easy to translate cross-language.
If you're talking about runtime speed, MFC (native code) will almost certainly be faster. | MFC vs. CLR? | [
"",
".net",
"c++",
"visual-studio",
"mfc",
"clr",
""
] |
As the title suggests, I'm using Google App Engine and Django.
I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.
I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE\_DIRS, but can't figure it out on my own.
EDIT:
I've tried:
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), )
```
But to no avail. I'll try some other possibilities too. | I found that it works "out of the box" if I don't load Templates first and render them with a Context object. Instead, I use the standard method shown in the [AppEngine tutorial](http://code.google.com/appengine/docs/python/gettingstarted/templates.html). | First, you should consider using [template inheritance](http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance) rather than the `include` tag, which is often appropriate but sometimes far inferior to template inheritance.
Unfortunately, I have no experience with App Engine, but from my experience with regular Django, I can tell you that you need to set your `TEMPLATE_DIRS` list to include the folder from which you want to include a template, as you indicated. | AppEngine and Django: including a template file | [
"",
"python",
"django",
"google-app-engine",
"templates",
"include",
""
] |
this subquery works in SQL Server:
```
select systemUsers.name,
(select count(id)
from userIncidences
where idUser = systemUsers.id )
from systemUsers
```
How can It be made in SQL Compact?
Thanks! | Try this:
```
SELECT su.Name, COUNT(ui.ID)
FROM systemUsers su
LEFT JOIN userIncidences ui ON ui.idUser = su.ID
GROUP BY su.Name
```
[Edit:]
I originally had an INNER JOIN just like Tomalak, but I realized that this would exclude users with no incidents, rather than show them with a 0 count. That might even be what you want, but it doesn't match your original. | There are cases when you can't avoid a subquery, for instance if you have to include calculated columns that use data from the current and the previous row. Consider this query, for instance:
```
SELECT
(Current.Mileage - Last.Mileage)/Quantity as MPG
FROM
GasPurchases AS Current
LEFT OUTER JOIN GasPurchases AS Last
ON Last.Date =
(SELECT MAX(PurchaseDate)
FROM GasPurchases
WHERE PurchaseDate < Current.PurchaseDate)
```
It will cause a parsing error:
> SQL Execution Error.
>
> Error Source: SQL Server Compact ADO.NET Data Provider
> Error Message: There was an error parsing the query.
I found [this thread](http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/3a6351a2-6c10-4595-9b50-2ad4dc54470b/) on MSDN that has a workaround. By changing the subquery so that it returns a set instead of a scalar value, I was able to save and run the following query.
```
SELECT
(Current.Mileage - Last.Mileage)/Quantity as MPG
FROM
GasPurchases AS Current
LEFT OUTER JOIN GasPurchases AS Last
ON Last.Date IN
(SELECT MAX(PurchaseDate)
FROM GasPurchases
WHERE PurchaseDate < Current.PurchaseDate)
``` | How can I make this query in SQL Server Compact Edition? | [
"",
"sql",
"sql-server",
"sql-server-ce",
""
] |
I have 2 classes, main and extended. I need to use main vars in extended class.
```
<?php
class Main {
public $vars = array();
}
$main = new Main;
$main->vars['key'] = 'value';
class Extended extends Main { }
$other = new Extended;
var_dump($other->vars);
?>
```
Who I can do it?
No valid for example:
```
<?php
class Extended extends Main {
function __construct ($main) {
foreach ($main as $k => $v) {
$this->$k = $v;
}
}
}
?>
```
I need some solution more transparent and efficient :) | **EDIT**: This can be solved much better with *Inversion of Control* (IoC) and *Dependency Injection* (DI). If you use your own framework or one without *Dependency Injection Container* try [League/Container](http://container.thephpleague.com/)
Answer below left as history of foolish answers.
---
The correct way I figure.
```
<?php
class Config {
protected $_vars = array();
protected static $_instance;
private function __construct() {}
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function &__get($name) {
return $this->_vars[$name];
}
public function __set ($name, $value) {
$this->_vars[$name] = $value;
}
}
$config = Config::getInstance();
$config->db = array('localhost', 'root', '');
$config->templates = array(
'main' => 'main',
'news' => 'news_list'
);
class DB {
public $db;
public function __construct($db)
{
$this->db = $db;
}
public function connect()
{
mysql_connect($this->db[0], $this->db[1], $this->db[2]);
}
}
$config = Config::getInstance();
$db = new DB($config->db);
$db->connect();
class Templates {
public $templates;
public function __construct($templates)
{
$this->templates = $templates;
}
public function load ($where) {
return $this->templates[$where];
}
}
$config = Config::getInstance();
$templates = new Templates($config->templates);
echo $templates->load('main') . "\n";
``` | It would be easily possible with a simple constructor
```
<?php
class One {
public static $string = "HELLO";
}
class Two extends One {
function __construct()
{
parent::$string = "WORLD";
$this->string = parent::$string;
}
}
$class = new Two;
echo $class->string; // WORLD
?>
``` | Using parent variables in a extended class in PHP | [
"",
"php",
"class",
"object",
"extends",
""
] |
This error message is being presented, any suggestions?
> Allowed memory size of 33554432 bytes exhausted (tried to allocate
> 43148176 bytes) in php | If your script is **expected** to allocate that big amount of memory, then you can increase the memory limit by adding this line to your php file
```
ini_set('memory_limit', '44M');
```
where `44M` is the amount you expect to be consumed.
**However**, most of time this error message means that **the script is doing something wrong** and increasing the memory limit will just result in the same error message with different numbers.
Therefore, instead of increasing the memory limit you must rewrite the code so it won't allocate that much memory. For example, processing large amounts of data in smaller chunks, unsetting variables that hold large values but not needed anymore, etc. | Here are two simple methods to increase the limit on shared hosting:
1. If you have access to your PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
`memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)`
2. If you don't have access to PHP.ini try adding this to an .htaccess file:
`php_value memory_limit 64M` | Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php | [
"",
"php",
"memory-management",
"memory-limit",
""
] |
I got an error today while trying to do some formatting to existing code. Originally, the code had the `using` directives declared outside the namespace:
```
using System.Collections.Generic;
namespace MyNamespace
{
using IntPair = KeyValuePair<int, int>;
}
```
When I tried to insert the `using` directive inside the statement (to comply with StyleCop's rules), I got an error at the aliasing directive, and I had to fully qualify it:
```
namespace MyNamespace
{
using System.Collections.Generic;
//using IntPair = KeyValuePair<int, int>; // Error!
using IntPair = System.Collections.Generic.KeyValuePair<int, int>; // works
}
```
I wonder what difference there is between the two cases? Does the location of the (import-style) `using` directive matter? | I used to think that it did not matter, but I always fully qualify using commands.
Edit: Checked the [C# spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx), section 9.4 says that:
> The scope of a using-directive specifically does not include its peer using-directives. Thus, peer using-directives do not affect each other, and the order in which they are written is insignificant.
So if System.Collections.Generic and KeyValuePair are treated as peers then KeyValuePair is going to ignore System.Collections.Generic. | Yes, it does - to a small extent. There is an edge-case to do with scoping / local names, see [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2007/06/25/inside-or-outside.aspx).
For a concrete example (specific to alias usage):
```
using System;
using Foo = Bar;
public static class Bar {
public static void Test() { Console.WriteLine("outer"); }
}
namespace MyNamespace {
//using Foo = Bar;
public static class Bar {
public static void Test() { Console.WriteLine("inner"); }
}
static class Program {
static void Main() {
Foo.Test();
}
}
}
``` | Does the location of the `using` directive make a difference in C#? | [
"",
"c#",
"syntax",
""
] |
I have this class called Table:
```
class Table
{
public string Name
{
get
{
return this.wrapper.Eval(//some command);
//wrapper is pass in by the ctor and is a COM object.
}
}
}
```
which is used in this class:
```
class Map
{
public Map MapTable(Table table)
{
return new Map(table.Name);
}
}
```
I want to test MapTable command, should I be mocking Table or should I mock the wrapper object that is used by the table object.
I was thinking something like this
```
Test()
{
Mock<ITable> mocktable = new Mock<ITable>(//pass in the wrapper object);
mocktable.ExpectGet(n => n.Name).Returns("Hello World");
ITable table = mocktable.object;
Map mymap = Map.MapTable(table);
}
```
Would that be correct? | Beyond the fact that there is usually no *one* perfect testing solution, I'd first go for mocking the COM object: there should be a interface available and you'll probably want to test everything "above" it.
If the `Table` contains non-trivial code (e.g. within the `Eval()`; anything with conditionals; or e.g. parsing using a `Culture`) you might want to have a mock of it as you show in your example. | **Yes** your sample looks fine, if you want to test the Map object you should be mocking the Table object.
If you do it the other way around you will not test the Map constructor. | Should I create a interface and mock this class | [
"",
"c#",
"mocking",
""
] |
There's a good discussion of Generics and what they really do behind the scenes over at [this question](https://stackoverflow.com/questions/31693/differences-in-generics), so we all know that `Vector<int[]>` is a vector of integer arrays, and `HashTable<String, Person>` is a table of whose keys are strings and values `Person`s.
However, what stumps me is the usage of `Class<>`.
The java class `Class` is supposed to also take a template name, (or so I'm being told by the yellow underline in eclipse). I don't understand what I should put in there. The whole point of the `Class` object is when you don't fully have the information about an object, for reflection and such. Why does it make me specify which class the `Class` object will hold? I clearly don't know, or I wouldn't be using the `Class` object, I would use the specific one. | Using the generified version of class Class allows you, among other things, to write things like
```
Class<? extends Collection> someCollectionClass = someMethod();
```
and then you can be sure that the Class object you receive extends `Collection`, and an instance of this class will be (at least) a Collection. | All we know is "*All instances of a any class shares the same java.lang.Class object of that type of class*"
e.g)
```
Student a = new Student();
Student b = new Student();
```
Then `a.getClass() == b.getClass()` is true.
Now assume
```
Teacher t = new Teacher();
```
without generics the below is possible.
```
Class studentClassRef = t.getClass();
```
But this is wrong now ..?
e.g) `public void printStudentClassInfo(Class studentClassRef) {}` can be called with `Teacher.class`
This can be avoided using generics.
```
Class<Student> studentClassRef = t.getClass(); //Compilation error.
```
Now what is T ?? T is type parameters (also called type variables); delimited by angle brackets (<>), follows the class name.
T is just a symbol, like a variable name (can be any name) declared during writing of the class file. Later that T will be substituted with
valid Class name during initialization (`HashMap<String> map = new HashMap<String>();`)
e.g) `class name<T1, T2, ..., Tn>`
So `Class<T>` represents a class object of specific class type '`T`'.
Assume that your class methods has to work with unknown type parameters like below
```
/**
* Generic version of the Car class.
* @param <T> the type of the value
*/
public class Car<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
```
Here T can be used as `String` type as **CarName**
OR T can be used as `Integer` type as **modelNumber**,
OR T can be used as `Object` type as **valid car instance**.
Now here the above is the simple POJO which can be used differently at runtime.
Collections e.g) List, Set, Hashmap are best examples which will work with different objects as per the declaration of T, but once we declared T as String
e.g) `HashMap<String> map = new HashMap<String>();` Then it will only accept String Class instance objects.
**Generic Methods**
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For generic methods, the type parameter section must appear before the method's return type.
```
class Util {
// Generic static method
public static <K, V, Z, Y> boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
class Pair<K, V> {
private K key;
private V value;
}
```
Here `<K, V, Z, Y>` is the declaration of types used in the method arguments which should before the return type which is `boolean` here.
In the below; type declaration `<T>` is not required at method level, since it is already declared at class level.
```
class MyClass<T> {
private T myMethod(T a){
return a;
}
}
```
But below is wrong as class-level type parameters K, V, Z, and Y cannot be used in a static context (static method here).
```
class Util <K, V, Z, Y>{
// Generic static method
public static boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
```
**OTHER VALID SCENARIOS ARE**
```
class MyClass<T> {
//Type declaration <T> already done at class level
private T myMethod(T a){
return a;
}
//<T> is overriding the T declared at Class level;
//So There is no ClassCastException though a is not the type of T declared at MyClass<T>.
private <T> T myMethod1(Object a){
return (T) a;
}
//Runtime ClassCastException will be thrown if a is not the type T (MyClass<T>).
private T myMethod1(Object a){
return (T) a;
}
// No ClassCastException
// MyClass<String> obj= new MyClass<String>();
// obj.myMethod2(Integer.valueOf("1"));
// Since type T is redefined at this method level.
private <T> T myMethod2(T a){
return a;
}
// No ClassCastException for the below
// MyClass<String> o= new MyClass<String>();
// o.myMethod3(Integer.valueOf("1").getClass())
// Since <T> is undefined within this method;
// And MyClass<T> don't have impact here
private <T> T myMethod3(Class a){
return (T) a;
}
// ClassCastException for o.myMethod3(Integer.valueOf("1").getClass())
// Should be o.myMethod3(String.valueOf("1").getClass())
private T myMethod3(Class a){
return (T) a;
}
// Class<T> a :: a is Class object of type T
//<T> is overriding of class level type declaration;
private <T> Class<T> myMethod4(Class<T> a){
return a;
}
}
```
And finally Static method always needs explicit `<T>` declaration; It wont derive from class level `Class<T>`. This is because of Class level T is bound with instance.
Also read [Restrictions on Generics](https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createStatic)
[Wildcards and Subtyping](https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html)
[type argument for a generic method](https://stackoverflow.com/questions/4829631/unusual-generic-syntax-arrays-stringaslist) | How to use Class<T> in Java? | [
"",
"java",
"templates",
"class",
"generics",
""
] |
Java `.class` files can be decompiled fairly easily. How can I protect my database if I have to use the login data in the code? | Never hard-code passwords into your code. This was brought up recently in the [Top 25 Most Dangerous Programming Mistakes](http://blog.codinghorror.com/top-25-most-dangerous-programming-mistakes/):
> Hard-coding a secret account and
> password into your software is
> extremely convenient -- for skilled
> reverse engineers. If the password is
> the same across all your software,
> then every customer becomes vulnerable
> when that password inevitably becomes
> known. And because it's hard-coded,
> it's a huge pain to fix.
You should store configuration information, including passwords, in a separate file that the application reads when it starts. That is the only real way to prevent the password from leaking as a result of decompilation (never compile it into the binary to begin with).
For more information about this common mistake, you can read the [CWE-259 article](http://cwe.mitre.org/data/definitions/259.html). The article contains a more thorough definition, examples, and lots of other information about the problem.
In Java, one of the easiest ways to do this is to use the Preferences class. It is designed to store all sorts of program settings, some of which could include a username and password.
```
import java.util.prefs.Preferences;
public class DemoApplication {
Preferences preferences =
Preferences.userNodeForPackage(DemoApplication.class);
public void setCredentials(String username, String password) {
preferences.put("db_username", username);
preferences.put("db_password", password);
}
public String getUsername() {
return preferences.get("db_username", null);
}
public String getPassword() {
return preferences.get("db_password", null);
}
// your code here
}
```
In the above code, you could call the `setCredentials` method after showing a dialog askign for the username and password. When you need to connect to the database, you can just use the `getUsername` and `getPassword` methods to retrieve the stored values. The login credentials will not be hard-coded into your binaries, so decompilation will not pose a security risk.
**Important Note:** The preference files are just plain text XML files. Make sure you take appropriate steps to prevent unauthorized users from viewing the raw files (UNIX permissions, Windows permissions, et cetera). In Linux, at least, this isn't a problem, because calling `Preferences.userNodeForPackage` will create the XML file in the current user's home directory, which is non-readable by other users anyway. In Windows, the situation might be different.
**More Important Notes:** There has been a lot of discussion in the comments of this answer and others about what the correct architecture is for this situation. The original question doesn't really mention the context in which the application is being used, so I will talk about the two situations I can think of. The first is the case in which the person using the program already knows (and is authorized to know) the database credentials. The second is the case in which you, the developer, are trying to keep the database credentials secret from the person using the program.
**First Case: User is authorized to know the database login credentials**
In this case, the solution I mentioned above will work. The Java `Preference` class will stored the username and password in plain text, but the preferences file will only be readable by the authorized user. The user can simply open the preferences XML file and read the login credentials, but that is not a security risk because the user knew the credentials to begin with.
**Second Case: Trying to hide login credentials from the user**
This is the more complicated case: the user should not know the login credentials but still needs access to the database. In this case, the user running the application has direct access to the database, which means the program needs to know the login credentials ahead of time. The solution I mentioned above is not appropriate for this case. You can store the database login credentials in a preferences file, but he user will be able to read that file, since they will be the owner. In fact, there is really no good way to use this case in a secure way.
**Correct Case: Using a multi-tier architecture**
The correct way to do it is to have a middle layer, in between your database server and your client application, that authenticates individual users and allows a limited set of operations to be performed. Each user would have their own login credentials, but not for the database server. The credentials would allow access to the middle layer (the business logic tier) and would be different for each user.
Every user would have their own username and password, which could be stored locally in a preferences file without any security risk. This is called a [three-tier architecture](http://en.wikipedia.org/wiki/Three-tier_(computing)) (the tiers being your database server, business logic server, and client application). It is more complex, but it really is the most secure way to do this sort of thing.
The basic order of operations is:
1. Client authenticates with business logic tier using the user's personal username/password. The username and password are known to the user and are not related to the database login credentials in any way.
2. If authentication succeeds, the client makes a request to the business logic tier asking for some information from the database. For example, an inventory of products. Note that the client's request is not a SQL query; it is a remote procedure call such as `getInventoryList`.
3. The business logic tier connects to the database and retrieves the requested information. The business logic tier is in charge of forming a secure SQL query based on the user's request. Any parameters to the SQL query should be sanitized to prevent SQL injection attacks.
4. The business logic tier sends the inventory list back to the client application.
5. The client displays the inventory list to the user.
Note that in the entire process, **the client application never connects directly to the database**. The business logic tier receives a request from an authenticated user, processes the client's request for an inventory list, and only then executes a SQL query. | Put the password into a file that the application will read. NEVER embed passwords in a source file. Period.
Ruby has a little-known module called [DBI::DBRC](https://rubygems.org/gems/dbi-dbrc) for such usage. I have no doubt that Java has an equivalent. Anyway, it is not difficult to write one. | How can I protect MySQL username and password from decompiling? | [
"",
"java",
"mysql",
"security",
"reverse-engineering",
"decompiling",
""
] |
*[The [only similar question](https://stackoverflow.com/questions/137933/what-is-the-best-scripting-language-to-embed-in-a-c-desktop-application) I can find was answered long ago and contains a reference to mostly IronPython. I want to consider other options as well]*
We have a complex data analysis application written in C#. The application should provide users with a sophisticated means of customizing their data analysis tasks. Currently, we use a mixture of configuration files and Excel tables to specify this, but it gets unwieldy, so we're looking for a scripting language to embed.
What's the best simple scripting language for C#/.NET embedding? Is it possible to somehow embed VBA similarly to Excel/Word? Or is perhaps JavaScript/Lua are used?
Needless to say, it should be easy to expose some API and objects from the main application into the embedded scripts. | I know the other question references [IronPython](http://www.codeplex.com/IronPython), but I still feel like it should be here because I think it's one of the best options.
Another great option would be [IronRuby](http://www.ironruby.net/). The main difference I see would be if your developers/users had any experience with either Python or Ruby that could be transferable.
Really, in the end your best option is going to be a language that is most easily adapted to by the users. Unless they accept it and are able to be more productive than they were with the old method it isn't worth the effort. | [Boo](http://boo.codehaus.org) perhaps? | Scripting language for embedding into C#/.NET applications? | [
"",
"c#",
".net",
"scripting",
"embed",
""
] |
Say I have two script controls and one control has the other as a child control:
```
ParentControl : ScriptControl
{
ChildControl childControl;
}
```
The script for the Child Control:
```
ChildControl = function(element)
{
ChildControl.initializeBase(this, [element]);
}
ChildControl.prototype =
{
callMethod: function()
{
return 'hi';
},
initialize: function()
{
ChildControl.callBaseMethod(this, 'initialize');
},
dispose: function()
{
ChildControl.callBaseMethod(this, 'dispose');
}
}
```
And on script side I want to call a method on the child control:
```
ParentControl.prototype =
{
initialize: function()
{
this._childControl = $get(this._childControlID);
this._childControl.CallMethod();
ParentControl.callBaseMethod(this, 'initialize');
},
dispose: function()
{
ParentControl.callBaseMethod(this, 'dispose');
}
}
```
Problem is, everytime I try this is says this method isn't found or supported. Shouldn't all methods on the ChildControl be accessible by the ParentControl?
Is there some way I have to make the method public so that the ParentControl can see it?
**Update**
Would it be possible to "type" the this.\_childControl?
Here's the reason I ask... When I use Watch, the system knows what the ChildControl class is, and I can call methods off the class itself, however, I can't call the same methods off the this.\_childControl object. You would think that if the class design (?) in memory recognizes the method existing, and object instantiated from that class would too. | On the client, you're using a field of your parent control object called \_childControlID by passing it into $get. There's a few problems with this:
1. How did \_childControlID get set? I would guess by adding it as a property in the parent control's descriptor on the server, but you don't show that code and you don't show a property on the client-side parent control class.
2. $get returns element references--not controls. So even if \_childControlID was set to a valid element ID, that element won't have a method called CallMethod. If the client-side child control class did initialize before the parent control, the element will have a field called "control" that you can use to access the script control that "attached" itself to the element. This only works if the child control initialized before the parent control, of course. | The problem is the "this." This, in javaScript, refers to the DOM object. You need to do something similar to what happens when you use Function.createDelegate, which is required when using $addHandler (which I know you're not using, just giving context). | ASP.Net ScriptControl - Call one method from another | [
"",
"asp.net",
"javascript",
"ajax",
"scriptcontrol",
"extendercontrol",
""
] |
I have an ASP.NET website (in C#) that takes in user data and then attempts to create a windows scheduled task. Of course, this works great on the DEV machine, but fails to run on the server. I'm trying to figure out what permission(s) are required on the ASPNET user (or anonymous web user) to create tasks.
The error is:
```
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Stacktrace:
at MyScheduler.NewWorkItem(String TaskName, Guid& rclsid, Guid& riid, Object& obj)
at MyScheduler.CreateTask(String name)
```
I've done some searching, and the suggested resolution is to use the web.config 'impersonate' flag to force the application to run as a user with sufficient permissions, as opposed to the ASPNET account which may not have those permissions.
Example:
```
<system.web>
<identity impersonate="true" />
</system.web>
```
Unfortunately, this does not seem to resolve the issue. From the documentation I read, this should run as the anonymous web user, but it seems that user does not have enough permissions.
I altered the setting to specify a specific domain user that happens to be an administrator on the machine. Example:
```
<system.web>
<identity impersonate="true" userName="WindowsDomain\YourUserName" password="YourPassword" />
</system.web>
```
Doing this allowed the application to successfully create the Windows Scheduled Task. So, obviously, with the correct set of Windows 2003 permissions I can get the app to perform as it does in the development environment. However, I'm not about to place the network or machine administrator account's user credentials in plain text on a Web.config file.
Does anybody happen to know what permissions exactly need to be set in order to get the ASPNET account to behave as desired?
**EDIT:** The Win32 API is being used to create scheduled tasks. | I have been able to solve my particular problem, though not completely. I have still not identified the exact rights needed to create and run scheduled tasks, but the following seems to work:
1. Add the `<identity impersonate="true" />` to the Web.config
2. Add the IUSR user (which is the user the app will run as using impersonate) to the "Backup Operators" group.
This gives the application access to the Scheduled Tasks folder so that they can create and run the task.
We had an additional issue, which was that the tasks were attempting to run as the Local System Account. Unfortunately, only administrators seem to be able to assign the Local System Account as the running user, so we needed to impersonate as an Administrator account, not as a Backup Operator in order to get our code functioning correctly. | Instead of worrying about the ASPNET user permissions, would your internal process allow you to create a machine specific account and supply the credentials there? | .NET create scheduled task on server fails with E_ACCESSDENIED | [
"",
"c#",
".net",
"asp.net",
"permissions",
"scheduled-tasks",
""
] |
Where would you place the SaveSettings method in your project when the user is done editing any settings on the Settings dialog in your program?
Should it be in the return like:
```
using (frmSettings frmSettings = new frmSettings())
{
if (frmSettings.ShowDialog() == DialogResult.OK)
{
// clicked OK, should I call SaveSettings() here?
}
else
{
// clicked cancel.
}
}
```
Or where should I place it? | ```
// clicked OK, should I call SaveSettings() here?
```
That seems like a good place. =)
EDIT: I suppose it depends on the framework of the application, but there's nothing wrong with putting it there. It's a logical (by all definitions of logic) place to put it. | Putting the save code in the calling form is, in my opinion, putting it in the incorrect place. Yes, it will work in this instance, but it means that the settings form is not reusable, and that any error in your save code will cause the settings form to dismount before you know of any errors.
Additionally, if you add a new setting, you need to make the changes in two source locations, once to add controls (and initialize them) in the settings form, and once to save the values, in the calling form.
I'd attach the code to the OK button of the Settings form. If any errors are experienced in the saving, you can inform the user while their changes are visible and repairable. The form will be able to be called from different locations, as needed, or moved with nothing more than moving the ShowDialog() call. Your handling of DialogResult.OK should be used to update the calling form as the changes in settings apply to it. | C#: Where do you call your own save method after pressing OK on a Settings Dialog for your program? | [
"",
"c#",
""
] |
We have a C# application that connects to a FTP server, downloads some files, disconnects, and after a certain amount of time (selected by the user through the UI) reconnects and repeats the process. We implemented this using BackgroundWorker, but we noticed that after running for a longer time, the program stopped logging its actions, both in the UI and the log file.
At that point, there were no files for it to download, so we uploaded some and it resumed activity as if nothing had happened.
The problem was that the regular users had no way of knowing that the program was still working, so we decided to implement it using our own threading. We did a simpler program, to rule out any other problems, and this one only connects to the FTP and disconnects. It stopped displaying messages just like BackgroundWorker (one time after 2 hours, one time after 22 hours, without any pattern that we could find, and on a computer that did nothing else).
```
DoFTPWork += new DoFTPWorkDelegate(WriteFTPMessage);
FTPWorkThread = new Thread(new ParameterizedThreadStart(Process));
//seData is the FTP login info
FTPWorkThread.Start(seData);
```
and the FTP method is:
```
private void Process(object seData1)
{
seData = (SEData)seData1;
while (!stopped)
{
try
{
ftp = null;
ftp = new FTP_Client();
if (ftp.IsConnected)
{
logMessages += DateTime.Now + "\t" + "info" + "\t" + "Ftp disconnected from " + seData.host + "\r\n";
ftp.Disconnect();
}
ftp.Connect(seData.host, 21);
ftp.Authenticate(seData.userName, seData.password);
logMessages += DateTime.Now + "\t" + "info" + "\t" + "Ftp connected to " + seData.host + "\r\n";
error = false;
logMessages += DateTime.Now + "\t" + "info" + "\t" + "Trying to reconnect in 5 seconds\r\n";
System.Threading.Thread.Sleep(5000);
SlaveEventArgs ev = new SlaveEventArgs();
ev.Message = logMessages;
txtLog.Invoke(DoFTPWork, ev);
System.Threading.Thread.Sleep(200);
logMessages = "";
}
catch (Exception ex)
{
logMessages = "";
if (ftp.IsConnected)
{
ftp.Disconnect();
}
ftp.Dispose();
logMessages += DateTime.Now + "\t" + "ERR" + "\t" + ex.Message + "\r\n";
logMessages += DateTime.Now + "\t" + "info" + "\t" + "Trying to reconnect in 5 seconds\r\n";
SlaveEventArgs ev = new SlaveEventArgs();
ev.Message = logMessages;
txtLog.Invoke(DoFTPWork, ev);
System.Threading.Thread.Sleep(5 * 1000);
error = true;
}
}
}
```
WriteFTPMessage displays the message in a TextBox and in the original program wrote to a .txt file. | If I'm understanding you correctly this `while(!stopped)` loop is the loop that is running for several hours? If that is the case, where are you terminating your ftp connection if anywhere? The only time you close it in the code you've posted is if an exception is thrown, otherwise you simply dereference the object and create a new one which is a pretty serious resource leak and at least contributing to the problem if not causing it.
Also it seems that ftp is globally accessible. Are you accessing it anywhere using a different thread? Is the object thread safe??
**EDIT:**
The biggest issue I see here is design. Not that I'm trying to bag on you or anything but you've got all sorts of operations intermixed. Threading, logging and ftp access code all in the same function.
What I would recommend is restructuring your program. Create a method much like the following:
```
// Called by thread
void MyThreadOperation()
{
while(!stopped)
{
// This is poor design in terms of performance.
// Consider using a ResetEvent instead.
Thread.Sleep(5000);
try
{
doFTPDownload();
}
catch(Exception ex)
{
logMessage(ex.ToString());
}
}
}
```
`doFTPDownload()` should be self contained. The FTP object should be created and opened inside the function when it is called and prior to it finishing it should be closed. This same concept should be applied to `logMessage()` as well. I would also recommend using a database to store log messages instead of a file so that locking issues don't complicate matters.
I know this isn't an answer in that you may still experience issues since I can't say for certain what could be the cause. However I'm confident with a little design restructuring you will be much better able to track down the source of the problem. | I would suggest putting anything that can go wrong in the catch block (in particular the bit which disconnects from the FTP server) in its own try/catch block. In addition, log something as soon as you've caught the exception, before doing anything else - that way you're more likely to be able to tell if the logging dies half way through for some reason.
Also, add a log message to the end of the while loop so that you can tell if it's finished "normally". | Thread stops doing its job | [
"",
"c#",
"multithreading",
"backgroundworker",
""
] |
When I extract files from a ZIP file created with the Python [`zipfile`](http://docs.python.org/library/zipfile.html) module, all the files are not writable, read only etc.
The file is being created and extracted under Linux and Python 2.5.2.
As best I can tell, I need to set the `ZipInfo.external_attr` property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me? | This seems to work (thanks Evan, putting it here so the line is in context):
```
buffer = "path/filename.zip" # zip filename to write (or file-like object)
name = "folder/data.txt" # name of file inside zip
bytes = "blah blah blah" # contents of file inside zip
zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED)
info = zipfile.ZipInfo(name)
info.external_attr = 0777 << 16L # give full access to included file
zip.writestr(info, bytes)
zip.close()
```
I'd still like to see something that documents this... An additional resource I found was a note on the Zip file format: <http://www.pkware.com/documents/casestudies/APPNOTE.TXT> | [This link](http://trac.edgewall.org/attachment/ticket/8919/ZipDownload.patch) has more information than anything else I've been able to find on the net. Even the zip source doesn't have anything. Copying the relevant section for posterity. This patch isn't really about documenting this format, which just goes to show how pathetic (read non-existent) the current documentation is.
```
# external_attr is 4 bytes in size. The high order two
# bytes represent UNIX permission and file type bits,
# while the low order two contain MS-DOS FAT file
# attributes, most notably bit 4 marking directories.
if node.isfile:
zipinfo.compress_type = ZIP_DEFLATED
zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r--
data = node.get_content().read()
properties = node.get_properties()
if 'svn:special' in properties and \
data.startswith('link '):
data = data[5:]
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
if 'svn:executable' in properties:
zipinfo.external_attr |= 0755 << 16L # -rwxr-xr-x
zipfile.writestr(zipinfo, data)
elif node.isdir and path:
if not zipinfo.filename.endswith('/'):
zipinfo.filename += '/'
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x
zipinfo.external_attr |= 0x10 # MS-DOS directory flag
zipfile.writestr(zipinfo, '')
```
Also, [this link](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) has the following.
Here the low order byte presumably means the rightmost (lowest) byte of the four bytes. So this one is
for MS-DOS and can presumably be left as zero otherwise.
> external file attributes: (4 bytes)
>
> ```
> The mapping of the external attributes is
> host-system dependent (see 'version made by'). For
> MS-DOS, the low order byte is the MS-DOS directory
> attribute byte. If input came from standard input, this
> field is set to zero.
> ```
Also, the source file unix/unix.c in the sources for InfoZIP's zip program, downloaded from [Debian's archives](http://packages.debian.org/source/stable/zip) has the following in comments.
```
/* lower-middle external-attribute byte (unused until now):
* high bit => (have GMT mod/acc times) >>> NO LONGER USED! <<<
* second-high bit => have Unix UID/GID info
* NOTE: The high bit was NEVER used in any official Info-ZIP release,
* but its future use should be avoided (if possible), since it
* was used as "GMT mod/acc times local extra field" flags in Zip beta
* versions 2.0j up to 2.0v, for about 1.5 years.
*/
```
So taking all this together, it looks like only the second highest byte is actually used, at least for Unix.
EDIT: I asked about the Unix aspect of this on Unix.SX, in the question "[The zip format's external file attribute](https://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute)". Looks like I got a couple of things wrong. Specifically both of the top two bytes are used for Unix. | How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module? | [
"",
"python",
"attributes",
"zip",
"file-permissions",
"python-zipfile",
""
] |
I have a Drupal module page where I am populating a form with a drop-down that contains a list of available parts of a set of files that the user can upload. Once the user uploads a file of a certain type, it removes that option from the list, and when all the available files are uploaded the form will not be rendered.
The problem is that Drupal is drawing the form before it carries out the submit action, so it appears to the user that the operation didn't work until they reload the page.
What is the common way to deal with this? Setting form\_state['redirect'] to go to the page doesn't seem to work. | You modify your form so that it saves some information on the state of the form. Then you add a new case to the beginning of the submit function that returns immediately if you're not done uploading all the files, and it will redraw the form.
```
function modulename_uploader_form(&$form_stuff=null) {
//the function that sets your form array
$stuff = (isset($form_stuff['values'])) ?
$form_stuff['storage']['done_uploading'] :
false; //if values isnt set, this is the first visit.
$form_stuff['storage']['done_uploading'] = done_uploading();
.... the rest of your form creation function.
function modulename_uploader_submit($form, &$form_stuff) {
if($form_stuff['storage']['done_uploading']) {
return;
}
... rest of the function
```
make sure to unset the storage variable when you're done processing the form. You can also google multi page forms in drupal. | Setting $form\_state['redirect'] in your submit handler will just cause the form to reload, fresh, without the old data. It's a way of clearing out the form so that old values don't hang around as defaults.
You probably want to use $form\_state['rebuild'], which gives your form-building functions an opportunity to rebuild the form's actual structure, adding more fields or removing options from other fields after the form submit handlers run.
[This blog post](http://www.ferolen.com/blog/how-to-create-multistep-form-in-drupal-6-tutorial/) has a rough tutorial on doing multiple-stage forms in D6, and the [Drupal 5 to 6 upgrade docs](http://drupal.org/node/144132#form-state) on Drupal.org contain a useful overview of how $form\_state works and what its various flags are for. | Drupal form being rendered before submit action | [
"",
"php",
"drupal",
"drupal-6",
"drupal-fapi",
""
] |
I have a 100 classes that have some similar elements and some unique. I've created an interface that names those similar items eg: interface IAnimal. What i would normally do is:
```
class dog : IAnimal
```
But there are 100 classes and i don't feel like going though them all and looking for the ones that i can apply IAnimal to.
What i want to do is this:
```
dog scruffy = new dog();
cat ruffles = new cat();
IAnimal[] animals = new IAnimal[] {scruffy as IAnimal, ruffles as IAnimal} // gives null
```
or
```
IAnimal[] animals = new IAnimal[] {(IAnimal)scruffy, (IAnimal)ruffles} //throws exception
```
then do
```
foreach (IAnimal animal in animals)
{
animal.eat();
}
```
Is there a way to make c# let me treat ruffles and scruffy as an IAnimal without having to write : IAnimal when writing the class.
Thanks!
EDIT (not lazy): The classes are generated off of sql stored proc metadata, which means every time it gets generated i would have to go back and add them in,or modify the code generator to identify the members that are in the interface, actually thats not a bad idea. I was hoping there was some sort of generics approach or something though. | You might solve this problem with **partial classes**: let the machine-generated/regenerated code be in one source file of each class, and the hand-coded part (defining the subclassing from IAnimal) in another. | What you are asking for is called duck typing and is not part of C# I am afraid. Any solution will involve reflection and looking at the properties, It will be quicker to check the classes by hand I think.
It would be an interesting project to try though. | Treat a class as if it was defined with an interface | [
"",
"c#",
"casting",
"interface",
"enumeration",
""
] |
What is the latest version of gcc that still uses libstdc++.so.5 (as opposed to libstdc++.so.6)? | After searching all over for the answer, and failing to find it. I compiled several different versions and the last version to use libstdc++.so.5 is version 3.3 (more specifically 3.3.6). Version 3.4.X uses libstdc++.so.6. | In the [Gnu ABI policy](http://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html "Gnu ABI Policy"), you can find this:
* ...
* gcc-3.3.3: libstdc++.so.5.0.5
* gcc-3.4.0: libstdc++.so.6.0.0 (Incompatible with previous)
* ...
So unless they didn't list a version, gcc-3.3.3 is the one you want. | The latest version of gcc to use libstdc++.so.5 | [
"",
"c++",
"gcc",
"libstdc++",
""
] |
I want to limit a report to return records from Date A through Date B. This is what I have been doing:
```
declare @startDate varchar(20)
declare @endDate varchar(20)
set @startDate = '01/01/2008'
set @endDate = '04/01/2008'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date between @startDate and @endDate
```
... which I was told returned records from 12 am Jan 1st through 11:59 pm March 31st (that midnight is the default when no time is indicated). But I noticed a discrepancy, which is if a record has a time of 00:00:00 that it will be part of this set.
Is there a more exact way of doing this so it will return exactly the date range I want?\*
I tried using time:
```
declare @startDate varchar(20)
declare @endDate varchar(20)
set @startDate = '01/01/2008 00:00:00'
set @endDate = '04/01/2008 11:59:59'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date between @startDate and @endDate
```
... but I noticed something wonky: SQL Server will ROUND the hundreth-second up by half. So I get that April 1st record (ha! April Fool's record! grr) if I use any time later than 11:59:29. Why is that?
* (I feel sure there is. I'm new at this. Thanks for your help!) | There's always the easy option:
```
declare @startDate varchar(20)
declare @endDate varchar(20)
set @startDate = '01/01/2008'
set @endDate = '04/01/2008'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date >= @startDate
and date < @endDate
``` | I suspect that the date column in view\_Inspections is a SmallDateTime data type. This data type has 1 minute accuracy, which explains your unexpected results (rounding the seconds to the nearest minute).
The method Roland Shaw suggests is the best way to modify your query to accommodate your requirements. | Limiting a date range with exactness in MS SQL / SQL Server 2005 | [
"",
"sql",
"datetime",
"rounding",
"date-range",
""
] |
If i create a program, which in one small out of the way area, uses Excel automation:
will the application fail when Excel is needed
or will the application fail to start?
---
## Update
Let me ask the same question, but in a more drawn out way:
Will the application be usable by
* > 99.9% of the users who never use the feature that requires Excel
* 0% of the users, since Excel is not installed.
---
*Let me ask the same question another way:*
Will an application fail to initialize that references the COM interop dll's?
---
*Let me ask the same question another way:*
Will an application that doesn't use Excel, but references the COM interop DLL's fail to start?
---
*Let me ask the same question another way:*
Will an application that doesn't use Excel be usable if Excel is not installed, if that application has a dependancy on the Office Primary Interop dlls?
---
*Let me ask the same question another way:*
If my application doesn't use Excel, does the user have to have Excel installed? | The code will properly execute until it tries to make a call to the automation libraries, at that time it will generate an exception. | I have an app that uses Excel automation and I can definitively say that it will fail at runtime, not at load time. In fact we check to see if it's even installed and only show the "Show data in Excel" button if we find it (but the PIAs are deployed to all installs). | .NET: If my .NET automates Office, does the customer have to have Office installed? | [
"",
"c#",
"com",
"ms-office",
""
] |
I moved a typed dataset from one project to an ASP Web Application project. I put the typed dataset into one of the existing directories as it was in the App\_Code directory of the previous site but don't see the option to create that asp.net folder in this project.
Now, when I try to instantiate the typed dataset, the compiler says 'The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)'.
Thoughts? | You may need to re-gen the DataSet. When you move the .xsd, you've only moved the xml layout of the DataSet.
Delete any generated code file, open the xsd, move something, and then save it. The save operation calls the generator. Or you can right-click on the .xsd file and call the generator directly. | I moved my web site to a Web Application Project and experienced the same issues. I took the approach mentioned in the first answer and was able to get the project to compile eventually.
I would like to add a little more detail to the first answer.
To be explicit: I first deleted all of the files associated with the xsd file except for the xsd file itself (the xss, xsc, cs, ...). I then right-clicked on the xsd file, selecting "View Designer" and then "View Code", and then "Run Custom Tool". All of the files were re-gened and the references compiled. | Typed dataset not recognized when moved to another project | [
"",
"c#",
"asp.net",
"ado.net",
"dataset",
"strongly-typed-dataset",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.