Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have some functionality on my page that JavaScript is currently handling. I want to make my page compatible with non-Javascript users. Is there a way I can say "If JavaScript is enabled, use my JavaScript routine, otherwise do a Postback and let the server-side handle it?" | I have to presume that whatever triggers this postback or client-side behaviour (depending on javascript being available or not) is a html submit button?
If it is, I would attach the javascript handler for the client-side stuff to the button and have the handler return 'false' to prevent postback. When javascript is not enabled, the button will perform the standard html form function of triggering a postback and that will then let you do things server-side instead.
You can do a similar thing for links by having javascript run on the link click event to do client-side stuff but just follow the link in the event javascript is not available.
These methods are a bit more graceful in how they react to the browser not having javascript as they fall back to standard html form behaviour and require no code to detect javascript - it simply ignores your javascript and submits the form as it should.
**Regarding checkboxes**, be aware that the default behaviour in non-javascript enabled pages is not to post back on changes. If you change the state of a check-box, you always have to hit the submit button to postback, you simply can't do a postback on checkbox state change without javascript.
Several controls in asp.net (including drop down lists) have the option to auto-postback upon client change, this is done via javascript and if that is not available the only way to gracefully degrade is to have a button that the user clicks to force a standard html postback so your server can respond to the changed control state.
If you find you are struggling to have a coherent 'flow' in your UI if you don't have the auto-postback on checkboxes/combos etc then you might need to rethink your UI design and move to a more wizard-based layout.
I disable auto-postbacks on those types of things anyway as it is *horrible* for the user, which is a shame as you are going to great lengths to give them a usable experience when their browser is not using javascript. | I recommend you read up on using unobtrusive JavaScript, which the solutions proposed abide by. The fundamental idea is that JavaScript and Ajax should extend your user experience rather than being a requirement. Your JavaScript code should hijack events like clicking a button and prevent the default behavior, since the script should handle the processing and responses in real time, within the browser. | ASP.NET - clients without JavaScript | [
"",
"asp.net",
"javascript",
""
] |
Consider:
```
#include <map>
int main()
{
std::map< int, int > m;
m[ 0 ] = 0;
m[ 1 ] = 1;
m.erase( 0 ); // ok
m.erase( 2 ); // no-op
m.erase( m.find( 2 ) ); // boom!
}
```
(OK, so the title talks abouting erasing an end() iterator, but find will return end() for a non-existent key.)
Why is erasing a non-existent key OK, yet erasing end() blows up. I couldn't see any explicit mention of this in the standard?
I've tried this on VS2005 (throws an exception in debug configuration) and GCC 4.0.1 (100% CPU). Is it implementation dependent?
Thanks. | For `erase(key)`, the standard says that all elements with value key are removed. There may of course be no such values.
For `erase(it)` (where `it` is a `std::map::iterator`), the standard says that the element pointed to by it is removed - unfortunately, if it is `end()` it does not point to a valid element and you are off in **undefined behaviour** land, as you would be if you used `end()` for any other map operation. See section 23.1.2 for more details. | `end()` is not an interator into the map. It's effectively 'one past the end' of the map.
The 'iterator' version wants an iterator to something in the map.
The 'key' version of erase does the lookup and protects itself against key not found, the iterator version assumes you aren't trying to break stuff. | map.erase( map.end() )? | [
"",
"c++",
"stl",
"dictionary",
"iterator",
""
] |
I have a class that looks like this:
```
public class UploadBean {
protected UploadBean(Map<String,?> map){
//do nothing.
}
}
```
To use reflection and create a object by invoking the corresponding constructor, I wrote code as follows:
```
Class<?> parTypes[] = new Class<?>[1];
parTypes[0] = Map.class;
Constructor ct = format.getMappingBean().getConstructor(parTypes);
Object[] argList = new Object[1];
argList[0] = map;
Object retObj = ct.newInstance(argList);
```
This code fails at runtime with "No Such Method Exception".
Now, how do I set the param type correctly?! such that the generic map argument in the constructor is identified? | The constructor is protected - if you make it public *or* use `getDeclaredConstructor` instead of `getConstructor` it should work.
(You'll need to use `setAccessible` if you're trying to call this from somewhere you wouldn't normally have access.)
EDIT: Here's a test to show it working okay:
```
import java.lang.reflect.*;
import java.util.*;
public class UploadBean {
// "throws Exception" just for simplicity. Not nice normally!
public static void main(String[] args) throws Exception {
Class<?> parTypes[] = new Class<?>[1];
parTypes[0] = Map.class;
Constructor ct = UploadBean.class.getDeclaredConstructor(parTypes);
Object[] argList = new Object[1];
argList[0] = null;
Object retObj = ct.newInstance(argList);
}
protected UploadBean(Map<String,?> map){
//do nothing.
}
}
``` | The generic information is not available at runtime, it's just for static analysis, so do it as if the generics didn't exist. | Java Generics and reflection! | [
"",
"java",
"generics",
"reflection",
""
] |
Within my scenario, I have a button within an iframe section of my page that performs some database processing.
What I need is a means of performing a page refresh of the main page, when this button within the iframe is pressed.
I am seeking some JavaScript code that I can trigger within the iframe, that will reload the main window holding the iframe. | ```
window.top.location.reload();
``` | If the parent's and child iframe domains will be different you will get cross-window security error, in that case you can try to use following:
```
window.parent.location = document.referrer;
``` | How to reload Main Page from within an iFrame | [
"",
"javascript",
""
] |
And I'm doing some exercises about switch. I just did it from console application and I would like to do it in window forms applications. I'm looking for syntax on how to do switch in window forms.
In console it's usually like this:
```
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered numbered two");
break;
default:
break;
```
how can I do this in my window forms, if I would like to display this cases in listbox1?
Thanks
=======
Thank you. I tried this one but I'm getting an error. This is what I've tried:
```
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one");
break;
}
}
```
========
This is the code I'm trying to do:
```
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered one");
break;
}
}
```
====
This is the new code:
```
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
WriteNumber(intNumber);
}
else
{
MessageBox.Show("Please enter an integer not a character");
}
}
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listBox2.Items.Add("You have entered numbered one");
break;
case 2:
listBox2.Items.Add("You have entered numbered two");
break;
case 3:
listBox2.Items.Add("You have entered numbered three");
break;
default:
listBox2.Items.Add("You have exceeded the range of 1-3. Please enter the number between 1-3");
break;
}
``` | The switch/case syntax is identical between WinForms and a console app (or any other type of application or class library), the only difference is how you display the data. If you want to add a string to a listbox (which is apparently what you're asking), it's as simple as
```
listBox1.Items.Add("Here is the text of the list box item");
``` | This should work:
```
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one"); break;
}
}
```
You need to remove the **static** keyword to get access to the listbox, which is an instance variable. | Using the switch statement in a Windows Forms application | [
"",
"c#",
"winforms",
"switch-statement",
""
] |
We have an application written in C language which interacts with Oracle database. This application is an executable and runs on unix platform. We need to expose this application over http as web service for others to consume.
I thought of using JNI and CXF for webservice and run the application in tomcat.
Is this a right solution or there are other possibilities?
I found Axis2 supporting C language to write webservice. I have no experience of C language. Is Axis2 in C is good? What http server I can use to deploy the app? Would Apache webserver siffice in this case?
EDIT: The command line is not an option as though I mentioned its an exe but the part which I have to expose don't have any command line available and its bit hard as it needs complicated data structure as input. | It depends on a few factors. Vinko's method requires the app has a good clean command-line interface. Further, creating a new process for every webservice request will limit the number of requests that can be serviced. This may or may not be okay depending on how big the audience is expected to be.
If there's not that great a command-line interface and you want to maximize the number of requests you can serve, that then leaves you two main choices. Write the web service in Java, and call out to C with JNI or [JNA](https://github.com/twall/jna/). Or, write it in pure C or C++. The last is probably not advisable if the responsible developers don't know any C.
EDIT: Given that command-line is not an option, I recommend Java with JNI or JNA. | Consider using the Apache Foundation package [Axis2/C](http://ws.apache.org/axis2/c/). It is a pretty solid interface, though it still has slightly limited portability (works out of the box on Linux, but not on Solaris, for example - needs some tweaks).
However, since you say you don't have the experience in C, that may make it too daunting for you. On the other hand, you say the code you're trying to convert to a web service is in C (plus perhaps Oracle OCI); that means that you are going to find it hard to avoid learning some C to get things working. | Enable C application as Webservice | [
"",
"java",
"c",
"web-services",
"java-native-interface",
""
] |
I got two dates, how do I check if both dates does not exceed over one year?
Short question! :-) | ```
if (Math.Abs((d1 - d2).TotalDays) < 365)
```
---
**Edit:** This should account for leap years better.
```
if ( d1 <= d2 && d1.AddYears(1) >= d2 || d2 < d1 && d2.AddYears(1) > d1)
```
**Update:**
I like @JDunkerley's solution better:
```
if (d1 < d2 ? d2 < d1.AddYears(1) : d1 < d2.AddYears(1))
``` | I give you a little example:
```
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
``` | Two dates within a year of each other | [
"",
"c#",
"asp.net",
"datetime",
""
] |
I cannot find a way to make this work and hoping someone has an idea. A simplified example would be having a list of say integers 1-100, i want to group every 3 rows so the result would be 1,2,3 in first group then 4,5,6 in next group etc. I know how to get every nth record but what I need is all the records so I can then aggregate them, using first, last, sum, max, etc.
Thanks! | ```
var q = Enumerable.Range(0, 100).GroupBy(x => x/3);
```
Am I missing something? | This example should work for querying non-numeric collections. It projects an index into the object to be grouped, and then removes it again during the grouping.
```
var studentQuery2 = students
.Select((student, index) => new {student, index})
.GroupBy(g => g.index / 3, i => i.student);
``` | How to use Linq to group every N number of rows | [
"",
"c#",
"linq",
"group-by",
""
] |
How do I set the classpath order in ant?
Specifically, When I am trying to run my ant build, I need it to pick up a class in a jar (jaxws-api.jar) instead of the same class which is in the jre. I am currently setting the classpath to explicitly include those jars however it seems to still pick up the jre first. What I am looking for is some type of equivalent to Order/Export in eclipse under the "Build Configuration" menu.
Edit: I'll be more explicit. I have some classes which were generated with CXF 2.1.3. They call javax.xml.ws.Service#getPort(QName, Class, WebServiceFeature...). I am using Java version 1.6.02. This method does not exist in that class in that version. However, it does exist in the jaxws version of the class (and later versions of the JRE class). When I try to do an ant build, the JRE class is always picked up first before the jaxws version. This makes my compilation fail. How can I modify my classpath to put the JRE last?
I can't change the JRE version, so please don't suggest that as a fix unless it is the only possible one. | Looks like you need to use the `bootclasspath` setting in the [Javac](http://ant.apache.org/manual/Tasks/javac.html) or [Java](http://ant.apache.org/manual/Tasks/java.html) Ant task.
You can always do `ant -v` to get verbose output of your Ant build. | Jars in the ant classpath are placed in the order you declare them. | Ant classpath Order | [
"",
"java",
"ant",
"classpath",
""
] |
I want a nice way to get the current unix timestamp from a java Date object, this is my solution:
```
public class Date extends java.util.Date {
public int getUnixTimeStamp() {
int unixtimestamp = (int) (this.getTime() * .001);
return unixtimestamp;
}
}
```
That works fine, but the problem is when I try to cast a java Date object to my custom date class, i.e:
```
Calendar foo = Calendar.getInstance();
foo.set(0, 0, 0, 12, 30);
myapp.Date foo2 = (myapp.Date)foo.getTime();
```
This generates: Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to myapp.Date
I understand why this exception is made but is there any way to cast a superclass to a subclass? If not, how would you implement the unixtimestamp method? I use it quite often in my application. | You can't cast a superclass in a subclass because the subclass may have a bigger interface than the superclass means the subclass can have functions like getUnixTimeStamp() that the superclass doesn't have. In your example that would mean you trying to call getUnixTimeStamp on a java.util.Date.
You can use a Delegate or Composition instead of inheritance here.
That means you have a Class
```
public class Date {
private java.util.date date;
public Date(java.util.Date date) {
this.date = date
}
public int getUnixTimeStamp() {
int unixtimestamp = (int) ((this.date.getTime()) * .001);
return unixtimestamp;
}
```
}
In this way you don't cast the date into your date you create a class arround the java.util.date.
If you use only this function it could be an easier solution to just create a static util function getUnixTime(Date date) that returns the changed date. | If you're keen on having your subclass, implement a constructor in your `Date` class taking a `java.util.Date foo` and in it call `super` with `foo.getTime()`; then instead of casting you just call `Date(foo)` to instantiate your subclass. | Java typecasting and inheritance | [
"",
"java",
"oop",
"casting",
""
] |
I want to view the `Log` on device i.e the `System.out.println()`.
I am able to view on *DDMS* but how to view on device screen while running an *APK* file. | Provided you have root on your phone you can use the `logcat` utility in the `Terminal` application:
```
# logcat
D/dalvikvm( 142): GC freed 200 objects / 8744 bytes in 254ms
etc..
```
It displays the same log (`/dev/log/main`) as the `adb logcat` command that was suggested in another answer. | There is also a Logcat app available for android.
**code.google.com/p/android-random/downloads/list** | View the Log on device | [
"",
"java",
"android",
"logging",
""
] |
For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code:
```
template<int> struct TT {typedef int type;};
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
struct P1 {int x; };
struct P2 {float X; };
// it also could be struct P3 {unknown_type X; };
int main()
{
P1 p1 = {1};
P2 p2 = {1};
Check_x(p1); // must return true
Check_x(p2); // must return false
return 0;
}
```
But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template:
```
template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; }
```
But it does not compile in GNU C++. Is there universal solution?
UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.
P.S. Please, do not post C++11 solutions here because they are obvious and not relevant to the question. | Another way is this one, which relies on [SFINAE for expressions](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2634.html) too. If the name lookup results in ambiguity, the compiler will reject the template
```
template<typename T> struct HasX {
struct Fallback { int x; }; // introduce member name "x"
struct Derived : T, Fallback { };
template<typename C, C> struct ChT;
template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];
template<typename C> static char (&f(...))[2];
static bool const value = sizeof(f<Derived>(0)) == 2;
};
struct A { int x; };
struct B { int X; };
int main() {
std::cout << HasX<A>::value << std::endl; // 1
std::cout << HasX<B>::value << std::endl; // 0
}
```
It's based on a brilliant idea of someone on usenet.
Note: HasX checks for any data or function member called x, with arbitrary type. The sole purpose of introducing the member name is to have a possible ambiguity for member-name lookup - the type of the member isn't important. | Here is a solution simpler than [Johannes Schaub - litb](https://stackoverflow.com/users/34509/johannes-schaub-litb)'s [one](https://stackoverflow.com/a/1007175/1137388). It requires C++11.
```
#include <type_traits>
template <typename T, typename = int>
struct HasX : std::false_type { };
template <typename T>
struct HasX <T, decltype((void) T::x, 0)> : std::true_type { };
```
**Update**: A quick example and the explanation on how this works.
For these types:
```
struct A { int x; };
struct B { int y; };
```
we have `HasX<A>::value == true` and `HasX<B>::value == false`. Let's see why.
First recall that `std::false_type` and `std::true_type` have a `static constexpr bool` member named `value` which is set to `false` and `true`, respectively. Hence, the two templates `HasX` above inherit this member. (The first template from `std::false_type` and the second one from `std::true_type`.)
Let's start simple and then proceed step by step until we get to the code above.
1) Starting point:
```
template <typename T, typename U>
struct HasX : std::false_type { };
```
In this case, there's no surprise: `HasX` derives from `std::false_type` and hence `HasX<bool, double>::value == false` and `HasX<bool, int>::value == false`.
2) Defaulting `U`:
```
// Primary template
template <typename T, typename U = int>
struct HasX : std::false_type { };
```
Given that `U` defaults to `int`, `Has<bool>` actually means `HasX<bool, int>` and thus, `HasX<bool>::value == HasX<bool, int>::value == false`.
3) Adding a specialization:
```
// Primary template
template <typename T, typename U = int>
struct HasX : std::false_type { };
// Specialization for U = int
template <typename T>
struct HasX<T, int> : std::true_type { };
```
In general, thanks to the primary template, `HasX<T, U>` derives from `std::false_type`. However, there exists a specialization for `U = int` which derives from `std::true_type`. Therefore, `HasX<bool, double>::value == false` but `HasX<bool, int>::value == true`.
Thanks to the default for `U`, `HasX<bool>::value == HasX<bool, int>::value == true`.
4) `decltype` and a fancy way to say `int`:
A little digression here but, please, bear with me.
Basically (this is not entirely correct), `decltype(expression)` yields the type of *expression*. For instance, `0` has type `int` thus, `decltype(0)` means `int`. Analogously, `1.2` has type `double` and thus, `decltype(1.2)` means `double`.
Consider a function with this declaration:
```
char func(foo, int);
```
where `foo` is some class type. If `f` is an object of type `foo`, then `decltype(func(f, 0))` means `char` (the type returned by `func(f, 0)`).
Now, the expression `(1.2, 0)` uses the (built-in) comma operator which evaluates the two sub-expressions in order (that is, first `1.2` and then `0`), discards the first value and results in the second one. Hence,
```
int x = (1.2, 0);
```
is equivalent to
```
int x = 0;
```
Putting this together with `decltype` gives that `decltype(1.2, 0)` means `int`. There's nothing really special about `1.2` or `double` here. For instance, `true` has type `bool` and `decltype(true, 0)` means `int` as well.
What about a class type? For instace, what does `decltype(f, 0)` mean? It's natural to expect that this still means `int` but it might not be the case. Indeed, there might be an overload for the comma operator similar to the function `func` above that takes a `foo` and an `int` and returns a `char`. In this case, `decltype(foo, 0)` is `char`.
How can we avoid the use of a overload for the comma operator? Well, there's no way to overload the comma operator for a `void` operand and we can cast anything to `void`. Therefore, `decltype((void) f, 0)` means `int`. Indeed, `(void) f` casts `f` from `foo` to `void` which basically does nothing but saying that the expression must be considered as having type `void`. Then the built-in operator comma is used and `((void) f, 0)` results in `0` which has type `int`. Hence, `decltype((void) f, 0)` means `int`.
Is this cast really necessary? Well, if there's no overload for the comma operator taking `foo` and `int` then this isn't necessary. We can always inspect the source code to see if there's such operator or not. However, if this appear in a template and `f` has type `V` which is a template parameter, then it's no longer clear (or even impossible to know) whether such overload for the comma operator exists or not. To be generic we cast anyway.
Bottom line: `decltype((void) f, 0)` is a fancy way to say `int`.
5) SFINAE:
This is a whole science ;-) OK I'm exagerating but it's not very simple either. So I'll keep the explanation to the bare minimum.
SFINAE stands for Substitution Failure is Not An Error. It means that when a template parameter is substituted by a type, an illegal C++ code might appear but, *in some circunstances*, instead of aborting compilation the compiler simply ignores the offending code as if it wasn't there. Let's see how it applies to our case:
```
// Primary template
template <typename T, typename U = int>
struct HasX : std::false_type { };
// Specialization for U = int
template <typename T>
struct HasX <T, decltype((void) T::x, 0)> : std::true_type { };
```
Here, again, `decltype((void) T::x, 0)` is a fancy way to say `int` but with the benefit of SFINAE.
When `T` is substituted with a type, an invalid construct might appear. For instance, `bool::x` is not valid C++, so substituting `T` with `bool` in `T::x` yields an invalid construct. Under the SFINAE principle, the compiler doesn't reject the code, it simply ignores (parts of) it. More precisely, as we have seen`HasX<bool>` means actually `HasX<bool, int>`. The specialization for `U = int` should be selected but, while instantiating it, the compiler finds `bool::x` and ignores the template specialization altogether as if it didn't exist.
At this point, the code is essencially the same as in case (2) above where just the primary template exists. Hence, `HasX<bool, int>::value == false`.
The same argument used for `bool` holds for `B` since `B::x` is an invalid construct (`B` has no member `x`). However, `A::x` is OK and the compiler sees no issue in instantiating the specialization for `U = int` (or, more precisely, for `U = decltype((void) A::x, 0)`). Hence, `HasX<A>::value == true`.
6) Unnaming `U`:
Well, looking at the code in (5) again, we see that the name `U` is not used anywhere but in its declaration (`typename U`). We can then unname the second template argument and we obtain the code shown at the top of this post. | How to detect whether there is a specific member variable in class? | [
"",
"c++",
"visual-studio",
"templates",
"g++",
"sfinae",
""
] |
This may seems rather argumentative, but I just went through SQLAlchemy's [ORM tutorial](http://www.sqlalchemy.org/docs/05/ormtutorial.html) and ended up with the following code:
```
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('fullname', String),
Column('password', String)
)
metadata.create_all(engine)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
users_table = User.__table__
metadata = Base.metadata
Session = sessionmaker(bind=engine)
Session = sessionmaker()
Session.configure(bind=engine) # once engine is available
session = Session()
# actually using the ORM isn't too bad..
ed_user = User('ed', 'Ed Jones', 'edspassword')
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
print our_user
session.add_all([
User('wendy', 'Wendy Williams', 'foobar'),
User('mary', 'Mary Contrary', 'xxg527'),
User('fred', 'Fred Flinstone', 'blah')])
ed_user.password = 'f8s7ccs'
print session.dirty
print session.new
session.commit()
for instance in session.query(User).order_by(User.id):
print instance.name, instance.fullname
for name, fullname in session.query(User.name, User.fullname):
print name, fullname
```
This seems incredibly complicated for effectively a Hello World table, especially compared to the roughly similar SQLObject code:
```
from sqlobject import SQLObject, StringCol, sqlhub, connectionForURI
sqlhub.processConnection = connectionForURI('sqlite:/:memory:')
class Person(SQLObject):
fname = StringCol()
mi = StringCol(length=1, default=None)
lname = StringCol()
Person.createTable()
p = Person(fname="John", lname="Doe")
p.mi = 'Q'
p2 = Person.get(1)
print p2
print p2 is p
```
I understand SQLAlchemy is "more powerful", but that power seems to come at a cost, or am I missing something? | Well, there is one thing you are missing: the tutorial you mention doesn't "build" a complete example, the different snippets of code are not meant to be concatenated into one source file. Rather, they describe the different ways the library can be used. No need to try and do the same thing over and over again yourself.
Leaving out the actually-using-the-orm part from your example, the code could look like this:
```
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(engine))
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
Base.metadata.create_all()
```
The "declarative" extension takes care of defining the table and mapping it to your class, so you don't need to declare the `users_table` yourself. The User class will also allow instantiating with keyword arguments, like `User(name="foo")`, (but not positional arguments though).
I've also added use of scoped\_session, which means you can directly use `Session` without actually having to instantiate it (it will instantiate a new session if there isn't already one present in the current thread, or reuse the existing one otherwise) | The code examples you give aren't apples-to-apples. The SQLAlchemy version could be pared down a bit:
```
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column('id', Integer, primary_key=True)
name = Column('name', String)
fullname = Column('fullname', String)
password = Column('password', String)
def __repr__(self):
return "" % (self.name, self.fullname, self.password)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# actually using the ORM isn't too bad..
ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
session.add_all([
User(name='wendy', fullname='Wendy Williams', password='foobar'),
User(name='mary', fullname='Mary Contrary', password='xxg527'),
User(name='fred', fullname='Fred Flinstone', password='blah')])
ed_user.password = 'f8s7ccs'
session.flush()
for instance in session.query(User).order_by(User.id):
print instance.name, instance.fullname
for name, fullname in session.query(User.name, User.fullname):
print name, fullname
```
You might also find [Elixir](http://elixir.ematia.de/trac/wiki) more like SQLObject (but since I haven't used either, that's just a guess).
Not having used SQLObject at all, I can't comment on what exactly SA does better. But I have had great experiences with SA, especially when dealing with complicated, real-world, legacy schemas. It does a good job of coming up with good SQL queries by default, and has lots of ways to tune them.
I've found SQLAlchemy author's [elevator pitch](http://techspot.zzzeek.org/?p=33) to hold up pretty well in practice. | SQLAlchemy is convoluted? | [
"",
"python",
"orm",
"sqlalchemy",
""
] |
Is there any plugins I can use for Eclipse that will show graphical view of classes dependencies? | **[Classycle](http://classycleplugin.graf-tec.ch/index.html)** can be a good start (for static dependencies between classes at least)
(I find their graph a bit complicated to follow though : [CDA - Class Dependency Analyzer](https://stackoverflow.com/questions/62276/java-package-cycle-detection-how-to-find-the-specific-classes-involved/71610#71610) is an external tool, but produce much more readable dependency graphs) | [stan4j](http://stan4j.com/):
* Free for private use
* For commercial use requires license
* Video on homepage does a good job of demoing features | View classes dependency graph plugin? | [
"",
"java",
"eclipse",
"eclipse-plugin",
"eclipse-rcp",
"eclipse-3.4",
""
] |
Is there a way to directly "restart" a background worker?
Calling CancelAsync() followed by RunWorkerAsync() clearly won't do it as their names imply.
Background info:
I have a background worker which calculates a total in my .net 2.0 Windows Forms app.
Whenever the user modifies any value which is part of this total I'd like to restart the background worker in case it would be running so that directly the latest values are considered. | The backgriound work itself does not do any cancleing.
When you call `bgw.CancelAsync` it sets a flag on the background worker that you need to check yourself in the DoWork handler.
something like:
```
bool _restart = false;
private void button1_Click(object sender, EventArgs e)
{
bgw.CancelAsync();
_restart = true;
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 300; i++)
{
if (bgw.CancellationPending)
{
break;
}
//time consuming calculation
}
}
private void bgw_WorkComplete(object sender, eventargs e) //no ide to hand not sure on name/args
{
if (_restart)
{
bgw.RunWorkerAsync();
_restart = false;
}
}
``` | There are a couple of options, it all depends on how you want to skin this cat:
If you want to continue to use `BackgroundWorker`, then you need to respect the model that has been established, that is, one of "progress sensitivity". The stuff inside `DoWork` is clearly required to always be aware of whether or not the a pending cancellation is due (i.e., there needs to be a certain amount of polling taking place in your `DoWork` loop).
If your calculation code is monolithic and you don't want to mess with it, then don't use `BackgroundWorker`, but rather fire up your own thread--this way you can forcefully kill it if needs be. | Restart background worker | [
"",
"c#",
".net",
"backgroundworker",
""
] |
Which Javascript AOP library do you use, and what are its key features ? | Here is what I found until now :
* [dotvoid](http://www.dotvoid.com/2005/06/aspect-oriented-programming-and-javascript/)'s implementation, clean syntax, nice to use, the article is a good introduction on why/how to use the given code, supports introductions, but is bugged,
* Dojo has what seems to be a good built-in implementation in [dojox](http://api.dojotoolkit.org/jsdoc/1.3/dojox.lang.aspect), [here](http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/) is a nice introduction on how to use it,
* there is a plugin for jQuery, [jquery-aop](http://code.google.com/p/jquery-aop/), with a rougher syntax, passing objects and methods in a javascript object,
* [AspectJS](http://zer0.free.fr/aspectjs/aspectjs.js) with an even rougher syntax (need to pass type of pointcut as arguments to a single method)
Like I said, dotvoid's code did not work.
I corrected a little and got something that seems to work better :
```
InvalidAspect = new Error("Missing a valid aspect. Aspect is not a function.");
InvalidObject = new Error("Missing valid object or an array of valid objects.");
InvalidMethod = new Error("Missing valid method to apply aspect on.");
function doBefore(beforeFunc,func){
return function(){
beforeFunc.apply(this,arguments);
return func.apply(this,arguments);
};
}
function doAfter(func, afterFunc){
return function(){
var res = func.apply(this,arguments);
afterFunc.apply(this,arguments);
return res;
};
}
Aspects = function(){};
Aspects.prototype={
_addIntroduction : function(intro, obj){
for (var m in intro.prototype) {
obj.prototype[m] = intro.prototype[m];
}
},
addIntroduction : function(aspect, objs){
var oType = typeof(objs);
if (typeof(aspect) != 'function')
throw(InvalidAspect);
if (oType == 'function'){
this._addIntroduction(aspect, objs);
}
else if (oType == 'object'){
for (var n = 0; n < objs.length; n++){
this._addIntroduction(aspect, objs[n]);
}
}
else{
throw InvalidObject;
}
},
addBefore : function(aspect, obj, funcs){
var fType = typeof(funcs);
if (typeof(aspect) != 'function')
throw(InvalidAspect);
if (fType != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++){
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = doBefore(aspect,old)
obj.prototype[fName] = res;
}
},
addAfter : function(aspect, obj, funcs) {
if (typeof(aspect) != 'function')
throw InvalidAspect;
if (typeof(funcs) != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++)
{
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = doAfter(old,aspect);
obj.prototype[fName] = res;
}
},
addAround : function(aspect, obj, funcs){
if (typeof(aspect) != 'function')
throw InvalidAspect;
if (typeof(funcs) != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++)
{
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = aspect(old);
obj.prototype[fName] = res;
}
return true;
}
}
``` | Have you seen `meld.js` and `aop.js` from
<https://github.com/cujojs>?
SpringSource provides AOP functionality there, in addition to a bunch of other useful things for advanced Javascript programmers.
**Disclaimer**: I work for SpringSource. | Javascript AOP libraries | [
"",
"javascript",
"aop",
""
] |
Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order.
Usage would be something like
```
./find.py LinkThatStartsWithB
```
So it would navigate to the webpage associated with the letter B.
My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?
What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index.
(A = 1, B = 2...)
Example code:
```
#Use base url as starting point then add extension on end.
Base_URL = "http://www.website.com/"
#Use list index as representation of letter
Alphabetic_Urls = [
"/extensionA.html",
"/extensionB.html",
"/extensionC.html",
]
```
Or would Dictionary be a better bet?
Thanks | How are you getting this list of URLS?
If your commandline app is crawling the website for links, and you are only looking for a single item, building a dictionary is pointless. It will take at least as long to build the dict as it would to just check as you go! eg, just search as:
```
for link in mysite.getallLinks():
if link[0] == firstletter:
print link
```
If you are going to be doing multiple searches (rather than just a single commandline parameter), *then* it might be worth building a dictionary using something like:
```
import collections
d=collections.defaultdict(list)
for link in mysite.getallLinks():
d[link[0]].append(link) # Dict of first letter -> list of links
# Print all links starting with firstletter
for link in d[firstletter]:
print link
```
Though given that there are just 26 buckets, it's not going to make that much of a difference. | The smartest way here will be whatever makes the code simplest to read. When you've only got 26 items in a list, who cares what algorithm it uses to look through it? You'd have to use something really, *really* stupid to make it have an impact on performance.
If you're really interested in the performance though, you'd need to benchmark different options. Looking at just the complexity doesn't tell the whole story, because it hides the factors involved. For instance, a dictionary lookup will involve computing the hash of the key, looking that up in tables, then checking equality. For short lists, a simple linear search can sometimes be more efficient, depending on how costly the hashing algorithm is.
If your example is really accurate though, can't you just take the first letter of the input string and predict the URL from that? (`"/extension" + letter + ".html"`) | A question on python sorting efficiency | [
"",
"python",
"sorting",
""
] |
I need to do 2 things: run a batch file (works fine), and run a command (does not work).
The method for the command throws the exception 'file not found'. If I open a cmd window, and type the command, it works perfectly.
```
private static void Rescan()
{
//System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("DEVCON ReScan");
//psi.RedirectStandardOutput = true;
//psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//psi.UseShellExecute = false;
//System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "DEVCON ReScan";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
System.IO.StreamReader myOutput = proc.StandardOutput;
proc.WaitForExit(4000);
if (proc.HasExited)
{
string output = myOutput.ReadToEnd();
FileIO.WriteLog(_writePath, output);
}
}
```
The commented code also throws the same exception. | `DEVCON ReScan` is really the name of the executable? I guess the executable is DEVCON, while ReScan is a parameter. This means you have to set StartInfo.FileName to "DEVCON" and StartInfo.Arguments to "ReScan". | Is the DEVCON application actually in the working directory ?
Otherwise it won't work unless you specify the full path to it.
Furthermore you have to specify the extension, so I suppose you'd go for "Devcon.exe",
and specify the parameters not in the filename but in the parameters :) | How do I run Command line commands from code | [
"",
"c#",
".net",
"command-line",
"batch-file",
""
] |
How do I initialise a list with 10 times a default value in Python?
I'm searching for a good-looking way to initialize a empty list with a specific range.
So make a list that contains 10 zeros or something to be sure that my list has a specific length. | If the "default value" you want is immutable, @eduffy's suggestion, e.g. `[0]*10`, is good enough.
But if you want, say, a list of ten `dict`s, do *not* use `[{}]*10` -- that would give you a list with the **same** initially-empty `dict` ten times, **not** ten distinct ones. Rather, use `[{} for i in range(10)]` or similar constructs, to construct ten separate `dict`s to make up your list. | list multiplication works.
```
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
``` | Initialise a list to a specific length in Python | [
"",
"python",
"list",
""
] |
Here is my button
```
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
```
Here is the server function
```
public void doSomething(int num)
{
int someOtherNum = 10 + num;
}
```
When I try to compile the code I get the error "Method Name Expected" for the line:
```
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
```
What am I doing wrong? Am I not allowed to pass values to the server from an OnClick event? | There are two problems here. First, the onclick event has a specific signature. It is
```
MethodName(object sender, EventArgs e);
```
Second, in the markup, you need to pass the Method name only with no parentheses or params.
```
<asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />
```
Then change your codebehind as follows:
```
public void doSomething(object sender, EventArgs e)
{
....
}
```
The passing of parameters can done on a client side click event handler, in this case OnClientClick, but not on the server side handler. | OnClick of the Button is an Event Handler. To hook a function to an eventHandler you need to obey the Contract that was defined by the EventHandler, as [mentioned](https://stackoverflow.com/questions/1005499/problems-with-aspbutton-onclick-event/1005514#1005514) by Jose. OnClick is bound to a function of the format `void doSomething(object sender, EventArgs e)`. So your function should be of the same format.
I am unsure why would want to pass a parameter to the Event Handler. If you want to take some manuplation you need to do that using some other control.
```
<asp:TextBox ID="txtNumber" runat="server" /><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />
```
And in the Code
```
public void doSomething(object sender, EventArgs e)
{
int AnotherNumber= Int32.Parse(txtNumber.Text)+10;
}
``` | Problems with asp:Button OnClick event | [
"",
"c#",
"asp.net",
"onclick",
""
] |
My database must be updated at arbitrary intervals, manually, with new info to put on standart tables that don't require structural modifications. one app will update the database.
Another app, the one I will distribute (to friends and family only, but doesn't require any security feature to it, like encrypting the database) will read the database and use its data on labels, listviews, etc.
The problem is, I'm the perfect definition of full-fledged n00b at programming of any sort, and still don't know what database to use.
I thought that I should use a SQL CE (\*.sdf) file, and store that database thing on an FTP. then, I could download it and get data from it everytime the "client" app runs, and certain button ("connect") is clicked.
After some hard-core googling, I found out how to connect to the sdf thing, using this connection string:
```
Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=D:\Documents and Settings\Camilo\JCTM.sdf
```
So it connects, or at least didn't show any error.
I don't know if it's a good idea to use sdf SQL CE files as databases, if it's too hard maybe I should go for XML? what do you guys suggest, what is the easiest way to implement very simple databases in VB.NET?
By simple databases I mean:
- no search needed
- no advanced features except storing strings on tables with columns and rows
- easy to access, read, edit, etc. by different VB.NET apps
Is sdf a good idea? | Luckily for you, you can abstract away the need to be concerned with which back-end database you use to store your data.
Technologies such as ODBC (Open Database Connectivity) and OLEDB (Object Linking and Embedding, Database) allow you to limit your concern for the backend datastore to the task of crafting your connection string. In your example, the connection string says, "I'm going to connect to a SQL Server CE database via its OLEDB provider, and it's physically located over on D:/...
Within the code, you use standard OLEDB mechanisms to access and manage the database. Because of this abstraction, you can use OLEDB providers for SQL Server, Oracle, XML, Access or comma delimited text files as your backing store if you wish, and the only change you need to make to your code is the connection string. Your choice then should be to pick the database that you have the tools and know-how to set up and manage initially. | I would recommend [Sql Server Express](http://www.microsoft.com/express/sql/default.aspx) Its free and can be redistributed with .net applications as part of the install process.
The challenge will be syncing the changes between the different clients. If you have access to a FTP server, you may have the ability to host a website in IIS. If you can do that you can just use webservices and read against one database instead of copying one local. | What database should I use in this VB.NET app? | [
"",
"sql",
"vb.net",
"visual-studio-2008",
"sql-server-ce",
""
] |
I need a way to load multiple style sheets with the same rule names, and then apply them to different elements on a page. Is this possible?
Here's an example of something I'd like to do. Take the two style sheets below:
style1.css:
```
.size{
color: #FF6600;
font-size: 18px;
}
```
style2.css:
```
.size{
color: #FF0000;
font-size: 14px;
}
```
I would like to be able to import both of them into a page (perhaps with an id of some sort), and then set the text inside one particular div to use the rules from style1.css and another div should use the rules from style2.css.
I need to do things this way because it will allow users of my application to upload custom style sheets for different widgets on a page. This scheme should work, provided that the sheets use the same rule naming scheme. | The answer is no you can't do it this way. The rule loaded last will take precedence.
**You should differentiate the *different* widgets with *different* classes or IDs, and then you won't have the same rules.**
```
#widgetB .size{
color: #FF0000;
font-size: 14px;
}
#widgetA .size{
color: purple;
font-size: 10px;
}
``` | Maybe you can put each widget within an iframe. In that iframe you would call the custom stylesheet for that widget. That way you would win more modularity as well as allowing you to do what you want directly, without worrying about cheats to go around the problem. | Using different CSS sheets with the same rule names for different HTML document elements | [
"",
"javascript",
"css",
"html",
"styles",
""
] |
Is there any library or framework for writing P2P applications in Python ?
I know the initial Bittorrent client was written in Python. I'm looking something like [JXTA](https://jxta.dev.java.net/) but for Python. | Twisted is pretty much the answer to anything seriously network-related in Python, but you really have to buy into the Twisted way of doing things. It's not intrinsically a P2P stack, it's an event loop, callback system and networking framework.
Divmod Vertex is not currently being maintained, and was still pretty rough when I tried using it a few years ago.
[CSpace](http://cspace.in/) might be the closest to what you're looking for: "a platform for secure, decentralized, user-to-user communication over the internet." It abstracts the P2P and NAT traversal out so your app can act normally and not be "a P2P app."
Similarly, there was an old P2P system out of Australia called "The Circle" a few years ago, written entirely in Python, which had secure P2P messaging, chat, file sharing and other features. 0.41c was the last version: <http://savannah.nongnu.org/projects/circle/>
Also from my bookmarks:
<http://entangled.sourceforge.net/> is Entangled, "a distributed hash table (DHT) based on Kademlia, as well as a peer-to-peer tuple space implementation."
<http://khashmir.sourceforge.net/> is a Python distributed hash table, notable because it networks using the Airhook protocol, which is very fault-tolerant (designed for use e.g. over cellular networks).
<http://kenosis.sourceforge.net/> is a Python P2P RPC system. | Best option I can think, of course, is to use [**twisted**](http://twistedmatrix.com/).
[Old version of BitTorrent](http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz) was built with it. The link is to last known version that uses twisted. You can study that as a starting point.
There's also [Vertex](http://divmod.org/trac/wiki/DivmodVertex). It is a library that uses twisted and allows p2p with firewall bypassing. | Python Library/Framework for writing P2P applications | [
"",
"python",
"networking",
"p2p",
"jxta",
""
] |
I have a table which has two columns start time and end time. I am able to calculate the time duration for each row but I also want to get the total duration. how to do this.
Thanks | Your columns are of datatype TIMESTAMP, like this:
```
SQL> create table mytable (start_time,end_time)
2 as
3 select to_timestamp('2009-05-01 12:34:56','yyyy-mm-dd hh24:mi:ss')
4 , to_timestamp('2009-05-01 23:45:01','yyyy-mm-dd hh24:mi:ss')
5 from dual
6 union all
7 select to_timestamp('2009-05-01 23:45:01','yyyy-mm-dd hh24:mi:ss')
8 , to_timestamp('2009-05-02 01:23:45','yyyy-mm-dd hh24:mi:ss')
9 from dual
10 union all
11 select to_timestamp('2009-05-01 07:00:00','yyyy-mm-dd hh24:mi:ss')
12 , to_timestamp('2009-05-01 08:00:00','yyyy-mm-dd hh24:mi:ss')
13 from dual
14 /
Tabel is aangemaakt.
```
Subtracting one timestamp from another, leads to an INTERVAL datatype:
```
SQL> select start_time
2 , end_time
3 , end_time - start_time time_difference
4 from mytable
5 /
START_TIME END_TIME TIME_DIFFERENCE
------------------------------ ------------------------------ ------------------------------
01-05-09 12:34:56,000000000 01-05-09 23:45:01,000000000 +000000000 11:10:05.000000000
01-05-09 23:45:01,000000000 02-05-09 01:23:45,000000000 +000000000 01:38:44.000000000
01-05-09 07:00:00,000000000 01-05-09 08:00:00,000000000 +000000000 01:00:00.000000000
3 rijen zijn geselecteerd.
```
And INTERVAL datatypes cannot be summed. It's an annoying restriction:
```
SQL> select sum(end_time - start_time)
2 from mytable
3 /
select sum(end_time - start_time)
*
FOUT in regel 1:
.ORA-00932: inconsistente gegevenstypen: NUMBER verwacht, INTERVAL DAY TO SECOND gekregen
```
To circumvent this restriction, you can convert and calculate with the number of seconds, like this:
```
SQL> select start_time
2 , end_time
3 , trunc(end_time) - trunc(start_time) days_difference
4 , to_number(to_char(end_time,'sssss')) - to_number(to_char(start_time,'sssss')) seconds_difference
5 from mytable
6 /
START_TIME END_TIME DAYS_DIFFERENCE SECONDS_DIFFERENCE
------------------------------ ------------------------------ --------------- ------------------
01-05-09 12:34:56,000000000 01-05-09 23:45:01,000000000 0 40205
01-05-09 23:45:01,000000000 02-05-09 01:23:45,000000000 1 -80476
01-05-09 07:00:00,000000000 01-05-09 08:00:00,000000000 0 3600
3 rijen zijn geselecteerd.
```
And then they are normal NUMBERs that can be summed
```
SQL> select sum
2 ( 86400 * (trunc(end_time) - trunc(start_time))
3 + to_number(to_char(end_time,'sssss')) - to_number(to_char(start_time,'sssss'))
4 ) total_time_difference
5 from mytable
6 /
TOTAL_TIME_DIFFERENCE
---------------------
49729
1 rij is geselecteerd.
```
And if you wish, you can convert this number back to an INTERVAL:
```
SQL> select numtodsinterval
2 ( sum
3 ( 86400 * (trunc(end_time) - trunc(start_time))
4 + to_number(to_char(end_time,'sssss')) - to_number(to_char(start_time,'sssss'))
5 )
6 , 'second'
7 ) time_difference
8 from mytable
9 /
TIME_DIFFERENCE
------------------------------
+000000000 13:48:49.000000000
1 rij is geselecteerd.
```
Regards,
Rob. | This method for Oracle is simple, a bit of a hack though:
```
select sum((end_timestamp+0) - (start_timestamp+0))
from your_table
```
Result is a NUMBER of days (with fractional part for hours, minutes and you know).
I don't know what timestamp + 0 does exactly; maybe the ANSI timestamp gets converted to Oracle's earlier timestamp type that allows simple arithmetic. | Calculate the Sum of duration in sql query | [
"",
"sql",
"oracle",
""
] |
I have a function called "go()" which needs to be called thrice on page load. Right now I have called it on the ready event of a div with class "nav". Can someone suggest how can I call the go function thrice. Adding go() calls one after other calls it only once.
```
$('.nav').ready(function() {
go();
});
``` | Even though you say this does not work, it should...
```
$('.nav').ready(function() {
go();
go();
go();
});
```
Update:
If there is an error in your go() function, it might terminate execution before go() returns for the first time. Run in Firebug and see if you are getting any errors. | ```
$('.nav').ready(function() {
go();
go();
go();
});
```
Should call it three times. | Calling a function more than once in jQuery | [
"",
"javascript",
"jquery",
""
] |
In a django application I am working on, I have just added the ability to archive a number of files (starting 50mb in total) to a zip file. Currently, i am doing it something like this:
```
get files to zip
zip all files
send HTML response
```
Obviously, this causes a big wait on line two where the files are being compressed. What can i do to make this processes a whole lot better for the user? Although having a progress bar would be the best, even if it just returned a static page saying 'please wait' or whatever.
Any thoughts and ideas would be loved. | You should keep in mind showing the progress bar may not be a good idea, since you can get timeouts or get your server suffer from submitting lot of simultaneous requests.
Put the zipping task in the queue and have it callback to notify the user somehow - by e-mail for instance - that the process has finished.
Take a look at [django-lineup](http://code.google.com/p/django-lineup/)
Your code will look pretty much like:
```
from lineup import registry
from lineup import _debug
def create_archive(queue_id, queue):
queue.set_param("zip_link", _create_archive(resource = queue.context_object, user = queue.user))
return queue
def create_archive_callback(queue_id, queue):
_send_email_notification(subject = queue.get_param("zip_link"), user = queue.user)
return queue
registry.register_job('create_archive', create_archive, callback = create_archive_callback)
```
In your views, create queued tasks by:
```
from lineup.factory import JobFactory
j = JobFactory()
j.create_job(self, 'create_archive', request.user, your_resource_object_containing_files_to_zip, { 'extra_param': 'value' })
```
Then run your queue processor (probably inside of a screen session):
```
./manage.py run_queue
```
Oh, and on the subject you might be also interested in [estimating zip file creation time](https://stackoverflow.com/questions/767684/estimating-zip-size-creation-time). I got pretty slick answers there. | Fun fact: You might be able to use a progress bar to trick users into thinking that things are going faster than they really are.
<http://www.chrisharrison.net/projects/progressbars/index.html> | Progress bar with long web requests | [
"",
"python",
"django",
""
] |
How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript? | From [Alexandre Gomes Blog](http://www.alexandre-gomes.com/?p=115) I have not tried it. Let me know if it works for you.
```
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
``` | Using jQuery, you can shorten Matthew Vines answer to:
```
function getScrollBarWidth () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
``` | How can I get the browser's scrollbar sizes? | [
"",
"javascript",
"scrollbar",
""
] |
I want to invoke methods with a certain attribute.
So I'm cycling through all the assemblies and all methods to find the methods with my attribute. Works fine, but how do I invoke a certain method when I only got it's MethodInfo.
```
AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
foreach (Assembly a in ass)
{
types = a.GetTypes();
foreach (Type t in types)
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
// Invoke a certain method
}
}
}
```
The problem is that I don't know the instance of the class that contains that certain method. So I can't invoke it properly because the methods are not static.
I also want to avoid creating a new instance of this class if possible. | This strikes me as an issue in terms of the problem definition rather than coding.
Instance methods depend on which instance they're called on - it makes no sense to call an instance method without caring about what it's called on. (As Martin says, an instance method which doesn't care which instance it's being called on should almost always be static. The only immediate exception I can think of for this is virtual methods, where the instance implicitly specifies which implementation to use.)
Work out what it really *means* in your context for there to be an annotated instance method. Why are you trying to invoke methods anyway? What's the bigger picture? What context do you have? I strongly suspect you'll want some notion of a context - a collection of objects which you *can* call the instance methods on. | Non-static methods are instance specific so you must instantiate the class to invoke the method. If you have the ability to change the code where it is defined and the method doesn't require itself to be part of an instance (it doesn't access or modify any non-static properties or methods inside the class) then best practice would be to make the method static anyway.
Assuming you can't make it static then the code you need is as follows:
```
foreach (Type t in types)
{
object instance = Activator.CreateInstance(t);
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
method.Invoke(instance, params...);
}
}
``` | Invoke method by MethodInfo | [
"",
"c#",
"reflection",
"invoke",
"methodinfo",
""
] |
I want to add one day to a particular date. How can I do that?
```
Date dt = new Date();
```
Now I want to add one day to this date. | Given a `Date dt` you have several possibilities:
**Solution 1:** You can use the `Calendar` class for that:
```
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
```
**Solution 2:** You should seriously consider using the **[Joda-Time library](http://www.joda.org/joda-time/)**, because of the various shortcomings of the `Date` class. With Joda-Time you can do the following:
```
Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
```
**Solution 3:** With **Java 8** you can also use the new **JSR 310** API (which is inspired by Joda-Time):
```
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
```
**Solution 4:** With **org.apache.commons.lang3.time.DateUtils** you can do:
```
Date dt = new Date();
dt = DateUtils.addDays(dt, 1)
``` | ```
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
```
Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.
Important hint: That is not correct in all cases. Read the WARNING comment, below. | How to add one day to a date? | [
"",
"java",
"datetime",
""
] |
What I need is an equivalent for PHP's `fseek()` function. The function works on files, but I have a variable that contains binary data and I want to work on it. I know I could use `substr()`, but that would be lame - it's used for strings, not for binary data. Also, creating a file and then using `fseek()` is not what I am looking for either.
Maybe something constructed with streams?
EDIT: Okay, I'm almost there:
```
$data = fopen('data://application/binary;binary,'.$bin,'rb');
```
> Warning: failed to open stream: rfc2397: illegal parameter | Kai:
You have almost answered yourself here. Streams are the answer. The following manual entry will be enlightening: <http://us.php.net/manual/en/wrappers.data.php>
It essentially allows you to pass arbitrary data to PHP's file handling functions such as fopen (and thus fseek).
Then you could do something like:
```
<?php
$data = fopen('data://mime/type;encoding,' . $binaryData);
fseek($data, 128);
?>
``` | fseek on data in a variable doesn't make sense. fseek just positions the file handle to the specified offset, so the next fread call starts reading from that offset. There is no equivalent of fread for strings.
Whats wrong with substr()?
With a file you would do:
```
$f = fopen(...)
fseek($f, offset)
$x = fread($f, len)
```
with substr:
```
$x = substr($var, offset, len)
``` | PHP fseek() equivalent for variables? | [
"",
"php",
"variables",
"stream",
"fseek",
""
] |
I have a collection of string paths like ["x1/x2/x3","x1/x2/x4","x1/x5"] in a list.
I need to construct a tree-like structure from this list which can be iterated to get a pretty printed tree.
like this
```
x1
/ \
x5 x2
/ \
x3 x4
```
Any ideas/suggestions?
I believe that the problem can be attacked first by processing the list of strings EDIT: The correct answer chosen was an elegant implementation, other suggestions were good too. | Follow an implementation of naive implementation of a visitable tree:
```
class Tree<T> implements Visitable<T> {
// NB: LinkedHashSet preserves insertion order
private final Set<Tree> children = new LinkedHashSet<Tree>();
private final T data;
Tree(T data) {
this.data = data;
}
void accept(Visitor<T> visitor) {
visitor.visitData(this, data);
for (Tree child : children) {
Visitor<T> childVisitor = visitor.visitTree(child);
child.accept(childVisitor);
}
}
Tree child(T data) {
for (Tree child: children ) {
if (child.data.equals(data)) {
return child;
}
}
return child(new Tree(data));
}
Tree child(Tree<T> child) {
children.add(child);
return child;
}
}
```
interfaces for Visitor Pattern:
```
interface Visitor<T> {
Visitor<T> visitTree(Tree<T> tree);
void visitData(Tree<T> parent, T data);
}
interface Visitable<T> {
void accept(Visitor<T> visitor);
}
```
sample implementation for Visitor Pattern:
```
class PrintIndentedVisitor implements Visitor<String> {
private final int indent;
PrintIndentedVisitor(int indent) {
this.indent = indent;
}
Visitor<String> visitTree(Tree<String> tree) {
return new IndentVisitor(indent + 2);
}
void visitData(Tree<String> parent, String data) {
for (int i = 0; i < indent; i++) { // TODO: naive implementation
System.out.print(" ");
}
System.out.println(data);
}
}
```
and finally (!!!) a simple test case:
```
Tree<String> forest = new Tree<String>("forest");
Tree<String> current = forest;
for (String tree : Arrays.asList("x1/x2/x3", "x1/x2/x4", "x1/x5")) {
Tree<String> root = current;
for (String data : tree.split("/")) {
current = current.child(data);
}
current = root;
}
forest.accept(new PrintIndentedVisitor(0));
```
output:
```
forest
x1
x2
x3
x4
x5
``` | Just split each path by its delimiter and then add them to a tree structure one by one.
i.e. if `'x1'` does not exist create this node, if it does exist go to it and check if there is a child `'x2'` and so on... | Construct a tree structure from list of string paths | [
"",
"java",
"tree",
""
] |
I have this line that works OK:
```
c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name)
```
But I want to use SQLite parameter substitution instead instead of string substitution (because I see [here](http://docs.python.org/library/sqlite3.html) that this is safer).
This is my (failed) try:
```
t = (name,)
c.execute('select cleanseq from cleanseqs WHERE newID="?"',t)
```
But this line returns:
> 'Incorrect number of bindings
> supplied. The current statement uses
> 0, and there are 1 supplied.'
So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.
So the question is: How do I convert this line:
```
c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name)
``` | about """If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them."""
What you remember from when you were building the whole SQL statement yourself is irrelevant.
The new story is: mark with a ? each place in the SQL statement where you want a value substituted then pass in a tuple containing one value per ? -- it's that simple; the wrapper will quote any strings to make sure that they are acceptable SQL constants. | To anyone who like me found this thread and got really frustrated by people ignoring the fact that sometimes you can't just ignore the quotes (because you're using say a LIKE command) you can fix this by doing something to the effect of:
```
var = name + "%"
c.execute('SELECT foo FROM bar WHERE name LIKE ?',(var,))
```
This will allow you to substitute in wildcards in this situation. | SQLite parameter substitution and quotes | [
"",
"python",
"sqlite",
""
] |
So let's say I want to select the ID of all my blog posts and then a count of the comments associated with that blog post, how do I use GROUP BY or ORDER BY so that the returned list is in order of number of comments per post?
I have this query which returns the data but not in the order I want? Changing the group by makes no difference:
```
SELECT p.ID, count(c.comment_ID)
FROM wp_posts p, wp_comments c
WHERE p.ID = c.comment_post_ID
GROUP BY c.comment_post_ID;
``` | I'm not familiar with pre-SQL92 syntax, so I'll express it in a way that I'm familiar with:
```
SELECT c.comment_post_ID, COUNT(c.comment_ID)
FROM wp_comments c
GROUP BY c.comment_post_ID
ORDER BY COUNT(c.comment_ID) -- ASC or DESC
```
What database engine are you using? In SQL Server, at least, there's no need for a join unless you're pulling more data from the posts table. With a join:
```
SELECT p.ID, COUNT(c.comment_ID)
FROM wp_posts p
JOIN wp_comments c ON c.comment_post_ID = p.ID
GROUP BY p.ID
ORDER BY COUNT(c.comment_ID)
``` | ```
SELECT p.ID, count(c.comment_ID) AS [count]
FROM wp_posts p, wp_comments c
WHERE p.ID = c.comment_post_ID
GROUP BY c.comment_post_ID;
ORDER BY [count] DESC
``` | SQL Join and Count can't GROUP BY correctly? | [
"",
"sql",
"join",
"count",
"group-by",
""
] |
I am trying to send report from sql reportserver 2008 as e mail attachment using ASP.NET and C#,
Till now I learned how to [Get report as PDF](http://weblogs.asp.net/srkirkland/archive/2007/10/29/exporting-a-sql-server-reporting-services-2005-report-directly-to-pdf-or-excel.aspx) in my code ,
Now I wanna combine line of codes like
```
byte[] bytes = rview.ServerReport.Render(format, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);
Response.OutputStream.Write(bytes, 0, bytes.Length);
Attachment reportAttachment = new Attachment(Response.OutputStream.Write(bytes,0,bytes.Length),"ado"); //Here I go wrong
```
Thanx in advance | Maybe I getting this wrong (I know little about SSRS) but I think you should
1. Save the file to the file system
```
System.IO.File.WriteAllBytes("c:\temp\temp.pdf", bytes);
```
2. Send the file by email
```
MailMessage mail = new MailMessage();
mail.From = "Me";
mail.To = "You";
mail.Subject = "Subject";
mail.Body = "Body";
mail.BodyFormat = MailFormat.Html;
mail.Attachments.Add(new MailAttachment("c:\temp\temp.pdf"));
try
{
SmtpMail.Send(mail);
}
catch(Exception ex)
{
Response.Write("Ouch! " + ex.Message);
}
``` | Instead of saving the pdf to the file system first, you could try to use the byte[] returned from the report server and attach this:
```
MemoryStream ms = new MemoryStream(bytes);
mail.Attachments.Add(new Attachment(ms, "temp.pdf"));
```
For a quick fudge on one of my reports I did the following:
```
WebClient client = new WebClient();
byte[] bytes = client.DownloadData("http://localhost/ReportServer/Pages/ReportViewer.aspx? *** report name *** &rs%3aFormat=PDF");
MemoryStream ms = new MemoryStream(bytes);
mail.Attachments.Add(new Attachment(ms, "temp.pdf"));
```
Hope this is helpful | Send SQL Report in E mail attachment using C# and ASP.NET | [
"",
"c#",
"asp.net",
"reporting-services",
""
] |
How do I handle big integers in C#?
I have a function that will give me the product of divisors:
```
private static int GetDivisorProduct(int N, int product)
{
for (int i = 1; i < N; i++)
{
if (N % i == 0)
{
Console.WriteLine(i.ToString());
product *= i;
}
}
return product;
}
```
The calling function is `GetDivisorProduct(N, 1)`
If the result is bigger than 4 digits , I should obtain only the last 4 digits. ( E.g. If I give an input of 957, the output is 7493 after trimming out only the last four values.
The actual result is 876467493.).
Other sample inputs: If I give 10000, the output is 0.
The `BigInteger` class has been removed from the C# library!
How can I get the last four digits? | If you're only looking at the last four digits, you don't need anything larger than an integer. Consider this:
When multiplying two numbers, if you are only interested in the least significant digits (i.e. the last four digits), then the **upper-most digits will not have an effect** on lowest digits of the outcome... so you can just "**throw out**" the most significant (right-side) digits **before you multiply**.
For example: I want to multiply two large numbers but I only need the last two digits:
```
int num1 = 123456789;
int num2 = 987654321;
int result = num1 * num2; // Last two digits would be "69" but this OVERFLOWS
```
but if we multiply only the last two digits...
```
int result = (num1 % 100) * (num2 % 100); // result = 89 * 21
```
89 \* 21 = 1869 (the last two digits are still "**69**" but we **have not overflowed**).
**I used this technique** to calculate the [Six Right-Most Digits of 1,000,000 factorial](http://www.codeproject.com/Messages/2621778/Re-The-six-rightmost-non-zero-digits-of-1000000-modified.aspx). | [.NET 4.0](http://blogs.msdn.com/bclteam/archive/2009/05/22/what-s-new-in-the-bcl-in-net-4-beta-1-justin-van-patten.aspx) has a [BigInteger](http://msdn.microsoft.com/fr-fr/library/system.numerics.biginteger(en-us,VS.100).aspx) class | Handling "Big" Integers in C# | [
"",
"c#",
"overflow",
"biginteger",
"modulo",
""
] |
We have a large amount of **C**/C++ code that's compiled for multiple targets, separated by #ifdefs. One of the targets is very different from the others and it's often important to know if the code you're editing is compiled for that target. Unfortunately the #ifdefs can be very spread out, so it's not always obvious which code is compiled for which targets.
Visual Studio's #ifdef highlighting can be helpful for visually identifying which code is compiled for which target, but changing the highlighting apparently requires modifications to the project file.
I'm interested in finding a tool or method that can help coders quickly recognize which targets are using each line of code. Even if it requires some sort of manual in-source annotation I think it could still be helpful. Best case it's automated, not tied to a specific editor or IDE, and it could be configured to warn in certain conditions (eg "you modified some code on Target X, be sure to test your code on that platform!"). | Check out [Visual SlickEdit](http://www.slickedit.com/). The *"Selective Display"* option might be what you are looking for. I can't find any on-line documentation on it, but it will allow you to essentially *apply* a set of macro definitions to the code. So you can tell it to show you the code as the compiler will see it with a set of macros defined. This is a lot more than preprocessor output since it literally hides blocks of code that would be excluded based on the macro definitions.
This doesn't give you the ability to answer the question "Under what preprocessor conditions is this line of code included in compilation" though. The nice thing is that it applies the selective display filter to searches and printing. | If your code is getting that big that you can't tell what #ifdef your in then it's time to refactor your code. I would recommend that you refactor it into seperate cpp files per platform.
I noramlly only use #idef when the code is only one or two lines long, any longer and I normally refactor into it's only function or class into there own cpp file. That makes it simple to figure out where you are. | Visually marking conditional compilation | [
"",
"c++",
"cross-platform",
"c-preprocessor",
""
] |
I'm finally parsing through wikipedias wiki text. I have the following type of text here:
```
{{Airport-list|the Solomon Islands}}
* '''AGAF''' (AFT) – [[Afutara Airport]] – [[Afutara]]
* '''AGAR''' (RNA) – [[Ulawa Airport]] – [[Arona]], [[Ulawa Island]]
* '''AGAT''' (ATD) – [[Uru Harbour]] – [[Atoifi]], [[Malaita]]
* '''AGBA''' – [[Barakoma Airport]] – [[Barakoma]]
```
I need to retrieve all lines in a single array which start with the pattern
```
* '''
```
I think a regular expression would be called to order here but I'm really messed up on my regular expressions part though.
Plus in another example I have the following text:
```
{{otheruses}}
{{Infobox Settlement
|official_name = Doha
|native_name = {{rtl-lang|ar|الدوحة}} ''ad-Dawḥa''
|image_skyline = Doha Sheraton.jpg
|imagesize =
|image_caption = West Bay at night
|image_map = QA-01.svg
|mapsize = 100px
|map_caption = Location of the municipality of Doha within [[Qatar]].
|pushpin_map =
|pushpin_label_position =
|pushpin_mapsize =
|subdivision_type = [[Countries of the world|Country]]
|subdivision_name = [[Qatar]]
|subdivision_type1 = [[Municipalities of Qatar|Municipality]]
|subdivision_name1 = [[Ad Dawhah]]
|established_title = Established
|established_date = 1850
|area_total_km2 = 132
|area_total_sq_mi = 51
|area_land_km2 =
|area_land_sq_mi =
|area_water_km2 =
|area_water_sq_mi =
|area_water_percent =
|area_urban_km2 =
|area_urban_sq_mi =
|area_metro_km2 =
|area_metro_sq_mi =
|population_as_of = 2004
|population_note =
|population_footnotes = <ref name=poptotal>[http://www.planning.gov.qa/Qatar-Census-2004/Flash/introduction.html Qatar 2004 Census]</ref>
|population_total = 339847
|population_metro = 998651
|population_density_km2 = 2574
|population_density_sq_mi = 6690
|latd=25 |latm=17 | lats=12 |latNS=N
|longd=51|longm=32 | longs=0| longEW=E
|coordinates_display = inline,title
|coordinates_type = type:city_region:QA
|timezone = [[Arab Standard Time|AST]]
|utc_offset = +3
|website =
|footnotes =
}} <!-- Infobox ends -->
'''Doha''' ({{lang-ar|الدوحة}}, ''{{transl|ar|ad-Dawḥa}}'' or ''{{unicode|ad-Dōḥa}}'') is the [[capital city]] of [[Qatar]]. It has a population of 400,051 according to the 2005 census,<ref name="autogenerated1">[http://www.hotelrentalgroup.com/Qatar/Sheraton%20Doha%20Hotel%20&%20Resort.htm Sheraton Doha Hotel & Resort | Hotel discount bookings in Qatar<!-- Bot generated title -->]</ref> and is located in the [[Ad Dawhah]] municipality on the [[Persian Gulf]]. Doha is Qatar's largest city, with over 80% of the nation's population residing in Doha or its surrounding [[suburbs]], and is also the economic center of the country.
It is also the seat of government of Qatar, which is ruled by [[Sheikh Hamad bin Khalifa Al Thani]]–the current ruling Emir of Qatar.
```
I need to extract the infobox here. The infobox is and includes all text between the first occurrence of
```
{{Infobox Settlement
```
and ends with the first occurrence of
```
}} <!-- Infobox ends -->
```
I'm totally lost when it comes to regular expressions and I could use help here. I'm using Php.
---
## EDIT! HELP!
I've been battling for 40 hours and I can't get the stupid regular expression to work right :( so far I just have this:
{{Infobox[^\b(\r|\n)}}(\r|\n)\b]\*[\b(\r|\n)}}(\r|\n)(\r|\n)\b]
But its not working I want it to read all the string data between {{infobox and ends with a \n}}\n
I'm using Php and can't get this to work :( It just returns the first occurrence of }} ignoring the fact that I want it to retrieve }} with preceding linefeed. Help please before I waste more of my sanity on this :'( | > I need to extract the infobox ...
Try this, this time making sure dotall mode is *enabled*:
```
\{\{Infobox.*?(?=\}\} <!-- Infobox ends -->)
```
And again, explanation for that:
```
(?xs) # x=comment mode, s=dotall mode
\{\{ # two opening braces (special char, so needs escaping here.)
Infobox # literal text
.*? # any char (including newlines), non-greedily match zero or more times.
(?= # begin positive lookahead
\}\} # two closing braces
<!-- Infobox ends --> # literal text
) # end positive lookahead
```
This will match upto (but excluding) the the ending expression - you could remove the lookahead itself and include just the contents to have it include the ending, if necessary.
Update, based on comment to answer:
```
\{\{Infobox.*?(?=\n\}\}\n)
```
Same as above, but lookahead looks for two braces on their own line.
To optionally allow the comment also, use:
```
\{\{Infobox.*?(?=\n\}\}(?: <!-- Infobox ends-->)?\n)
``` | [MediaWiki](http://www.mediawiki.org/wiki/MediaWiki) is open-source. Have a look at their [source code](http://svn.wikimedia.org/svnroot/mediawiki/trunk/phase3/) ... ;-) | Need a simple Regular Expressions here | [
"",
"php",
"regex",
"string",
"wiki",
""
] |
What is the difference between `public`, `private`, and `protected` inheritance in C++? | To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".
There are three accessors that I'm aware of: `public`, `protected` and `private`.
Let:
```
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
```
* Everything that is aware of `Base` is also aware that `Base` contains `publicMember`.
* Only the children (and their children) are aware that `Base` contains `protectedMember`.
* No one but `Base` is aware of `privateMember`.
By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
## next:
The same happens with public, private and protected inheritance. Let's consider a class `Base` and a class `Child` that inherits from `Base`.
* If the inheritance is `public`, everything that is aware of `Base` and `Child` is also aware that `Child` inherits from `Base`.
* If the inheritance is `protected`, only `Child`, and its children, are aware that they inherit from `Base`.
* If the inheritance is `private`, no one other than `Child` is aware of the inheritance. | ```
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
```
IMPORTANT NOTE: Classes B, C and D all contain the variables x, y and z. It is just question of access.
About usage of protected and private inheritance you could read [here](https://stackoverflow.com/questions/374399/private-protected-inheritance/374423). | What is the difference between public, private, and protected inheritance? | [
"",
"c++",
"inheritance",
"encapsulation",
"access-specifier",
"c++-faq",
""
] |
I am working on a CRUD application using .NET and I have about 10 or so dialogs I must implement. The user will enter information on one dialog and be sent to another dialog depending on the information being passed. This application basically mirrors what Spring MVC and JSF do when passing information between JSP pages.
Is there a design pattern I can use along with the MVC pattern/architecture that will help me transfer information between dialogs? | Try [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern). If the dependencies between the observers start to be a too big mess, consider switching to [Mediator pattern](http://en.wikipedia.org/wiki/Mediator_pattern). | The [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern) is useful in many of these situations. | What design pattern should I use to pass information between multiple dialogs in a desktop app? | [
"",
"c#",
".net",
"design-patterns",
"desktop",
""
] |
I was writing a python function that looked something like this
```
def foo(some_list):
for i in range(0, len(some_list)):
bar(some_list[i], i)
```
so that it was called with
```
x = [0, 1, 2, 3, ... ]
foo(x)
```
I had assumed that index access of lists was `O(1)`, but was surprised to find that for large lists this was significantly slower than I expected.
My question, then, is how are python lists are implemented, and what is the runtime complexity of the following
* Indexing: `list[x]`
* Popping from the end: `list.pop()`
* Popping from the beginning: `list.pop(0)`
* Extending the list: `list.append(x)`
For extra credit, splicing or arbitrary pops. | there is [a very detailed table on python wiki](http://wiki.python.org/moin/TimeComplexity) which answers your question.
However, in your particular example you should use `enumerate` to get an index of an iterable within a loop. like so:
```
for i, item in enumerate(some_seq):
bar(item, i)
``` | The answer is "undefined". The Python language doesn't define the underlying implementation. Here are some links to a mailing list thread you might be interested in.
* [It is true that Python's lists have
been implemented as contiguous
vectors in the C implementations of
Python so far.](http://mail.python.org/pipermail/python-list/2003-April/199506.html)
* [I'm not saying that the O()
behaviours of these things should be
kept a secret or anything. But you
need to interpret them in the context
of how Python works generally.](http://mail.python.org/pipermail/python-list/2003-April/199585.html)
Also, the more Pythonic way of writing your loop would be this:
```
def foo(some_list):
for item in some_list:
bar(item)
``` | What is the runtime complexity of python list functions? | [
"",
"python",
"complexity-theory",
""
] |
It has worked for over a year and started opening in a new window. I am not aware of anything changing.
I made it following the guide at [Stunnware](http://www.stunnware.com/crm2/topic.aspx?id=AdvancedFind1).
The code in the page is:
```
<html>
<head/>
<body class='stage' onload='resultRender.submit()'>
<FORM id='resultRender' method='post' action='/ALI/AdvancedFind/fetchData.aspx' target='resultFrame'>
<INPUT value='<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="account"><attribute name="websiteurl"/><attribute name="accountnumber"/><attribute name="new_geocat"/><attribute name="new_contracttype"/><attribute name="name"/><attribute name="accountid"/><order attribute="name" descending="false"/><filter type="and"><condition attribute="parentaccountid" operator="null"/><condition attribute="statecode" operator="eq" value="0"/></filter></entity></fetch>' type=hidden name=FetchXml>
<INPUT value='<grid name="resultset" object="1" jump="name" select="1" preview="1" icon="1"><row name="result" id="accountid"><cell name="name" width="200"/><cell name="new_contracttype" width="125"/><cell name="new_geocat" width="100"/><cell name="accountnumber" width="100"/><cell name="websiteurl" width="100"/></row></grid>' type='hidden' name='LayoutXml'>
<INPUT value='account' type='hidden' name='EntityName'>
<INPUT value='{00000000-0000-0000-00AA-000000666000}' type='hidden' name='DefaultAdvFindViewId'>
<INPUT value='{B444C27F-FC37-DD11-BDAA-000C292407C5}' type='hidden' name='ViewId'>
<INPUT value='1039' type='hidden' name='ViewType'>
<INPUT value='name' type='hidden' name='SortCol'>
<INPUT value='false' type='hidden' name='SortDescend'>
</FORM>
</body>
``` | I finally figured it out after trial and error. I added the line below to my HTML page, right after the form.
```
<iframe id='resultFrame' ></iframe>
``` | You also may try:
From the Iframe properties window, make sure that the "restrict cross frame scripting" check box is de-selected.
This solved a problem of mine that was similar to the one above.
thanks, | CRM view in a iframe now opens in a new window, why? | [
"",
"javascript",
"html",
"dynamics-crm",
""
] |
According to [an answer in this thread](https://stackoverflow.com/questions/182534/how-long-does-it-take-to-become-reasonably-proficient-in-orcle-given-sql-server/183657#183657), semicolons are bad and should be avoided. I realized this firsthand after spending hours trying to figure out why my queries were running so terribly slow in SQL Developer. After removing the semicolon from the end of a complex query, it finished in a matter of seconds (compared to me just giving up on it after several minutes, which was the case before removing the semicolon). This behavior startled me, and a Google search didn't turn up much as to when and why I should or should not use semicolons in my SQL statements. Can anyone clear this up with a brief explanation? | It's not the semicolon. Rerunning the same query meant that the rows were already cached, so you got them back much faster. | I am coming from 5+ years of MS SQL Experience and 4+ years of Oracle Development.
I know you will hate a lot of Oracle features, especially in SQL, ;) but take it easy. Oracle is a really powerful DBMS. Even though from lot of perspectives I prefer MSSQL over Oracle but that's a different topic.
As for your issue:
A semicolon is just a statement separator.
SQL developer is using Java and OCI so you might have different issues (I am just guessing something can be wrong).
If you feel something is not running right I advise you to get that query and run it in SQLPLUS instead of Visual Query Tools because it will give you the right feeling.
Good luck with Oracle development.
Visit [SQL\*Plus FAQ](http://www.orafaq.com/wiki/SQL*Plus_FAQ). | Using Semicolons in Oracle SQL Statements | [
"",
"sql",
"performance",
"oracle",
""
] |
I'm looking for the best way to run a java app as a Windows Server 2003 service. What are my options, and what's the basic general process for going about doing this? Thanks much. | One thing you could try is the Tanuki Wrapper:
<http://wrapper.tanukisoftware.org/doc/english/download.jsp>
This software basically wraps up the Java executable into something that can be invoked by the service console. | One option would be to use procrun. The only downside to this method is documentation is kind of slim.
The basic idea is simple. You grab the procrun.exe (which is also the tomcat.exe) available from <http://tomcat.apache.org> and then pass the exe parameters to install the service. The available parameters are listed at <http://commons.apache.org/daemon/procrun.html>
Another option is java service wrapper from: <http://wrapper.tanukisoftware.org/doc/english/download.jsp>, but I haven't had very good luck with it in the past. | How would I run a java process as a Windows Server 2003 service? | [
"",
"java",
"service",
"windows-server-2003",
""
] |
I'm writing a snippet of code to be put on any third party website and have NO idea what environment it will be dropped into. My end goal is for the badge to be
```
<script src="http://example.com/js/badge.js"></script>
```
I would like to use jQuery in my badge code to make my life easier, but I don't want to require another include on the client side (getting anything updated on the client is a pain).
This is the best I could come up with. I don't want anything before or after my script to be affected with any leftover variables or weird collisions. Does anyone see any issues?
```
(function() {
function main($) {
// do stuff with $
$(document.body).css("background", "black")
}
// If jQuery exists, save it
var old_jQuery = null;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery.noConflict(true);
}
}
var addLibs = function() {
// Body isn't loaded yet
if (typeof(document.body) == "undefined" || document.body === null) {
setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.body.appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
setTimeout(checkLibs, 100);
return;
}
var new_jQuery = jQuery.noConflict(true);
jQuery = old_jQuery;
main(new_jQuery);
}
addLibs();
})();
``` | I ended up going with <http://yourock.paulisageek.com/js/popup.js> . See the test (with console logging avialable) <http://paulisageek.com/tmp/jquery-programatically.html>. It doesn't reset jQuery and $ until jQuery actually finishes loading. Any way to block javascript without an infinite loop (which blocks the jQuery loading itself)?
```
// A namespace for all the internal code
var yourock = {};
// Include JQuery programatically
(function() {
// Don't let the script run forever
var attempts = 30;
// If jQuery exists, save it and delete it to know when mine is loaded
var old_jQuery;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery;
delete jQuery;
}
}
var addLibs = function() {
var head = document.getElementsByTagName("head");
if (head.length == 0) {
if (attempts-- > 0) setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head[0].appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
if (attempts-- > 0) setTimeout(checkLibs, 100);
return;
}
yourock.jQuery = jQuery.noConflict(true);
if (typeof old_jQuery == "undefined")
jQuery = old_jQuery;
}
addLibs();
})();
``` | This works:
```
(function(){
if (window.jQuery !== undefined) {
doStuff(jQuery);
} else {
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var interval = setInterval(function(){
if (window.jQuery) {
clearInterval(interval);
var JQ = jQuery.noConflict(true);
doStuff(JQ);
}
}, 100);
}
})();
function doStuff($) { /* Do stuff with $ */ }
``` | Programmatically include JQuery in high conflict environment - | [
"",
"javascript",
"jquery",
"scripting",
"include",
""
] |
> **Possible Duplicates:**
> [Changing c++ output without changing the main() function](https://stackoverflow.com/questions/646169/changing-c-output-without-changing-the-main-function)
> [How to assign a method's output to a textbox value without code behind](https://stackoverflow.com/questions/36028/how-to-assign-a-methods-output-to-a-textbox-value-without-code-behind)
How to write hello world without modifying main function?
Thanks
```
int main(){return 0;}
``` | ```
#include<iostream>
int hello() {
cout<<"Hello World"<<endl;
}
static int foo = hello();
int main(){return 0;}
``` | Just add this code to a .cpp file somewhere.
```
class Hack {
Hack() { cout << "Hello World"; }
} hackInstance;
``` | Weird way to write "hello world" | [
"",
"c++",
""
] |
I'm configuring autocompletion for python and django in vim. One of the problems is that I need to set an environment variable DJANGO\_SETTINGS\_MODULE=myapp.settings. The django tutorial states that
> The value of DJANGO\_SETTINGS\_MODULE
> should be in Python path syntax, e.g.
> mysite.settings. Note that the
> settings module should be on the
> Python import search path.
<http://docs.djangoproject.com/en/dev/topics/settings/>
But if your app isn't in the import search path, how do you make it so that it is? | Three choices.
1. Set `PYTHONPATH` environment variable to include your application's directory. Be sure it has an `__init__.py` file.
2. Create a `.pth` file in site-packages to point to your application's directory.
3. Install your application in site-packages.
These are the three ways of "installing" a Python module. Read about the [site](http://docs.python.org/library/site.html) module for more information. | Try appending the path to sys.path at runtime.
```
import sys
sys.path.append('/path/to/myapp')
``` | django import search path | [
"",
"python",
"django",
""
] |
I need to create a countdown clock, that counts down the days, hours, minutes and seconds that are left to a date of my choice, using jQuery or Google App Engine (Python).
I have created a timer using JavaScript but for that I was using the system time.
I need to use the server time. Can anybody give me ideas to build a count down timer using the server UTC time. | > I created a timer using Javascript,But in that i used system time.
If that JavaScript really serves your needs, then that JavaScript code could easily be made dynamic as well. In the code, wherever the current system time is initialized, simply insert your server time using your language of choice (Python). In other words: use your server language (Python) to output the script just as it is right now, except for replacing the part that initializes the current time.
In PHP, some pseudocode (not sure about the arguments of the Date() constructor) might look like, for example:
```
// my_countdown_script.php
[..]
var startTime = new Date( <?php echo time(); ?> );
[..]
```
Then, rather than including your JavaScript, you would be including the PHP file that inserts the server time like above:
```
<script type="text/javascript" src="my_countdown_script.php"></script>
```
The good thing is: this will work in any browser that supports the JavaScript you already created.
(In some later version, your JavaScript could include some initializers that allow you to set the current time after including the library in your HTML. That would allow the actual JavaScript library to be static, and thus to be cached by the browser.) | a good jquery plugin can be found here <http://keith-wood.name/countdown.html>
all you need to do then is pass in your new date from your scripting language php/asp.net by setting a variable on the page before the initialisation and updating the \_calculatePeriods function to take that variable instead of the now one.
```
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery.countdown.js"></script>
<script type="text/javascript">
$(function () {
var servernow = new Date( <?php echo time(); ?> );
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26);
$('#defaultCountdown').countdown({until: austDay});
$('#year').text(austDay.getFullYear());
});
</script>
```
from js/jquery.countdown.js
```
* Calculate the requested periods between now and the target time.
@param inst (object) the current settings for this instance
@param show (string[7]) flags indicating which periods are requested/required
@param now (Date) the current date and time
@return (number[7]) the current time periods (always positive)
by year, month, week, day, hour, minute, second */
_calculatePeriods: function(inst, show, now) {
// Find endpoints
inst._now = servernow;
```
Josh | Countdown timer using jQuery or Google App Engine? | [
"",
"javascript",
"jquery",
"google-app-engine",
""
] |
I'd like to know what are the experiences with G1 garbage collector in newest JDK? I see `NullPointerException` thrown in my program, although code didn't change and behave correctly in earlier JDKs. | I've been running jEdit using:
```
-Xmx192M -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC
```
for the last couple of days on windows. Haven't experienced anything going wrong or misbehaving.
I also tried running Intellij using the G1 GC, it didn't fair so well. It lasted a couple of hours before crashing in a big pile of mess, a bit optimistic maybe. | A garbage collector will only impact the *performance* of your application, not its *correctness*. I've been using it for Eclipse, just for fun, and seemed stable.
I would look elsewhere for the source of the exceptions. | Experience with JDK 1.6.x G1 ("Garbage First") | [
"",
"java",
"nullpointerexception",
"garbage-collection",
"java-6",
"g1gc",
""
] |
I'm working on a simple Java application. Currently, I have two view, one for login in and another once you're logged in.
So my question is, once the user has logged in, should the controller of the login view creates the second view?
The problem is, the first controller needs to know every dependencies of the second view...
Edit : this is **not** a web application. | If your object needs to instantiate a class, but you don't want it to depend on the details of instantiating the class, inject a factory (as [you've suggested](https://stackoverflow.com/questions/933065/does-a-controller-create-new-views/933116#933116)).
I like to use interfaces so I can plug in different implementations of my dependencies. Here's an example:
```
public class RealLoginController implements LoginController {
private LoginViewFactory viewFactory;
public LoginController(LoginViewFactory viewFactory) {
this.viewFactory = viewFactory;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) {
if (isLoggedIn()) {
return viewFactory.createLoggedInView();
} else {
return viewFactory.createLoggedOutView();
}
}
// ...
}
public class RealLoggedInView implements LoginView {
// Implementation for rendering stuff
}
public class RealLoggedOutView implements LoginView {
// Implementation for rendering stuff
}
public interface LoginViewFactory {
public LoginView createLoggedInView();
public LoginView createLoggedInView();
}
public class RealLoginViewFactory implements LoginViewFactory {
private FooModel fooEngine;
private BarConfig barConfig;
public RealLoginViewFactory(FooModel fooLayer, BarConfig barConfig) {
this.fooEngine = fooEngine;
this.barConfig = barConfig;
}
public LoginView createLoggedInView() {
if (fooEngine.hasBaz()) {
return new RealLoginView(barCongig.getQux());
} else {
return new RealLoginView(barCongig.getQux(),
fooEngine.getBaz());
}
}
public LoginView createLoggedOutView() {
// ...
}
}
public class RealLoginController implements LoginController {
private LoginViewFactory viewFactory;
public LoginController(LoginViewFactory viewFactory) {
this.viewFactory = viewFactory;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) {
if (isLoggedIn()) {
return viewFactory.createLoggedInView();
} else {
return viewFactory.createLoggedOutView();
}
}
// ...
}
```
You can then use the controller with any views you like:
```
public class LoginControllerTest {
public void testSomething() {
// ...
controller = new RealLoginController(fakeViewFactory);
assertHasTag("td#row1", controller.getRenderedStuff());
// ...
}
}
```
You may be able to avoid the problem (as [bpappa suggests](https://stackoverflow.com/questions/933065/does-a-controller-create-new-views/933110#933110)) if you don't need complex instantiation logic and your framework knows how to get dependencies for you by name. | I dont think the LoginController should create the SecondView at all. Once the user has logged in the LoginController should fire off an event that login was successful and any Controller that cares about that should take the appropriate action.
If you are using DI you ideally want to inject the View into a Controller.
Not quite sure what you mean with your last statement though so leaving that unanswered. | Does a controller create new views? | [
"",
"java",
"model-view-controller",
"dependency-injection",
"dependencies",
""
] |
Can someone give me an example of creating a custom set of an Event and a Handler.
Say you have a Person object that you want your widgets to know if it got updated.
You create a HandlerManager and now you have to create an Event and a Handler.
How would you define those classes so that you can subscribe and fire events?
Most of the Events are DOM based, while I want to create some custom events and handlers that I can fire outside of any browser-based event. | Here's a pretty comprehensive example of creating a custom event, taken verbatim from the [GwtEventSystem Wiki](http://code.google.com/p/google-web-toolkit-incubator/wiki/GwtEventSystem) (when the event system was still in GWT's incubator).
This is an event that is triggered when the user becomes happy.
Define a new event class. You can add arbitrary metadata in the event class. For simplicity, we will not include any here though.
```
public class HappyEvent extends GwtEvent {
...
}
```
Define a new handler and marker interface for the event class.
```
interface HappyHandler extends EventHandler {
public void onHappiness(HappyEvent event);
}
interface HasHappyEvents {
public HandlerRegistration addHappyHandler(HappyHandler handler);
}
```
Add a unique event type
```
class HappyEvent extends AbstractEvent{
public static AbstractEvent.Key KEY = new AbstractEvent.Key(){...}
public GwtEvent.Key getKey(){
return KEY;
}
...
}
```
Wire up the handler's fire method
```
class HappyEvent extends GwtEvent {
static Key<HappyEvent,HappyHandler> KEY = new Key<HappyEvent,HappyHandler>(){
protected void fire(HappyHandler handler, HappyEvent event) {
handler.onHappiness(event);
};
...
}
``` | Thanks for all the responses. Zakness came the closest to giving me the answer I needed, however, I came up with a slightly simpler model.
My main goal was to avoid using a static variable to my main data structure. I also hit the problem of trying to figure out if that main data structure was successfully retrieved from the database at the time of trying to access it and what to do when it's not (i.e. when it's null).
After watching the [Google Web Toolkit Architecture: Best Practices For Architecting Your GWT App](http://code.google.com/events/io/sessions/GoogleWebToolkitBestPractices.html) video from Google IO, the Event Bus idea seemed perfect.
I'll post my solution here in case it helps anyone else out.
---
First, create the Handler class. Note the reference to the Event class already:
```
public interface CategoryChangeHandler extends EventHandler {
void onCategoryChange(CategoryChangeEvent event);
}
```
Now on to the Event class. This gave me the most trouble:
```
public class CategoryChangeEvent extends GwtEvent<CategoryChangeHandler> {
private final List<Category> category;
public CategoryChangeEvent(List<Category> category) {
super();
this.category = category;
}
public static final Type<CategoryChangeHandler> TYPE = new Type<CategoryChangeHandler>();
@Override
protected void dispatch(CategoryChangeHandler handler) {
handler.onCategoryChange(this);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CategoryChangeHandler> getAssociatedType() {
return TYPE;
}
public List<Category> getCategories(){
return category;
}
}
```
Now I am able to use these Handler and Event classes like so when this main data structure gets reloaded:
This code got the data structure and want to notify everyone who is listening that it got updated:
```
CategoryChangeEvent event = new CategoryChangeEvent(result);
eventBus.fireEvent(event);
```
This code is an implementation of the Event
```
public class PopulateCategoryHandler implements CategoryChangeHandler {
@Override
public void onCategoryChange(CategoryChangeEvent event) {
tearDownCategories();
List<Category> categories = event.getCategories();
populateCategories(categories);
}
}
``` | GWT Custom Event Handler | [
"",
"java",
"events",
"gwt",
"dom-events",
""
] |
Simple example of a nested function:
```
def maker(N):
def action(X):
return X * N
return action
```
Do factory functions have advantages over creating a class? Performance, memory, clean up? | What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:
```
class clsmaker(object):
def __init__(self, N):
self.N = N
def __call__(self, X):
return X * self.N
```
That doesn't seem so bad until you start adding more arguments to the constructor. Then doing it the class way takes an extra line for each argument, while the function just gets the extra args.
It turns out that there is a speed advantage to the nested functions as well:
```
>>> T1 = timeit.Timer('maker(3)(4)', 'from __main__ import maker')
>>> T1.timeit()
1.2818338871002197
>>> T2 = timeit.Timer('clsmaker(3)(4)', 'from __main__ import clsmaker')
>>> T2.timeit()
2.2137160301208496
```
This may be due to there being fewer opcodes involved in the nested functions version:
```
>>> dis(clsmaker.__call__)
5 0 LOAD_FAST 1 (X)
3 LOAD_FAST 0 (self)
6 LOAD_ATTR 0 (N)
9 BINARY_MULTIPLY
10 RETURN_VALUE
>>> act = maker(3)
>>> dis(act)
3 0 LOAD_FAST 0 (X)
3 LOAD_DEREF 0 (N)
6 BINARY_MULTIPLY
7 RETURN_VALUE
``` | Comparing a function factory to a class is comparing apples and oranges. Use a class if you have a cohesive collection of data and functions, together called an object. Use a function factory if you need a function, and want to parameterize its creation.
Your choice of the two techniques should depend on the meaning of the code. | python factory functions compared to class | [
"",
"python",
"function",
""
] |
I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.
One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.
If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.
My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. | It's not that hard to set up a Python environment, and I've never had it muck up my .NET work. Basically, install Python --- I'd use 2.6 rather than 3.0, which is not yet broadly accepted --- and add it to your PATH, and you're ready to go with the language. I wouldn't recommend using a Ubuntu VM as your development environment; if you're working on Windows, you might as well develop on Windows, and I've had no significant problems doing so. I go back and forth from Windows to Linux with no trouble.
If you have an editor that you're comfortable with that has basic support for Python, I'd stick with it. If not, I've found [Geany](http://www.geany.org) to be a nice, light, easy-to-use editor with good Python support, though I use [Emacs](http://www.gnu.org/software/emacs/) myself because I know it; other people like [SCITE](http://www.scintilla.org/SciTE.html), [NotePad++](http://notepad-plus.sourceforge.net/), or any of a slew of others. I'd avoid fancy IDEs for Python, because they don't match the character of the language, and I wouldn't bother with IDLE (included with Python), because it's a royal pain to use.
Suggestions for libraries and frameworks:
* [Django](http://www.djangoproject.org) is the *standard* web framework, but it's big and you have to work django's way; I prefer [CherryPy](http://www.cherrypy.org/), which is also actively supported, but is light, gives you great freedom, and contains a nice, solid webserver that can be replaced easily with httpd.
* Django includes its own ORM, which is nice enough; there's a standalone one for Python, though, which is even nicer: [SQL Alchemy](http://www.sqlalchemy.org)
* As far as a testing library goes, [pyunit](http://pyunit.sourceforge.net) seems to me to be the obvious choice
Good luck, and welcome to a really fun language!
EDIT summary: I originally recommended [Karrigell](http://karrigell.sourceforge.net), but can't any more: since the 3.0 release, it's been continuously broken, and the community is not large enough to solve the problems. [CherryPy](http://www.cherrypy.org/) is a good substitute if you like a light, simple framework that doesn't get in your way, so I've changed the above to suggest it instead. | You should install python 2.4, python 2.5, python 2.6 and python 3.0, and add to your path the one you use more often (Add c:\Pythonxx\ and c:\Pythonxx\Scripts).
For every python 2.x, install easy\_install; Download [ez\_setup.py](http://peak.telecommunity.com/dist/ez_setup.py) and then from the cmd:
```
c:\Python2x\python.exe x:\path\to\ez_setup.py
c:\Python2x\Scripts\easy_install virtualenv
```
Then each time you start a new project create a new virtual environment to isolate the specific package you needs for your project:
```
mkdir <project name>
cd <project name>
c:\Python2x\Scripts\virtualenv --no-site-packages .\v
```
It creates a copy of python and its libraries in .v\Scripts and .\v\Lib. Every third party packages you install in that environment will be put into .\v\Lib\site-packages. The -no-site-packages don't give access to the global site package, so you can be sure all your dependencies are in .\v\Lib\site-packages.
To activate the virtual environment:
```
.\v\Scripts\activate
```
For the frameworks, there are many. Django is great and very well documented but you should probably look at Pylons first for its documentions on unicode, packaging, deployment and testing, and for its better WSGI support.
For the IDE, Python comes with IDLE which is enough for learning, however you might want to look at Eclipse+PyDev, Komodo or Wingware Python IDE. Netbean 6.5 has beta support for python that looks promising (See [top 5 python IDE](http://www.ninjacipher.com/2009/05/01/top-5-django-ides/)).
For the webserver, you don't need any; Python has its own and all web framework come with their own. You might want to install MySql or ProgreSql; it's often better to develop on the same DB you will use for production.
Also, when you have learnt Python, look at [Foundations of Agile Python Development](http://www.apress.com/book/view/9781590599815) or [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book). | I need a beginners guide to setting up windows for python development | [
"",
"python",
"windows",
"development-environment",
""
] |
I have a query. I am developing a site that has a search engine. The search engine is the main function. It is a business directory site.
A present I have basic search sql that searches the database using the "LIKE" keyword.
My client has asked me to change the search function so instead of using the "Like" keyword they are after something along the lines of the "Startswith" keyword.
To clarify this need here is an example.
If somebody types "plu" for plumbers in the textbox it currently returns, e.g.,
1. CENTRE STATE PLUMBING & ROOFING
2. PLUMBING UNLIMITED
The client only wants to return the "PLUMBING UNLIMITED" because it startswith "plu", and doesn't "contain" "plu"
I know this is a weird and maybe silly request, however does anyone have any example SQL code to point me in the right direction on how to achieve this goal.
Any help would be greatly appreciated, thanks... | Instead of:
```
select * from professions where name like '%plu%'
```
, use a where clause without the leading %:
```
select * from professions where name like 'plu%'
``` | how about this:
`SELECT * FROM MyTable WHERE MyColumn LIKE 'PLU%'`
please note that the % sign is only on the right side of the string
example in MS SQL | Performing an ASP.NET database search with StartsWith keyword | [
"",
"sql",
"sql-like",
""
] |
I'm trying to design a code where one guess a number. I defined the range which number to display in my listbox. I started to write Random(1,10) but if I enter 11, it still writes in my listbox. How can I just write the number selected from my range, which is 1-10?
Here is a part of my code:
```
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber = RandomNumber(1, 10);
int.TryParse(textBox1.Text, out returnNumber);
listBox1.Items.Add(returnNumber);
}
```
## Additional question
If I would like to display a range of number like for example 1-10, how could I do the following? The user will type 11 the program will not accept that.
I made something like this:
```
int returnNumber = RandomNumber(1, 10);
string yourNumber;
yourNumber = textBox1.Text.Trim();
if(Int32.TryParse(textBox1.Text>=1)) && (Int32.TryParse(textBox1.Text<=10));
{
listBox1.Items.Add(yourNumber);
textBox1.Text = string.Empty;
}
```
Something is wrong in the program.
## Update
For Nathaniel, I tried this one:
```
int returnNumber=RandomNumber(1,10);
int counter=1;
int yourNumber;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber >=1 && yourNumber <= 10)
{
listBox1.Items.Add(yourNumber);
}
else
{
MessageBox.Show("Please enter a number between 1-10");
}
```
What I would like to do is design a program for guessing a number. So this is the first part.
## Update
Here is my final code, can it be improved? I think the next thing I'll do is to limit the times the user types the input. That means, they can only guess the right number 3 times or 5 times. Not sure where to implement it
```
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
if(yourNumber==randomNumber)
{
listBox2.Items.Add("You guessed the Magic Number!");
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
}
}
``` | Some minor changes to your code, condensing a couple lines and adding the limit code, utilizing the list of guesses as the counter:
```
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
private const int maxGuesses = 5;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
if (Int32.TryParse(textBox1.Text.Trim(), out yourNumber) &&
yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
else if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
else
{
listBox2.Items.Add("You guessed the Magic Number!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
//Will stop on the 5th guess, but guards the case that there were more than 5 guesses
if(listBox1.Items.Count >= maxGuesses && yourNumber != randomNumber)
{
listBox2.Items.Add("You are out of guesses!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
textBox1.Enabled = true;
btnOk.Enable = true;
}
}
}
```
Editted to prevent the "You're out of guesses" message when the number is correctly guessed on the last guess. | The line:
```
int returnNunmber = RandomNumber(1, 10);
```
does nothing, because in the next line returnNumber is used as an output variable and will be whatever number is in textBox1. Remove the
```
int.TryParse(textBox1.Text, out returnNumber);
```
line and it will add a random number from 1 to 10 to your listbox.
EDIT::::
To answer you additional question, try:
```
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber;
int.TryParse(textBox1.Text, out returnNumber);
if( returnNumber < 1 || returnNumber > 10) {
returnNumber = RandomNumber(1, 10);
}
listBox1.Items.Add(returnNumber);
}
``` | Displaying random numbers in C# | [
"",
"c#",
"random",
""
] |
I have a form that can open a sub form (with `ShowDialog`). I want to make sure that the sub form is being disposed properly when the main form is done.
I tried adding the subform to the `components` member of the main form, but at the moment I got a `ArgumentNullException`.
I know I can just instantiate the `components` myself, but isn't that a bit dangerous? One day I'll add a component in the designer view, and that will generate the `new Container()` line in the designer.cs file, and I'll never know I have two component instanses running around the heap.
Is there an easier way to make sure the sub form is being disposed?
EDIT - moved my solution to an answer | My current workaround:
I've added the Components property to the form, and am using it to access the collection
```
private IContainer Components{ get { return components ?? (components = new Container());}}
``` | If you're using the form in showdialog, one could assume that after you've received the result you could dispose the form there?
```
using(MyDialog dlg = new MyDialog())
{
result = dlg.ShowDialog();
}
``` | WinForm disposing a sub form when the form is disposed | [
"",
"c#",
"winforms",
"dispose",
""
] |
I'm trying to save a copied image from the clipboard but it's losing its alpha channel:
```
Image clipboardImage = Clipboard.GetImage();
string imagePath = Path.GetTempFileName();
clipboardImage.Save(imagePath);
```
If I copy a 32bit image from PhotoShop or IE/Firefox/Chrome and run the above code, the output loses its alpha channel, instead it is saved against a black background.
The image is saved as PNG, which can contain an alpha channel.
The correct data appears to be in the clipboard because pasting into other applications (such as PhotoShop) retains the alpha channel.
Can anyone put me out of my misery?
Thanks in advance!
**Update:**
```
// outputs FALSE
Debug.WriteLine(Image.IsAlphaPixelFormat(Clipboard.GetImage().PixelFormat));
```
The above suggests that the alpha data is lost as soon as it's taken out of the clipboard. Perhaps I need to get it out of the clipboard some other way? | Instead of calling `Clipboard.GetImage()`, try calling `Clipboard.GetDataObject()`
This returns an IDataObject, which you can in turn query by calling `dataObject.GetFormats()`. `GetFormats()` returns the type formats supported by the Clipboard object - there may be a more precise format supported that you can use to extract the data. | It might be like [this article](http://msdn.microsoft.com/en-us/magazine/cc164091.aspx) suggests, that the Clipboard object, working within Win32, is only able to manage bitmaps, which don't feature the transparent/partially transparent alpha channel. The OLE clipboard is more capable, it seems:
* [Intro](http://www.interviewup.com/view/What-is-OLE--How-do-you-handle-drag-and-drop-in-OLE-.aspx)
* [Vague support article](http://support.microsoft.com/kb/83659)
* [A bit of discussion about the Win32 clipboard](http://msdn.microsoft.com/en-us/magazine/cc164091.aspx)
However, the [netez](http://netez.com/2xExplorer/shellFAQ/adv_clip.html) was the best article I found on the topic.
(beware I haven't tested this myself) | How can I get an image out of the clipboard without losing the alpha channel in .NET? | [
"",
"c#",
".net",
"image",
"png",
"clipboard",
""
] |
I have two classes (A and B) which depend on each other in following sense:
Each class has a method performing some action.
The action of each class depends on an action of the other class.
So, if the user calls action of class A, it should automatically call
action of class B.
Same for the other way. But an infinite loop should be prevented.
I have found some code, which deals with this issue, but it seems to be a
little dumb to me: Infinite loop is prevented by **locking**.
```
import java.util.concurrent.locks.*;
import static java.lang.System.*;
import org.junit.*;
public class TEST_DependentActions {
static class A {
private B b = null;
private final ReentrantLock actionOnBLock = new ReentrantLock();
public void setB(B b) {
this.b = b;
}
public void actionOnB() {
if (!actionOnBLock.isLocked()) {
actionOnBLock.lock();
b.actionOnA();
actionOnBLock.unlock();
}
}
}
static class B {
private A a = null;
private final ReentrantLock actionOnALock = new ReentrantLock();
public void setA(A a) {
this.a = a;
}
public void actionOnA() {
if (!actionOnALock.isLocked()) {
actionOnALock.lock();
a.actionOnB();
actionOnALock.unlock();
}
}
}
@Test
public void test1()
throws Exception {
out.println("acting on class A first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
a.actionOnB();
}
@Test
public void test2()
throws Exception {
out.println("acting on class B first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
b.actionOnA();
}
}
```
Output is as following:
```
acting on class A first:
A : calling class B's action.
B : calling class A's action.
acting on class B first:
B : calling class A's action.
A : calling class B's action.
```
Well, it works, but doesn't seem to be an optimal solution.
How would **you** do it?
Is there a **pattern** which deal with such issue?
**EDIT:**
*I want to know it in general.
But let's say I have a **Container** which contains multiple **Element**s.
The Container provides the method **remove(someElement)** and the
Element also provides a method **removeMe()**.
Both methods depend on each other, but **can't** be connected to one
method, because both methods additionally perform **some internal stuff**, which is only
accessible **inside** each class.* | Can you make one of the methods private/internal.
This should ensure only the other one can be called by client code, and you always know which way the calls work.
Alternatively, using your container/element example, something like this:
```
public class Container
{
public void Remove(Element e)
{
e.RemoveImplementation();
RemoveImplementation();
}
// Not directly callable by client code, but callable
// from Element class in the same package
protected void RemoveImplementation()
{
// Mess with internals of this class here
}
}
public class Element
{
private Container container;
public void Remove()
{
RemoveImplementation();
container.RemoveImplementation();
}
// Not directly callable by client code, but callable
// from Container class in the same package
protected void RemoveImplementation()
{
// Mess with internals of this class here.
}
}
```
I'm not sure if there is a common name for this pattern. | I would handle this by rethinking the logic. Circular dependencies are typically a sign that something is a little ... off. Without more insight into the exact problem I can't be more specific. | For two methods who need to call each other: how do I prevent an infinite loop? | [
"",
"java",
"design-patterns",
""
] |
I need to serialize a java object which might change later on, like some of the variables can be added or removed. What are the pit falls of such an approach and What precautions should I take, if this remains the only way out. | * You definitely need to add a [serialVersionUID](http://www.javapractices.com/topic/TopicAction.do?Id=45) field right from the beginning.
* Changes might make the serialized objects [incompatible](http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678). Adding and removing fields can cause the violation of class contracts (up to the point of Exceptions being thrown) when deserializing instances where the field was not present in a class version that expects it to be - the field is set to the type's default value in that case; the most likely problems are `NullPointerException`s. This can be averted by implementing [readObject() and writeObject()](http://java.sun.com/javase/6/docs/api/java/io/Serializable.html). Other changes (such as changing a field's type) can cause the deserialization to fail entirely. | As Michael pointed out Java provides some support for serialization with java.io.Serializable. The main problem with the Java support is that versioning is clunky and requires to user to deal with it.
Instead I would recommend something like Googles Protocol Buffers or Apache Thrift. For both you define the object in a very simple language and then they will generate the serialization code for you. Both also handle all the versioning for you such that you don't have to worry about if you are reading an old or a new version of the object.
For example if you have a type foo() which has a field bar and you write a bunch of foo objects to disk. Then some time later you add a field baz to foo and write a few more foo objects to disk. When you read them back they will all be foo objects, it will seem as if all of the original foo objects simply never set their baz field. | serializing a java object which might change later on | [
"",
"java",
"serialization",
""
] |
I have received the task to make a [social graph](http://en.wikipedia.org/wiki/Social_network), where, with one user in the [center](http://en.wikipedia.org/wiki/Centrality), it shows the connections he has.
But before we can reach that, our focus is how we can determine the [shortest path](http://en.wikipedia.org/wiki/Shortest_path_problem) between 2 users.
I found some algorithm to do it, but it seems that it takes a lot of time, and because it's about social links, we are looking for one that is the fastest because we will need to run it on a regular basis to keep up with the updates in friends.
So, do you know which would be the fastest way to determine the shortest path between two users?
PS: If you know an example in PHP & MySQL, I will give you a virtual beer (or coke). :D | [Dijkstra's Algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) finds the shortest path between two nodes on a graph. | what you want is an [all-pairs shortest path](http://en.wikipedia.org/wiki/All_pairs_shortest_path) algorithm; if you have to generate the pairs globally for the graph it is quicker than running a shortest path algorithm for every pair. keeping this updated is another problem - note that you'll have to do it every time you add a connection to the graph, not just every time you add a person. if this is for a production site, it might be worth maintaining the graph generation as an offline task written in a language faster than php, and writing its results back to the db. you'll probably find existing c++ implementations out there. | Asking for Social network analysis (SNA) algorithm | [
"",
"php",
"algorithm",
"graph",
"social-networking",
""
] |
When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.
Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.
One possibility is the trick with the static function member:
```
Type& globalObject()
{
static Type theOneAndOnlyInstance;
return theOneAndOnlyInstance;
}
```
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
**Update:** Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it... | You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from <https://isocpp.org/wiki/faq/ctors#static-init-order> | Maybe you should reconsider whether you need so many global static variables. While they can sometimes be useful, often it's much simpler to refactor them to a smaller local scope, especially if you find that some static variables depend on others.
But you're right, there's no way to ensure a particular order of initialization, and so if your heart is set on it, keeping the initialization in a function, like you mentioned, is probably the simplest way. | C++ static initialization order | [
"",
"c++",
"static-variables",
"static-order-fiasco",
"initialization-order",
""
] |
I have a stored procedure like this:
```
CREATE PROCEDURE up_action
(@id int
,@group varchar(30)=''
,@nom varchar(30)=''
,@compte varchar(30)=NULL
)
AS
BEGIN
DECLARE @chrono int
......
select @date=date from users where compte=@compte
INSERT INTO dialog
(numappel,auteur,commentaire,etape,etapews,operant)
VALUES
(@numappel,@nomprenom,@dialogue,14,14,@nomoperateur)
SET @chrono = SCOPE_IDENTITY()
select 'chrono'=@chrono
END
```
I want to call this stored procedure from an application written in C# with the possibility to give the parameters separated by , (actually their values) and after that to receive eventually a record set rs from which I can get the value of the variable like rs("chrono").
I know the possibility with creating every parameter and telling the type, the name, the value etc.
But I want a method like in ASP because I have procedures with 100 parameters ... | So..the solution is:
```
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandText = strQuery;
rdr = sqlCommand.ExecuteReader();
rdr.Read();
int chrono = Convert.ToInt32(rdr["chrono"])
```
And for 2 parameters
```
rdr.NextResult();
rdr.Read();
int str = Convert.ToInt32(rdr["str"]);
```
Thank you all for your answers | Normally, with POADO (Plain Old ADO.Net) you would do something like this:
```
using (SqlConnection conn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "up_action"
cmd.Parameters.AddWithValue("@group", group);
cmd.Parameters.AddWithValue("@nom", nom);
cmd.Parameters.AddWithValue("@compte", compte);
conn.Open();
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
chrono = rs["chrono"];
}
}
}
```
But as Richard pointed out: you indeed better look into something like LINQ to SQL, as this wil generate a method for each stored procedure (which automatically has an argument per parameter of your stored procedure). See [this link](http://msdn.microsoft.com/en-us/library/bb399357.aspx) for more information. | Call a stored procedure from .net | [
"",
"c#",
".net",
"sql-server",
"sql-server-2005",
"ado.net",
""
] |
Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands via USB to another system (via a C++ library with SWIG) and once the other system has completed the task, it returns an "OK" value. I have reproduced the problem in the following example. How can I make "tic" and "toc" print one after the other without any delay? I suppose the solution involves threads, but I am not too familiar with them. Can anyone show me a simple way to solve this problem?
```
from math import sqrt
from time import sleep
def longcalc():
total = 1e6
for i in range(total):
r = sqrt(i)
return r
def longtime():
#Do stuff here
sleep(1)
return "sleep done"
print "tic"
longcalc()
print "toc"
longtime()
print "tic"
``` | Unless the SWIGged C++ code is specifically set up to release the GIL (Global Interpreter Lock) before long delays and re-acquire it before getting back to Python, multi-threading might not prove very useful in practice. You could try [multiprocessing](http://docs.python.org/library/multiprocessing.html) instead:
```
from multiprocessing import Process
if __name__ == '__main__':
print "tic"
Process(target=longcalc).start()
print "toc"
Process(target=longtime).start()
print "tic"
```
multiprocessing is in the standard library in Python 2.6 and later, but can be separately [downloaded](http://code.google.com/p/python-multiprocessing/) and installed for versions 2.5 and 2.4.
Edit: the asker is of course trying to do something more complicated than this, and in a comment explains:
"""I get a bunch of errors ending with: `"pickle.PicklingError: Can't pickle <type 'PySwigObject'>: it's not found as __builtin__.PySwigObject"`. Can this be solved without reorganizing all my code? Process was called from inside a method bound to a button to my wxPython interface."""
`multiprocessing` does need to pickle objects to cross process boundaries; not sure what SWIGged object exactly is involved here, but, unless you can find a way to serialize and deserialize it, and register that with the `copy_reg module`, you need to avoid passing it across the boundary (make SWIGged objects owned and used by a single process, don't have them as module-global objects particularly in `__main__`, communicate among processes with Queue.Queue through objects that don't contain SWIGged objects, etc).
The *early* errors (if different than the one you report "ending with") might actually be more significant, but I can't guess without seeing them. | ```
from threading import Thread
# ... your code
calcthread = Thread(target=longcalc)
timethread = Thread(target=longtime)
print "tic"
calcthread.start()
print "toc"
timethread.start()
print "tic"
```
Have a look at the [python `threading` docs](http://docs.python.org/library/threading.html) for more information about multithreading in python.
A word of warning about multithreading: it can be hard. **Very** hard. Debugging multithreaded software can lead to some of the worst experiences you will ever have as a software developer.
So before you delve into the world of potential deadlocks and race conditions, be absolutely sure that it makes sense to convert your synchronous USB interactions into ansynchronous ones. Specifically, ensure that any code dependent upon the async code is executed after it has been completed (via a [callback method](http://en.wikipedia.org/wiki/Callback_(computer_science)) or something similar). | Make my code handle in the background function calls that take a long time to finish | [
"",
"python",
"multithreading",
""
] |
This is a very trivial problem but I can't seem to find a way of solving it. It's annoying me because I feel I should know the answer to this, but I'm either searching for the wrong terms or looking at the wrong methods and properties.
I have a configuration dialog that's called from two places.
The first is from the button on the form which is working correctly - as you'd expect.
The second is from a context menu on the notifyIcon in the system tray, but here it appears at the top left of the screen. Ideally I'd like it to appear centered on the primary screen, or perhaps close to the system tray.
* I've tried setting the `Location`, but this appears to be overridden when `dialog.ShowDialog()` is called.
* I've tried using the `dialog.ShowDialog(IWin32Window)` overload, but that didn't seem to like me passing `null` as the window handle.
* I've tried using `dialog.Show()` instead, but (and this is where I could be going wrong) setting the location doesn't appear to give consistent results.
* I've even tried setting the `dialog.Parent` property - which of course raised an exception.
I just know that I'm going to realise that the answer is obvious when I (hopefully) see some answers, but at the moment I'm completely stuck.
*Thanks for the answers - as I suspected it was obvious, but as usual I'd got myself stuck into looking down the wrong route. The even more annoying thing is that I've used this property from the designer too.* | You can set the [`Form.StartPosition`](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition.aspx) property to `FormStartPosition.Manual` and then set the [`Form.Location`](https://msdn.microsoft.com/en-us/library/ms159414.aspx) property to your desired location. When you call `ShowDialog` the form should show up in the desired location.
```
MyForm frm = new MyForm();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(10, 10);
frm.ShowDialog();
``` | I assume you're using a Form, in which case you can use Form.StartPosition enumeration. You can find more about it [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition.aspx) and the enumeration behavior [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.formstartposition.aspx). | How can I control the location of a dialog when using ShowDialog to display it? | [
"",
"c#",
"winforms",
"dialog",
""
] |
How would you store a PDF document in a field in MySQL?
Currently I have a list of customers and each customer has a certificate with information about their account that they can give to other companies to prove that they're our customer. Currently their certificate is exported as a PDF and e-mailed to someone here at work (the customer gets a physical copy as well), and that person's mailbox is filled with these e-mails. I'd much prefer to just have it in the customer's record - allowing it to be accessed via the customer's file in our in-house CRM.
I considered putting the PDFs in a folder and storing their location as a `varchar` in the customer's record, but if the PDFs get moved/deleted/etc. then we're up a creek.
My understanding is that a `BLOB` or `MEDIUMBLOB` is the type of field that I'd use to store it, but I'm a little ignorant in this regard. I'm not sure how to store something like that in the field (what C# datatype to give it), and then how to get it and open it via a PDF reader. | Put it in the database, but the `BLOB` datatype probably won't cut it. The `MEDIUMBLOB` is normally sufficient.
[MySQL Datatypes](http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html)
```
BLOB, TEXT L + 2 bytes, where L < 216
MEDIUMBLOB, MEDIUMTEXT L + 3 bytes, where L < 224
LONGBLOB, LONGTEXT L + 4 bytes, where L < 232
```
I've used this several times with very good results. Be sure to save the filesize too, as it makes it easier to retrieve it. Not sure if it applies to C# as it does to PHP.
If using prepared statements with parameters the data will automatically be escaped AFAIK.
Also I can see no real reason as to why the database itself would get slow when storing this type of data in it. The main bottleneck will of course be the transfer of the data. Also MySQL is sometimes restrictive about the maximum length of queries and the responses in particular.
Once you have it running, it's pretty neat, especially when dealing with lots of small files. For a small number of large files, this approach does not make sense, better use some backup system to deal with moved/deleted files. | <http://www.phpriot.com/articles/images-in-mysql> is a good tutorial with some background information, and an implementation of storing images in MySQL | Store a PDF file in MySQL | [
"",
"c#",
"mysql",
"pdf",
"blob",
""
] |
I know that logically, there are some cases where NULL values make sense in a DB schema, for example if some values plain haven't been specified. That said, working around DBNull in code tends to be a royal pain. For example, if I'm rendering a view, and I want to see a string, I would expect no value to be a blank string, not "Null", and I hate having to code around that scenario.
Additionally, it makes querying easier. Admittedly, you can do "foo is not null" very easily, but for junior SQL devs, it's counter intuitive to not be able to use "foo != null" (and yes, I know about options to turn off ANSI nulls, etc, but that's definitely NOT simpler, and I don't like working away from the standard).
What good reason is there for having/allowing nulls in a database schema? | The most significant reason for allowing NULLS is that there is no reasonable alternative. Logically, a NULL value represents "undefined". For lack of NULLS, you'll end up trying to specify a "dummy" value wherever the result is undefined, and then you'll have to account for said "dummy" value in ALL of your application logic.
I wrote a blog article on the reasons for including NULL values in your database. You can find it [here](http://thehobt.blogspot.com/2009/03/sql-server-and-null-values-revisited.html). In short, I DO believe that NULL values are an integral part of database design, and should be used *where appropriate*. | C.J. Date in his book "SQL and Relational Theory" (2009: O'Reilly; ISBN 978-0-596-52306-0) takes a very strong stand against NULLs. He demonstrates that the presence of NULLs in SQL gives wrong answers to certain queries. (The argument does not apply to the relational model itself because the relational model does not allow NULLs.)
I'll try to summarize his example in words. He presents a table S with attributes SNO (Supplier Number) and City (City where supplier is located) and one row: (S1, London). Also a table P with attributes PNO (Part Number) and City (City where part is produced) and one row: (P1, NULL). Now he does the query "Get (SNO,PNO) pairs where either the supplier and part cities are different or the part city isn't Paris (or both)."
In the real world, P1 is produced in a city that either is or is not Paris, so the query should return (S1, P1) because the part city either is Paris or is not Paris. (The mere presence of P1 in table P means that the part has a city associated with it, even if unknown.) If it is Paris, then supplier and part cities are different. If it is not Paris, then the part city is not Paris. However, by the rules of three-valued logic, ('London' <> NULL) evaluates to UNKNOWN, (NULL <> 'Paris') evaluates to UNKNOWN, and UNKNOWN OR UNKNOWN reduces to UNKNOWN, which is not TRUE (and not FALSE either), and so the row isn't returned. The result of the query "SELECT S.SNO, P.PNO FROM S, P WHERE S.CITY <> P.CITY OR P.CITY <> 'Paris'" is an empty table, which is the wrong answer.
I'm not an expert and not currently equipped to take the pro or con here. I do consider C.J. Date to be one of the foremost authorities on relational theory.
P.S. It is also true that you can use SQL as something other than a relational database. It can do many things. | Should I allow null values in a db schema? | [
"",
"sql",
"database",
"database-design",
""
] |
64bit file API is different on each platform.
in windows: `_fseeki64`
in linux: `fseeko`
in freebsd: yet another similar call ...
How can I most effectively make it more convenient and portable? Are there any useful examples? | Most POSIX-based platforms support the "**\_FILE\_OFFSET\_BITS**" preprocessor symbol. Setting it to **64** will cause the **off\_t** type to be 64 bits instead of 32, and file manipulation functions like **lseek()** will automatically support the 64 bit offset through some preprocessor magic. From a compile-time point of view adding 64 bit file offset support in this manner is fairly transparent, assuming you are correctly using the relevant typedefs. Naturally, your ABI will change if you're exposing interfaces that use the **off\_t** type. Ideally you should define it on the command line, e.g.:
```
cxx -D_FILE_OFFSET_BITS=64
```
to make sure it applies to all OS headers included by your code.
Unfortunately, Windows doesn't support this preprocessor symbol so you'll either have to handle it yourself, or rely on a library that provides cross-platform large file support. [ACE](http://www.cs.wustl.edu/~schmidt/ACE.html) is one such library (both POSIX based and Windows platforms - just define **\_FILE\_OFFSET\_BITS=64** in both cases). I know that [Boost.filesystem](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm) also supports large files on POSIX based platforms, but I'm not sure about Windows. Other cross-platform libraries likely provide similar support. | My best suggestion would be to use a library for handling this which already exists.
A good candidate might be using the CPL file library from [GDAL](http://gdal.org/). This provides cross-platform large-file support for read+write, in ascii and binary access. Most of the GDAL file formats have been implemented using it, and are widely used. | Large file support in C++ | [
"",
"c++",
"c",
"64-bit",
"cross-platform",
"large-files",
""
] |
I'm writing an app that accepts .mp4 uploads.
So I've a 24.3MB .mp4 that is posted to the server, but it fails silently.
The next smallest file I have is a 5.2MB .flv. It's not the file type of course, but file size.
I wonder if anybody could shed some light on this?
P.S. the relevant php.ini entries are as follows:
```
memory_limit = 256M
upload_max_filesize = 32M
```
Help! | You should also set post\_max\_size. Files are sent using HTTP POST. | I wonder if it's encoding-related. Base64 encoding = 33% greater size. 24.3 \* 1.33 = 32.4 MB > 32 MB. Try a 23.9 MB file and see if that succeeds | 24MB PHP file upload fails silently | [
"",
"php",
"upload",
""
] |
I recently read about quicksort and was wondering whether it would be smart to build my own function to sort things with quicksort or if it would be inefficent. What do you think is the built in sort function better than a selfbuilt quicksort function? | From <http://php.net/sort>
> Note: Like most PHP sorting
> functions, sort() uses an
> implementation of » Quicksort.
The core PHP functions will be implemented in c, rather than PHP, so they should generally be significantly faster than anything you can write yourself in PHP. There will be cases where it is faster to write your own, but I guess these would be when you have a very specific case and you can make your own specific optimisations for that. I think that is unlikely to be the case here. | In fact I did this for a data point on a presentation I am putting together. The test sorts an array of 250,000 integers using the native sort function and an implementation of the quicksort algorithm written in php. The contents of the array are exactly the same for both runs, the data is randomized, and the time reported is only for performing the sort, not other processing necessary to invoke the php interpreter.
Results:
```
Native sort implementation: 1.379 seconds
PHP quicksort implementation: 30.615 seconds
```
Definitely use the native implementation. That should be the case for any interpreted language.
The results for the other languages I tested with the same conditions using the same implementation on the same hardware and OS, provide an interesting performance comparison and put the PHP result in perspective:
```
C: 0.107 seconds
Java: 0.250 seconds
JavaScript (FF3): 4.401 seconds
```
Notably, Chrome and Safari performed *much* faster for the JavaScript test, but I don't include those here because those tests were recorded in a different environment. | Building quicksort with php | [
"",
"php",
"quicksort",
""
] |
Which would be a better option for bulk insert into an Oracle database ?
A FOR Cursor loop like
```
DECLARE
CURSOR C1 IS SELECT * FROM FOO;
BEGIN
FOR C1_REC IN C1 LOOP
INSERT INTO BAR(A,
B,
C)
VALUES(C1.A,
C1.B,
C1.C);
END LOOP;
END
```
or a simple select, like:
```
INSERT INTO BAR(A,
B,
C)
(SELECT A,
B,
C
FROM FOO);
```
Any specific reason either one would be better ? | I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query | The general rule-of-thumb is, if you can do it using a single SQL statement instead of using PL/SQL, you should. It will usually be more efficient.
However, if you need to add more procedural logic (for some reason), you might need to use PL/SQL, but you should use bulk operations instead of row-by-row processing. (Note: in Oracle 10g and later, your FOR loop will automatically use BULK COLLECT to fetch 100 rows at a time; however your insert statement will still be done row-by-row).
e.g.
```
DECLARE
TYPE tA IS TABLE OF FOO.A%TYPE INDEX BY PLS_INTEGER;
TYPE tB IS TABLE OF FOO.B%TYPE INDEX BY PLS_INTEGER;
TYPE tC IS TABLE OF FOO.C%TYPE INDEX BY PLS_INTEGER;
rA tA;
rB tB;
rC tC;
BEGIN
SELECT * BULK COLLECT INTO rA, rB, rC FROM FOO;
-- (do some procedural logic on the data?)
FORALL i IN rA.FIRST..rA.LAST
INSERT INTO BAR(A,
B,
C)
VALUES(rA(i),
rB(i),
rC(i));
END;
```
The above has the benefit of minimising context switches between SQL and PL/SQL. Oracle 11g also has better support for tables of records so that you don't have to have a separate PL/SQL table for each column.
Also, if the volume of data is very great, it is possible to change the code to process the data in batches. | Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I am developing an application that remembers the user's preferences as to where the form was last located on the screen. In some instances the user will have it on a secondary screen, and then fire the app up later without the second screen (sometimes having the form appear off screen). Other times the user will change their resolution resulting in a similar effect.
I was hoping to do this checking in the Form\_Shown event handler. Basically I want to determine whether the form is completely off screen so I can re-position it.
Any advice? | Check with this function if Form is **fully on screen**:
```
public bool IsOnScreen( Form form )
{
Screen[] screens = Screen.AllScreens;
foreach( Screen screen in screens )
{
Rectangle formRectangle = new Rectangle( form.Left, form.Top,
form.Width, form.Height );
if( screen.WorkingArea.Contains( formRectangle ) )
{
return true;
}
}
return false;
}
```
Checking **only top left point** if it's on screen:
```
public bool IsOnScreen( Form form )
{
Screen[] screens = Screen.AllScreens;
foreach( Screen screen in screens )
{
Point formTopLeft = new Point( form.Left, form.Top );
if( screen.WorkingArea.Contains( formTopLeft ) )
{
return true;
}
}
return false;
}
``` | Combining all the solutions above with the "IntersectsWith"-method and LINQ-extensions give us in short:
```
public bool IsOnScreen(Form form)
{
// Create rectangle
Rectangle formRectangle = new Rectangle(form.Left, form.Top, form.Width, form.Height);
// Test
return Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(formRectangle));
}
``` | Determining if a form is completely off screen | [
"",
"c#",
"winforms",
"screen",
""
] |
Alrite, I am gonna jump straight to the code:
```
public interface Visitor {
public void visitInventory();
public void visitMaxCount();
public void visitCountry();
public void visitSomethingElse();
public void complete();
//the idea of this visitor is that when a validator would visit it, it would validate data
//when a persister visits it, it would persist data, etc, etc.
// not sure if I making sense here...
}
public interface Visitable {
public void accept(Visitor visitor);
}
```
here is a base implementation:
```
public class StoreValidator implements Visitor {
private List <ValidationError> storeValidationErrors = new ArrayList<ValidationError>();
public void addError(ValidationError error) {
storeValidationErrors.add(error);
}
public List<ValidationError> getErrors() {
return storeValidationErrors;
}
public void visitInventory() {
// do nothing
}
public void visitMaxCount() {
//do nothing
}
//... etc.. all empty implementations
}
```
You will see why I did an empty implementation here... I would write a validator now.. which extends StoreValidator
```
public XYZValidator extends StoreValidator {
@Override
public void visitInventory(Visitable visitable) {
// do something with visitable .. cast it to expected type
// invoke a DAO, obtain results from DB
// if errors found, do addError(new ValidationError()); with msg.
}
@Override
public void visitMaxCount(Visitable visitable) {
//do something with visitable..
}
// I wouldn't implement the rest coz they wouldn't make sense
// in XYZValidator.. so they are defined as empty in StoreValidator.
}
```
Now here is what a visitable would look like:
```
public Store implements Visitable {
public void accept(Visitor visitor) {
visitor.visitInventory();
visitor.visitMaxCount();
}
}
```
I could have code that does something like this on a list of Store objects:
```
List<Store> stores; //assume this has a list of stores.
StoreValidator validator = new XYZValidator(); //or I would get it from a validatorfactory
for(Store store: stores) {
store.accept(validator); // so even if you send a wrong validator, you are good.
}
```
Similarly you would have ABCValidator which would provide implementation for other methods (visitCountry / visitSomethinElse) and it would extend from StoreValidator. I would have another type of Object (not Store) defining accept method.
I do see a problem here...
Say, I need a FileValidator which is different from StoreValidator, I would expect it to have none of these business related validations such as visitInventory(), etc. But, by having a single interface Visitor, I would endup declaring all kinds of methods in Visitor interface. Is that correct? Is this how you do it?
I don't know if I got the pattern wrong, or if I am making any sense.
Please share your thoughts. | There is a problem with your code as given. The interface you give has methods such as
```
public void visitInventory();
```
but you then implement it in XYZValidator as
```
public void visitInventory(Visitable visitable)
```
The [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) is a way to implement [multiple dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch) in languages that do not do that automatically (such as Java). One of the requirements is that you have a group of related classes (i.e. a set of subclasses with a single super class). You don't have that here, so the visitor pattern is not appropriate. The task you are trying to do, however, is fine, it is just not the Visitor pattern.
In Java, you should think of the Visitor pattern if you have code like
```
public void count(Item item) {
if (item instanceof SimpleItem) {
// do something
} else if (item instanceof ComplexItem {
// do something else
} else ...
}
```
particulary if the subclasses of Item are relatively fixed. | Some time ago I wrote something similar for my master thesis. This code is slightly
type safe than yours:
```
interface Visitable<T extends Visitor> {
void acceptVisitor(T visitor);
}
interface Visitor {
/**
* Called before any other visiting method.
*/
void startVisit();
/**
* Called at the end of the visit.
*/
void endVisit();
}
```
example:
```
interface ConstantPoolVisitor extends Visitor {
void visitUTF8(int index, String utf8);
void visitClass(int index, int utf8Index);
// ==cut==
}
class ConstantPool implements Visitable<ConstantPoolVisitor> {
@Override
public void acceptVisitor(ConstantPoolVisitor visitor) {
visitor.startVisit();
for (ConstanPoolEntry entry : entries) {
entry.acceptVisitor(visitor);
}
visitor.endVisit();
}
```
so yes, I think that this definitely a good and flexible design if, and only if, your data changes slower than your behaviour. In my example the data is Java bytecode, that is fixed (defined by the JVM specification). When "behaviour dominates" (I want to dump, compile, transform, refactor, etc my bytecode) the Visitor pattern let you to change/add/remove behaviour without touching your data classes. Just add another implementation of Visitor.
For the sake of simplicity assume that I must add another visit method to my Visitor interface: I would end in breaking all my code.
**As alternative I would consider the strategy pattern for this scenario**. Strategy + decorator is a good design for validation. | Visitor pattern implementation in java- How does this look? | [
"",
"java",
"visitor-pattern",
""
] |
I just can't seem to wrap my head around this... I have a sequence that look a bit like this:
```
A 1 1 50
A 1 2 50
A 2 1 20
A 2 2 60
B 1 1 35
B 1 2 35
C 1 1 80
D 1 1 12
D 1 2 12
D 1 3 15
D 2 1 12
```
What I need to do is to set those last column values to 0, where they are not the last value. So for example I need to set A11 to 0 because there is an A12. And I need to set A21 to 0, because there is an A22. B11 must be 0, because there is a B12. C11 is left, since there is no C12. D11 and D12 goes 0 because of D13, and D21 is left like it is.
In the actual dataset, column 1 is usernames, column 2 is dates, column 3 is login times and the last is an amount. And I need to set all those amounts, that are not connected with the last login time on a certain date for a certain user to 0.
Anyone that is able to do this in an easy way? I'm thinking multiple nested foreach statements or joining and grouping etc etc, but I can't decide how to do it best... or how to do it at all really...
(And please do edit my title if you come up with a better one!)
---
**More info**
Sorry, I should of course have told you more about the language and such. I am using C# and .NET 3.5. And I am using Linq to SQL to fetch the data from the database, and I have all that data as objects (Of a simple kind of container type class) in a generic List. I wish I could have just adjusted the query to only get the last rows, but the problem is that this data is going into a report, and all of the rows has to be displayed. I was hoping that I could do this in the report, but this seems to be [not so easy](https://stackoverflow.com/questions/829569/ssrs-how-to-make-a-sum-that-only-includes-the-last-item-in-a-group). Or at least I have no clue how to do it, and haven't gotten any working answers either. So this is why I figure I need to copy that column and clear out those duplicate values. So that I can display the column with all values, and then do the summing on the column that only has the last values. Hope that made sense :P
Oh, and also, to clear up the dates and login times in separate columns issue: Thing is that they are both DateTimes, and the date doesn't need to have the same date as the login datetime. It is a weird issue caused by that in what I am working with a day may not need to be 00:00 to 23:59. A day may start at 3:00 in the morning for example.
---
**Update**
Just figured out that this whole issue might be solved in a different way... (And probably even should be) By creating a new column (In my case a new property) and then copy only those last values over into that new property. But again I would have to find all those values... So kind of same problem as the one I already have but a bit backwards or what to call it. | Ok, I decided to do it the other way around. I added another column, and then I run this code:
```
data
.GroupBy(x => new
{
x.Col1,
x.Col2,
})
.Select(x => x.MaxBy(y => y.Col3)
.ForEach(x =>
{
x.Col5 = x.Col4,
});
```
This solution does not really answer my original question though. But, to give a suggestion on how one could do that, based on the way I did it:
* Group like in other example
* For each group sequence ordered in descending order based on Col3
+ Set all but the first item to 0 (Maybe just use a bool or something)
Untested, but in my head this should work at least :p
**Note:** The [MaxBy](http://code.google.com/p/morelinq/wiki/OperatorsOverview) and [ForEach](http://code.google.com/p/morelinq/wiki/OperatorsOverview) methods are from [MoreLinq](http://code.google.com/p/morelinq/). | If the data is in ascending user/date/time order, how about simply:
```
Foo lastRow = null;
foreach (Foo row in list)
{
if (lastRow != null && row.User == lastRow.User
&& row.Date == lastRow.Date)
{
lastRow.Value = 0;
}
lastRow = row;
}
``` | Finding all non-last sequences in a sequence | [
"",
"c#",
"list",
""
] |
I found a C++ source file which calculates expressions from a command line argument (argv[1]), however I now want to change it to read a file.
```
double Utvardering(char* s) {
srcPos = s;
searchToken();
return PlusMinus();
}
int main(int argc, char* argv[]) {
if (argc > 1) {
FILE* fFile = fopen(argv[1], "r");
double Value = Utvardering(fopen(argv[1], "r"));
cout << Value << endl;
}else{
cout << "Usage: " << argv[0] << " FILE" << endl;
}
cin.get();
return 0;
}
```
However the Utvardering function requires a char\* parameter. How can I convert the data read from a file, fopen to a char\*? | The function fopen just opens a file. To get a string from there, you need to read the file. There are different ways to to this. If you know the max size of your string in advance, this would do:
```
const int MAX_SIZE = 1024;
char buf[MAX_SIZE];
if (!fgets(buf, MAX_SIZE, fFile) {
cerr << "Read error";
exit(1);
}
double Value = Utvardering(buf);
```
Note: this method is typical for C, not for C++. If you want more idiomatic C++ code, you can use something like this (instead of FILE and fopen):
```
ifstream in;
in.open(argv[1]);
if (!in) { /* report an error */ }
string str;
in >> str;
``` | Use the [fread()](http://msdn.microsoft.com/en-us/library/kt0etdcs(VS.71).aspx) function to read data from the FILE\* into a buffer. Send that buffer into Utvardering(). | C++ - Convert FILE* to CHAR* | [
"",
"c++",
"file",
"char",
""
] |
I have a `StackPanel` containing a `StackPanel` and some other items. The first `StackPanel` has a vertical orientation, the the inner one has a horizontal orientation. The inner one has a `TreeView` and a `ListView`, I would like them to expand and fit the width of the window, which I set by the window and allow the user to change. I would also like the outer `StackPanel` to fit the height of the window. How do I do this?
**Edit:**
I've converted to using a `DockPanel`, and I've set the `DockPanel.Dock` properties correctly in each of the elements, and have disabled `LastChildFill` in both of the dockpanels, the layout still does not stretch.
The Code:
```
<Window x:Class="Clippy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">
<DockPanel Name="wrapperDockPanel" LastChildFill="False">
<Menu Height="22" Name="mainMenu" Width="Auto" DockPanel.Dock="Top" />
<ToolBar Height="26" Name="mainToolBar" Width="Auto" DockPanel.Dock="Top" />
<DockPanel Height="Auto" Name="contentDockPanel" DockPanel.Dock="Top" LastChildFill="False">
<TreeView Name="categoryTreeView" />
<ListView Name="clipListView" />
</DockPanel>
<StatusBar Height="23" Name="mainStatusBar" DockPanel.Dock="Top" />
</DockPanel>
</Window>
``` | This should do it - I set it up so that the TreeView and the ListView shared the main view 50/50; if you don't want that, set it to 'Auto' and '\*' or something. Use "LastChildFill" to your advantage!
```
<Window x:Class="Clippy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">
<DockPanel LastChildFill="True">
<Menu Width="Auto" DockPanel.Dock="Top" />
<ToolBar Width="Auto" DockPanel.Dock="Top" />
<StatusBar DockPanel.Dock="Bottom" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="0.5*" />
</Grid.RowDefinitions>
<TreeView Name="categoryTreeView" Grid.Row="0" />
<ListView Name="clipListView" Grid.Row="1" />
</Grid>
</DockPanel>
</Window>
``` | Use a DockPanel instead. StackPanel explicitly doesn't care about visible space, whereas DockPanel does all of it's size calculation based on available space.
**Update:**
In addition, in my experience, putting the body of the window into a View, and only having the View in the Window makes for a better Auto Size experience.
For some reason putting all of the children directly into the Window seems to not auto size very well.
**Update 2:**
I would remove the explicit DockPanel.Dock attribute from the element that you want to stretch (fill) the unused space. | How to make items in a DockPanel expand to fit all available space in WPF? | [
"",
"c#",
"wpf",
"xaml",
"stackpanel",
"dockpanel",
""
] |
i have Problem with opening popups in javascript i have this function to open my popups in IE6 and IE7:
```
function open_window(Location,w,h) //opens new window
{
var win = "width="+w+",height="+h+",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
alert(win) ;
window.open(Location,'newWin',win).focus();
}
```
it's working . i mean my new window opens but an error occurs. The Error Message is :
> 'window.open(...)' is null is not an object.
> do you want to countinue running script on this page ?
then i have button in onclick event it's will call a function to close current window an refresh the opener function is
```
function refreshParent(location)
{
window.opener.location.href = location ;
window.close();
}
```
it's also gives me error : window.opener.location is null or not an object but i'm sure i'm passing correct parameters
i call it like this :
for second part :
```
<input type="button" name="pay" value="test" onclick="refreshParent('index.php?module=payment&task=default')" >
```
for first part :
```
<a onclick="javascript:open_window('?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on','500' , '500')" style="cursor:pointer" id="addtocard"> <img src="../images/new_theme/buy_book.gif" width="123" border="0"/> </a>
```
it's really confuse me . Please Help ;) | When popup windows opened using window.open are blocked by a popup blocker, a feature of pretty much any modern browser these days, the return value of window.open() is not a window object, but null.
In order to circumvent these issues you would need to test the value returned by window.open() before attempting to invoke any methods on it.
Below is a piece of code to demonstrate how to go around this problem:
```
function open_window(Location,w,h) //opens new window
{
var options = "width=" + w + ",height=" + h;
options += ",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
var newwin = window.open(Location,'newWin',options);
if (newwin == null)
{
// The popup got blocked, notify the user
return false;
}
newwin.focus();
}
```
In general, popup windows should be used only as a last resort or in controlled environments (internal company website, etc). Popup blockers tend to behave in very inconsistent ways and there may be more than a single popup blocker installed in a given browser so instructing the user on how to allow popups for a given website is not necessarily a solution. Example: IE7 + Google toolbar = two popup blockers.
If I may suggest, perhaps you should consider using something like this:
<http://jqueryui.com/demos/dialog/>
The advantages are numerous:
1. Skinnable, so you can create a more consistent look to match your website.
2. No popup blockers.
3. Good API and documentation that is consistent across most, if not all, major browsers.
If you still require that the newly opened "window" contain an external URL, you could use an IFRAME inside the opened dialog window.
Hope this helps,
Lior. | Works perfectly fine for me. Tested in IE6/7/8.
Of course I couldn't test it with your URLs so I replaced these with simple filenames. I'd suggest you try it also with simple filenames and see if it also fails then.
Beside that...
You don't need to add "javascript:" at the beginning of onclick attribute value.
It would also be good if you added a href="..." attribute to the link with the same URL that you give to open\_window. Then it would become a real link and you wouldn't have to add cursor:pointer to it. For example:
```
<a href="?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on"
onclick="open_window(this.href, '500' , '500'); return false;"> ...
``` | javascript popup issue In Internet Explorer ! | [
"",
"javascript",
"internet-explorer",
"popup",
""
] |
So I've just started playing around with Django and I decided to give it a try on my server. So I installed Django and created a new project, following the basics outlined in the tutorial on Djangoproject.com
Unfortunatly, no matter what I do, I can't get views to work: I constantly get
```
ImportError at /
No module named index
```
[Here](http://grabup.nakedsteve.com/4031375c5cdb6246abf2011e6cc69a8a.png) is a screenshot of this error
I've been googling and trying various commands with no luck, and I'm literally about to tear my hair out until I become bald. I've tried adding the django source directory, my project directory, and the app directory to PYTHONPATH with no luck. I've also made sure that **init**.py is in all of the directories (both project and app) Does anyone have any idea as to what could be going wrong here?
**UPDATES**
Sorry, I was in kind of a rush while posting this, here's some context:
The server I've been trying is just django's built in server using manage.py (python manage.py 0.0.0.0:8000, since I need to access it externally) on linux (debian)
appdir/views.py
```
from django.http import HttpResponse
def index(request):
return HttpResponse("Sup")
def test(request):
return HttpRespons("heyo")
```
urls.py
```
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^****/', include('****.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^test/', include('mecore.views.test')),
(r'^', include('mecore.views.index'))
)
``` | Your `urls.py` is wrong; you should consider reading [this](http://docs.djangoproject.com/en/dev/intro/tutorial03/#intro-tutorial03) and [this](http://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-urls).
You don't include a function; you include a module. You name a function, `mecore.views.index`. You only include entire modules `include('mecore.views')`.
```
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^****/', include('****.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^test/', 'mecore.views.test'),
(r'^', 'mecore.views.index')
)
``` | Do you have `__init__.py` in each of the mecore and views directories, as well as an index.py in views?
A directory is a package, from Python's viewpoint, only if it has a file named `__init__.py` (it may be empty, if you don't need to execute any special code when that package is imported, but it has to be there).
Edit: note that in `include` you must name the python path to a module, not to a function: see [Django's relevant docs](http://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs) -- judging from your comment you appear to be mis-using `include`, as I see @S.Lott had surmised in his answer. | Django ImportError at / no matter what I do | [
"",
"python",
"django",
""
] |
I have some template string
> this is my {0} template {1} string
which I plan to put user values in using `String.Format()`.
The string actually is longer so for readability I use:
> this is my {goodName1} template {goodName2} string
And then `String.Replace` each parameter with its value.
How can I get the highest performance and readability?
Maybe I should not have this template in a file (as now) but dynamically build it by concatanating to a string builder and adding the params when required? Although it's less readable.
What's my other options? | From Atwood: [It. Just. Doesn't. Matter.](http://www.codinghorror.com/blog/archives/001218.html) | You can put the parameters in a dictionary and use the `Regex.Replace` method to replace all of the parameters in one replacement. That way the method scales well if the template string gets long or the number of parameters grows.
Example:
```
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("goodName1", "asdf");
parameters.Add("goodName2", "qwerty");
string text = "this is my {goodName1} template {goodName2} string";
text = Regex.Replace(text, @"\{(.+?)\}", m => parameters[m.Groups[1].Value]);
``` | fastest way to replace string in a template | [
"",
"c#",
"performance",
"string",
""
] |
In a PHP script I'm accepting input from the user from a `textarea` and want to allow a few basic tags. So when I output the string I'm using -
```
echo strip_tags($content, '<b><i><ul><ol><li>');
```
Now normally I would use `FILTER_SANITIZE_STRING` but that would strip all tags and I would use `html_entities()` but that would prevent the tags I'm passing through from displaying as they should.
So what else do I need to strip or encode and how do I do that? | I don't think you can rely on `strip_tags()` for security purposes - from <http://php.net/strip_tags>:
> This function does not modify any
> attributes on the tags that you allow
> using allowable\_tags , including the
> style and onmouseover attributes that
> a mischievous user may abuse when
> posting text that will be shown to
> other users.
It might be better to look at something like [HTML Purifier](http://htmlpurifier.org/) or [PEAR HTML\_Safe](http://pear.php.net/package/HTML_Safe), which should be able to do exactly what you want. | Check your input against the rules mentioned on the [XSS cheat sheet](http://ha.ckers.org/xss.html). Also from a security stand point, it would be best to familiarize yourself with [OWASP Guide to Building Secure Web Applications and Web Services](http://www.owasp.org/index.php/Category:OWASP_Guide_Project) | After stripping unwanted tags, what else should I do to text input? | [
"",
"php",
"xhtml",
"string",
"filter",
"tags",
""
] |
In one class, ClassA, I have a timer object. In this class I register the event handlers for the timer elapsed event. In another class, ClassB, I have a public event-handler for the timer elapsed event. So I register the event-handler from ClassB in ClassA as follows:
```
myTimer.Elapsed += ClassBInstance.TimerElapsed
```
What happens if I were to create a new instance of ClassBInstance and the timer elapsed event fires when the previous instance of ClassB's event-handler is still tied to the Elapsed event of the timer?
For example:
```
ClassB classBInstance = new ClassB();
myTimer.Elapsed += classBInstance.TimerElapsed
classBInstance = new ClassB();
myTimer.Elapsed += classBInstance.TimerElapsed
``` | AFAIK, ClassBInstance is not garbage collected as long as there are events registered, because the event holds a reference to it.
You have to make sure that you unregister all events of instances that are no longer in use.
Important are cases where the registered instance is IDisposable, because the event could be fired when the instance is disposed. In this cases I found it easiest to let the instance register itself, and unregister in Dispose. | Events are implemented such that as long as your publisher is alive all subscribers will be kept alive by the publisher even if you don't hold any other references to these.
Of course this also implies, that you must detach subscribers, if you want them to be cleaned-up independently of the publisher. | What happens when an event fires and tries to execute an event-handler in an object that no longer exists? | [
"",
"c#",
"events",
"event-handling",
""
] |
I have a web page with embedded PDF on it. My code looks like this:
```
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%">
</embed>
```
I have this javascript code for print my PDF:
```
function printDocument(documentId) {
//Wait until PDF is ready to print
if (typeof document.getElementById(documentId).print == 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
var x = document.getElementById(documentId);
x.print();
}
}
```
When this code is executed Acrobat plug-in opens the well-known print dialog. Something like this:

Two questions:
* How to improve the way to detect that PDF is loaded and ready for print?
* How to avoid showing print dialog?
A little more info about my system:
**OS:** Windows XP
**Browser:** Internet Explorer 7
**PDF Plugin:** Acrobat Reader 9 | You are not going to be able to print silently with plain old JavaScript. How would you like your printer to start printing out 100000000 pages of all black. Not a good thing. If you want to print silently and have it work for Internet Explorer only, there are ActiveX controls out there that can do it. This requires higher security settings for your page and for your users to really trust your site. | This is possible in a trusted, Intranet environment.
```
<object id="pdfDoc" style="position:absolute;z-index:-1;" name="pdfDoc" classid="clsid:CA8A9780-280D-11CF-A24D-444553540000" width="900px" height="100%">
<param name="SRC" value="yourdoc.pdf" />
</object>
<input type="button" ... onclick="pdfDoc.printAll();" />
```
This will bypass the print dialog and send directly to the default printer. | Silent print an embedded PDF | [
"",
"javascript",
"html",
"pdf",
"acrobat",
""
] |
I was reading the C++0x FAQ by Stroustrup and got stuck with this code. Consider the following code
```
struct A
{
void f(double)
{
std::cout << "in double" << std::endl;
}
};
struct B : A
{
void f(int)
{
std::cout << "in int" << std::endl;
}
};
int main()
{
A a; a.f(10.10); // as expected, A.f will get called
B b; b.f(10.10); // This calls b.f and we lose the .10 here
return 0;
}
```
My understanding was when a type is inherited, all protected and public members will be accessible from the derived class. But according to this example, it looks like I am wrong. I was expecting the *b.f* will call base classes *f*. I got the expected result by changing the derived class like
```
struct B : A
{
using A::f;
void f(int)
{
std::cout << "in int" << std::endl;
}
};
```
*Questions*
1. Why was it not working in the first code?
2. Which section in the C++ standard describes all these scoping rules? | The first code works as c++ is designed to work.
Overloading resolution follows a very complicated set of rules. From Stroustrup's c++ bible 15.2.2 "[A]mbiguities between functions from different base classes are not resolved based on argument types."
He goes on to explain the use of "using" as you have described.
This was a design decision in the language.
I tend to follow the Stroustrup book rather than the standard, but I'm sure it is in there.
[Edit]
Here it is (from the standard):
Chapter 13
When two or more different declarations are specified for a single name in the same scope, that name is said to be
overloaded.
And then:
13.2 Declaration matching
1 Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations (13.1). A function member of a derived class is not in the same scope as a function member of
the same name in a base class. | Its because A::f is "hidden" rather than "overloaded" or "overridden". Refer:
<http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9> | Scoping rules when inheriting - C++ | [
"",
"c++",
"scope",
""
] |
When I compiled a code using the array name as a pointer, and I deleted the array name using `delete`, I got a warning about deleting an array without using the array form (I don't remember the exact wording).
The basic code was:
```
int data[5];
delete data;
```
So, what's the array form of delete? | The array form of delete is:
```
delete [] data;
```
**Edit:** But as others have pointed out, you shouldn't be calling `delete` for data defined like this:
```
int data[5];
```
You should only call it when you allocate the memory using `new` like this:
```
int *data = new int[5];
``` | You either want:
```
int *data = new int[5];
... // time passes, stuff happens to data[]
delete[] data;
```
or
```
int data[5];
... // time passes, stuff happens to data[]
// note no delete of data
```
The genera rule is: only apply `delete` to memory that came from `new`. If the array form of `new` was used, then you *must* use the array form of `delete` to match. If placement `new` was used, then you either never call `delete` at all, or use a matching placement `delete`.
Since the variable `int data[5]` is a statically allocated array, it cannot be passed to any form of the `delete` operator. | What is the array form of 'delete'? | [
"",
"c++",
"arrays",
"memory-management",
""
] |
I am setting up a .net project that is called to generate other webpages. Basically a true CODE BEHIND page. How do I go about making a connection on a Class Library File, when there is no webconfig file present/available? | In this case, I would create a 'Base Page' that derives from System.Web.UI.Page. On this page, you would create a property called 'ConnectionString'. You will have all of your web pages you create inherit from this page.
Example:
```
public partial class BasePage : System.Web.UI.Page
{
protected string ConnectionString
{
get
{
return System.Configuration.ConfigurationSettings.AppSettings["MyConnectionString"];
}
}
}
```
And in your web.config
```
<appSettings>
<!-- Connection String -->
<add key="MyConnectionString" value="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"/>
</appSettings>
```
Now you can have a web.config file with a connection string that is easily readable. And you can store this 'Base Page' in your class library, no problem. As long as your web pages inheriting from it are using the web.config file with the connection string.
After that, it's a simple matter of connecting using that string. You can do this in a variety of ways, either in your web pages, or in separate classes (I recommend separate classes). In this case, if you had a separate class, you would need to pass in the ConnectionString property to your connecting functions:
```
public void ExecuteQuery(string connectionString, string sql)
{
using (System.Data.SqlClient.SqlConnection theConnection = new System.Data.SqlClient.SqlConnection(connectionString))
using (System.Data.SqlClient.SqlCommand theCommand = new System.Data.SqlClient.SqlCommand(sql, theConnection))
{
theConnection.Open();
theCommand.CommandType = CommandType.Text;
theCommand.ExecuteNonQuery();
}
}
```
or you can create a function that does not take a connection string parameter, and just reads from the web.config file. It sounds like you may want to put your connecting and data access code in a class library for good separation of data and content. Hope this helps! | There are several ways to solve this:
1) If you're class library is really going to generate web pages, then it will probably be deployed on the server with the web.config and so can use properties of the web.config file. If you don't want to use the ConnectionString part, then you can just make an appSetting with the connection string.
The benefits of doing this are that it's easy to change or have different connection strings for different environments (testing, deployment, etc.). And if you decide to use the class library in another kind of app, you can use the app.config file with the same setting.
Depending on the type of database, you'll be using the System.Data and possibly some of the sub-namespaces to make this work.
2) You can hard code the connection string into the code. Ugly, but workable in a pinch.
3) You could use an entity framework to help you out and cut down on the work that you have to do. | Can I create a Database connection in a Class Library Project? | [
"",
"c#",
".net",
"asp.net",
"visual-studio",
"visual-studio-2008",
""
] |
User SQLServer 2005
Here is an example of string I'm stuck with: {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial Rounded MT Bold;}{\f1\fnil\fcharset0 Arial;}} \viewkind4\uc1\pard\f0\fs54 1000\f1\fs20\par }
I want to replace any font name with 'Times New Roman'
I can get the first one with (textlong1 is the field):
```
Select Replace(textlong1,
CASE When CharIndex(';',textlong1)> 10 Then
SubString(textlong1
, Charindex('fcharset',textlong1)+10
, CharIndex(';',textlong1) - Charindex('fcharset',textlong1)-10)
Else '' End
, 'Times New Roman') From exampletable
```
I'm using the case statement to prevent the SubString from error.
Since I am not replacing 'fcharset', even if I loop through, it is not finding the second instance (always gets stuck on the first). | If you can replace the first one, just keep replacing till there is no first one. If you're doing an update:
```
declare @done bit
while @done <> 1
begin
UPDATE ...
if @@rowcount = 0 set done = 1
end
```
Or selecting into a new variable:
```
declare @cur varchar(4000)
declare @next varchar(4000)
set @cur = 'The string to operate on'
set @next = ''
while @cur <> @next
begin
set @next = @cur
select @cur = REPLACE(@next,...)
end
```
The final result is now stored in @cur (and @next too.) | If you can integrate the .NET CLR functionality (MSDN has many examples for doing that), you could use a regex replace and make your task very simple. | Replace multiple instances in select statement | [
"",
"sql",
"sql-server",
"replace",
""
] |
What is the best to determine the Microsoft OS that is hosting your ASP.NET application using the `System.Environment.OSVersion` namespace
I need an example for Windows XP, Windows Server 2003 and Windows Vista
Here is what I am trying to accomplish using pseudocode
```
switch(/* Condition for determining OS */)
{
case "WindowsXP":
//Do Windows XP stuff
break;
case "Windows Server 2003":
//Do Windows Server 2003 stuff
break;
case "Windows Vista":
//Do Windows Vista stuff
break;
}
``` | The following should work. But why do you care? Is just for informational purposes in logging or are you looking for actual capabilities being present on the target platform?
```
if (Environment.OSVersion.Version.Major == 5)
{
if (Environment.OSVersion.Version.Minor == 1)
{
// XP
}
else if (Environment.OSVersion.Version.Minor == 2)
{
// Server 2003. XP 64-bit will also fall in here.
}
}
else if (Environment.OSVersion.Version.Major >= 6)
{
// Vista on up
}
``` | Not a complete list, but got this from <http://support.microsoft.com/kb/304283>:
```
+--------------------------------------------------------------+
| |Windows|Windows|Windows|Windows NT|Windows|Windows|
| | 95 | 98 | Me | 4.0 | 2000 | XP |
+--------------------------------------------------------------+
|PlatformID | 1 | 1 | 1 | 2 | 2 | 2 |
+--------------------------------------------------------------+
|Major | | | | | | |
| version | 4 | 4 | 4 | 4 | 5 | 5 |
+--------------------------------------------------------------+
|Minor | | | | | | |
| version | 0 | 10 | 90 | 0 | 0 | 1 |
+--------------------------------------------------------------+
```
Edit: Note, the information returned by System.Environment.OSVersion may be unreliable if the application is running in compatibility mode.
Edit2: I would recommend you just make it a configurable value in your application - that way your code does not need recompilation when a new OS comes out, e.g., Windows 7. | Determine OS using Environment.OSVersion | [
"",
"c#",
"asp.net",
"windows",
""
] |
I'm just diving into some C++ and I decided to make a random number generator (how random the number is, it really doesn't matter). Most of the code is copied off then net but my newbie eyes cannot see anything wrong with this, is there any way this can be tweaked to give a number other than "6" each time?
```
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int random_number(int min, int max)
{
srand((unsigned)time(0));
int random_num;
int range=(max-min)+1;
random_num = min+int(range*rand()/(RAND_MAX + 1.0));
return random_num;
}
int main()
{
for(int i =0;i < 100;i++)
{
cout << random_number(3,10) << endl;
}
}
``` | Add srand before the loop
```
srand((unsigned)time(0));
for(int i =0;i < 100;i++)
{
std::cout << random_number(3,10) << endl;
}
``` | Don't call srand() within random\_number(). This will re-seed the random number generator every call. For 100 calls, you'll very likely get the same seed every call, and therefore the same number. | What's wrong with my random number generator? | [
"",
"c++",
"random",
""
] |
I have written the following trigger in SQL server:
```
create trigger test_trigger
on invoice -- This is the invoice table
for insert
as
declare @invoiceAmount int -- This is the amount specified in the invoice
declare @custNumber int -- This is the customer's id
--use the 'inserted' keyword to access the values inserted into the invoice table
select @invoiceAmount = Inv_Amt from inserted
select @custNumber = cust_num from inserted
update customer
set amount = @invoiceAmount
where Id = @custNumber
```
Will this be able to run in MS Access or is the syntax different? | The Access database engine (formerly called Jet) does not have triggers and regardless has no control-of-flow syntax e.g. a PROCEDURE must consist of exactly one SQL statement.
Tell us what you really want to do and there could be an alternative syntax.
For example, you could create a new key using a UNIQUE constraint on invoice, (cust\_num, Inv\_Amt), a FOREIGN KEY customer (id, amount) to reference the new key, a VIEW that joins the two tables on the FOREIGN KEY columns and exposing all four columns, then INSERT into the VIEW rather than the table 'invoice'; you may want to use privileges to prevent INSERTs to the base table but user level security was removed from the new Access 2007 engine (called ACE).
But, if you don’t mind me saying, I think your trigger doesn't reflect a real life scenario. A column vaguely named 'amount' in table 'customer' to hold the most recent invoice amount? What about when the inserted logical table contains rows for more than one customer? As I say, I think you need to tell us what you are really trying to achieve. | Access doesn't have triggers
Your trigger that you show here will bomb out since it does not take into account multirow updates the moment someone updates more than one row (and don't say it won't happen because it will better to practice some defensive coding)
Triggers fire per batch not per row, please read [Multirow Considerations for DML Triggers](http://msdn.microsoft.com/en-us/library/ms190752(SQL.90).aspx)
join inserted pseudo table and the invoice table instead to update the values...that works for 1 and more than 1 row | Are writing triggers in MS SQL server the same as writing them in MS Access? | [
"",
"sql",
"sql-server",
"ms-access",
"triggers",
""
] |
I need to "grab" an attribute of a custom HTML tag. I know this sort of question has been asked many times before, but regex really messes with my head, and I can't seem to get it working.
A sample of XML that I need to work with is
`<!-- <editable name="nameValue"> --> - content goes here - <!-- </editable> -->`
I want to be able to grab the value of the name attribute, which in this case is nameValue. What I have is shown below but this returns a null value.
My regex string (for a Java app, hence the \ to escape the ") is:
`"(.)?<!-- <editable name=(\".*\")?> -->.*<!-- </editable> -->(.)?"`
I am trying to grab the attribute with quotation marks I figure this is the easiest and most general pattern to match. Well it just doesn't work, any help will help me keep my hair. | I don't think you need the `(.)?`s at the beginning and end of your regex. And you need to put in a capturing group for getting only the content-goes-here bit:
This worked for me:
```
String xml = "RANDOM STUFF<!-- <editable name=\"nameValue\"> --> - content goes here - <!-- </editable> -->RANDOM STUFF";
Pattern p = Pattern.compile("<!-- <editable name=(\".*\")?> -->(.*)<!-- </editable> -->");
Matcher m = p.matcher(xml);
if (m.find()) {
System.out.println(m.group(2));
} else {
System.out.println("no match found");
}
```
This prints:
```
- content goes here -
``` | Your search is [greedy](http://www.exampledepot.com/egs/java.util.regex/Greedy.html). Use `"\<\!-- \<editable name=\"(.*?)\"\> --\>.*?\<\!-- \<\/editable\> --\>"` (added `?`). Please note that this one will not work correctly with nested `<editable>` elements.
If you don't want to perform syntax checking, you could also simply go with: `"\<\!-- \<editable name=\"(.*?)\"\> --\>"` or even `"\<editable name=\"(.*?)\"\>"` for better simplicity and performance.
**Edit:** should be
```
Pattern re = Pattern.compile( "\\<editable name=\"(.*?)\"\\>" );
``` | How to change this regex to properly extract tag attributes - should be simple | [
"",
"java",
"regex",
""
] |
I have two listboxes in asp.net. On the click of a button I want to load a list box with the elements of the selected items in the other box. The problem is that this has to be done on the client side because when the button is clicked I don't allow it to submit. I want to call a javascript function onselectedindexchange but that is server side. any ideas? Should i be more clear?
***Solution***
```
enter code here
function Updatelist() {
var sel = document.getElementById('<%=ListBox1.ClientID%>')
var lst2 = document.getElementById('<%=ListBox2.ClientId %>')
var listLength = sel.options.length;
var list2length = lst2.options.length;
for (var i = 0; i < listLength; i++) {
if (sel.options[i].selected) {
//lst2.options.add(sel.options[i].text);
lst2.options[list2length] = new Option(sel.options[i].text);
list2length++;
}
}
}
``` | Try:
```
//onclick for button calls this function
function Updatelist() {
var sel = document.getElementbyId("list1");
var listLength = sel.options.length;
for(var i=0;i<listLength;i++){
if(sel.options[i].selected)
document.getElementById("list2").add(new Option(sel.options[i].value));
}
``` | more precisely we can do it like;
```
function selectedVal(list) {
alert(list.options[list.selectedIndex].text);
}
<select id="listbox" multiple="multiple"
style="height: 300px; width: 200px;"
onclick="javascript:selectedVal(this);">
</select>
``` | Get a listbox's selected items in javascript | [
"",
"asp.net",
"javascript",
"vb.net",
""
] |
My program draws text on its panel,but if I'd like to remove the text I have to repaint.
How do I call(raise) the paint event by hand? | The Invalidate() Method will cause a repaint.
[MSDN Link](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invalidate.aspx) | In a method of your Form or Control, you have 3 choices:
```
this.Invalidate(); // request a delayed Repaint by the normal MessageLoop system
this.Update(); // forces Repaint of invalidated area
this.Refresh(); // Combines Invalidate() and Update()
```
Normally, you would just call `Invalidate()` and let the system combine that with other Screen updates. If you're in a hurry you should call `Refresh()` but then you run the risk that it will be repainted several times consecutively because of other controls (especially the Parent) Invalidating.
The normal way Windows (Win32 and WinForms.Net) handles this is to wait for the [MessageQueue](http://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows) to run empty and then process all invalidated screen areas. That is efficient because when something changes that usually cascades into other things (controls) changing as well.
The most common scenario for Update() is when you change a property (say, label1.Text, which will invalidate the Label) in a for-loop and that loop is temporarily blocking the Message-Loop. Whenever you use it, you should ask yourself if you shouldn't be using a Thread instead. But the answer is't always Yes. | How do I call paint event? | [
"",
"c#",
".net",
"winforms",
"events",
""
] |
I know the differences between public member variables and accessors on private member variables, and saw a few posts already on stack overflow about this. My question has more to do with practices though. Other than not breaking class invariants, what would usually be criterias in terms of practicality to make the member variables to be public rather than private with accessors, and vice versa? Thanks in advance for the advices. | Using an accessor will enforce the client to treat the members as functions, not as raw memory. For instance it will not allow taking the address of said member. So even if the member is as POD as a simple int I still use a get-set pair of function for it. This pays of in the long run as refactoring can change the implementation w/o surprises like 'oh wait, I was taking a void\* to your member'.
Performance wise all compiler will inline this set/get accessors and the assembly will look just as if referencing a public member field.
I don't think in the past 5 years I ever wrote a class that exposed its members public. | My rule of thumb is: If it's not a really simple structure (e.g. `Point` and `Complex`) implement it as accessors to private member variables. And if you are not sure if your structure is simple enough, it probably isn't ;) ..
This way, you always have the option to extend the logic of setting/getting the variable without breaking existing code. Yes, it might be a little more work to implement the accessors in the first place, but it's much much much more work to modify the code to accessors if it was a direct variable access before. | practices on when to implement accessors on private member variables rather than making them public | [
"",
"c++",
""
] |
I need to convert some files to UTF-8 because they're being outputted in an otherwise UTF-8 site and the content looks a little fugly at times.
I can either do this now or I can do it as they're read in (through PHP, just using fopen, nothing fancy). Any suggestions welcome. | I don't have a clear solution for PHP, but for Python I personally used [Universal Encoding Detector library](http://pypi.python.org/pypi/chardet) which does a pretty good job at guessing what encoding the file is being written as.
Just to get you started, here's a Python script that I had used to do the conversion (the original purpose is that I wanted to converted a Japanese code base from a mixture of UTF-16 and Shift-JIS, which I made a default guess if chardet is not confident of detecting the encoding):
```
import sys
import codecs
import chardet
from chardet.universaldetector import UniversalDetector
""" Detects encoding
Returns chardet result"""
def DetectEncoding(fileHdl):
detector = UniversalDetector()
for line in fileHdl:
detector.feed(line)
if detector.done: break
detector.close()
return detector.result
""" Reencode file to UTF-8
"""
def ReencodeFileToUtf8(fileName, encoding):
#TODO: This is dangerous ^^||, would need a backup option :)
#NOTE: Use 'replace' option which tolerates errorneous characters
data = codecs.open(fileName, 'rb', encoding, 'replace').read()
open(fileName, 'wb').write(data.encode('utf-8', 'replace'))
""" Main function
"""
if __name__=='__main__':
# Check for arguments first
if len(sys.argv) <> 2:
sys.exit("Invalid arguments supplied")
fileName = sys.argv[1]
try:
# Open file and detect encoding
fileHdl = open(fileName, 'rb')
encResult = DetectEncoding(fileHdl)
fileHdl.close()
# Was it an empty file?
if encResult['confidence'] == 0 and encResult['encoding'] == None:
sys.exit("Possible empty file")
# Only attempt to reencode file if we are confident about the
# encoding and if it's not UTF-8
encoding = encResult['encoding'].lower()
if encResult['confidence'] >= 0.7:
if encoding != 'utf-8':
ReencodeFileToUtf8(fileName, encoding)
else:
# TODO: Probably you could make a default guess and try to encode, or
# just simply make it fail
except IOError:
sys.exit('An IOError occured')
``` | Doing it only once would improve performance and reduce the potential for future errors, but if you don't know the encoding, you cannot do a correct conversion at all. | Batch convert unknown file encoding to UTF-8 | [
"",
"php",
"linux",
"character-encoding",
""
] |
I need a C/C++ API that allows me to list the running processes on a Linux system, and list the files each process has open.
I do *not* want to end up reading the /proc/ file system directly.
Can anyone think of a way to do this? | <http://procps.sourceforge.net/>
<http://procps.cvs.sourceforge.net/viewvc/procps/procps/proc/readproc.c?view=markup>
Is the source of ps and other process tools. They do indeed use proc (indicating it is probably the conventional and best way). Their source is quite readable. The file
```
/procps-3.2.8/proc/readproc.c
```
May be useful. Also a useful suggestion as **posted by ephemient** is linking to the API provided by **libproc**, which should be available in your repo (or already installed I would say) but you will need the "-dev" variation for the headers and what-not.
**Good Luck** | If you do not want to read from '/proc. Then you can consider writing a Kernel module which will implement your own system call. And your system call should be written so that it can obtain the list of current processes, such as:
```
/* ProcessList.c
Robert Love Chapter 3
*/
#include < linux/kernel.h >
#include < linux/sched.h >
#include < linux/module.h >
int init_module(void) {
struct task_struct *task;
for_each_process(task) {
printk("%s [%d]\n",task->comm , task->pid);
}
return 0;
}
void cleanup_module(void) {
printk(KERN_INFO "Cleaning Up.\n");
}
```
The code above is taken from my article here at <http://linuxgazette.net/133/saha.html>.Once you have your own system call, you can call it from your user space program. | Linux API to list running processes? | [
"",
"c++",
"c",
"linux",
"api",
"process",
""
] |
I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
```
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
``` | [`$functionName()`](https://php.net/manual/en/functions.variable-functions.php) or [`call_user_func($functionName)`](https://php.net/manual/en/function.call-user-func.php)
If you need to provide parameters stored in another variable (in the form of array), use [array unpacking operator](https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat):
```
$function_name = 'trim';
$parameters = ['aaabbb','b'];
echo $function_name(...$parameters); // aaa
```
To dynamically create an object and call its method use
```
$class = 'DateTime';
$method = 'format';
echo (new $class)->$method('d-m-Y');
```
or to call a static method
```
$class = 'DateTime';
$static = 'createFromFormat';
$date = $class::$static('d-m-Y', '17-08-2023');
``` | My favorite version is the inline version:
```
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
```
You can place variables or expressions inside the brackets too! | How to call a function from a string stored in a variable? | [
"",
"php",
"dynamic-function",
""
] |
I want to display google maps (mutliple markers etc) and just found that there is one paid solution "GMap 2.3" for PHP. I was looking for an open source solution. Do you guys code using Google Maps API functions or use any wrapper script? What are some good links for this? | I just use the google maps api. Several months ago I coded up a combination google maps / weather underground ajax data source for creating user-specific weather reports. curl was used on the php side for acting as a proxy for the weather data. the google map side really didn't need any php at all. It really just relies on javascript.
Try doing it without the paid libraries, chances are you'll find it's easier than you expect. | This is the api wrapper i use
<http://www.phpinsider.com/php/code/GoogleMapAPI/>
it works very well and it's open source | Do you use any GoogleMaps Api PHP wrapper class/libarary/script to plot maps? | [
"",
"php",
"google-maps",
""
] |
Can anyone help me here, the following works fine on my xp but not my vista machine. Im querying a Generic dictionary.
Both computers have .NET 3.5 + SP1, 3.0, 2.0, etc., and have the web project targeted to 3.5 Framework.
```
using System.Linq;
string val = "Test";
var d = DictionaryOfStuff().Where(n => n.Key.ToLower().Contains(val.ToLower()));
```
Gives me the error:
CS1525: Invalid expression term '>'
I can run this in a differnet project on vista, I have IIS configured to use .NET 2.0 and the project in VS targeted at 3.5
I have even tried adding this to the web.config, it compiles fine w/o any lambda/linq | Well, here was the answer..
I changed the project to target .NET 3.0, tried to compile got all kinds of errors, changed it back to 3.5 and it compiled fine.
I musta had an old reference in there from something. | Based on the error message, I would have to say there is a configuration issue on your Vista machine and the web projects are using the 2.0 compiler instead of the 3.5 compiler. This is the only reason I can think of that you would get this message.
Make sure that
* IIS is configured properly
* Web settings are configured properly. | Linq + Invalid expression term '>' | [
"",
"c#",
".net",
"linq",
""
] |
I want to execute a command line tool to process data. It does not need to be blocking.
I want it to be low priority. So I wrote the below
```
Process app = new Process();
app.StartInfo.FileName = @"bin\convert.exe";
app.StartInfo.Arguments = TheArgs;
app.PriorityClass = ProcessPriorityClass.BelowNormal;
app.Start();
```
However, I get a `System.InvalidOperationException` with the message "No process is associated with this object." Why? How do I properly launch this app in low priority?
Without the line `app.PriorityClass = ProcessPriorityClass.BelowNormal;` the app runs fine. | Try setting the PriorityClass AFTER you start the process. Task Manager works this way, allowing you to set priority on a process that is already running. | You can create a process with lower priority by doing a little hack. You lower the parent process priority, create the new process and then revert back to the original process priority:
```
var parent = Process.GetCurrentProcess();
var original = parent.PriorityClass;
parent.PriorityClass = ProcessPriorityClass.Idle;
var child = Process.Start("cmd.exe");
parent.PriorityClass = original;
```
`child` will have the `Idle` process priority right at the start. | How do I launch a process with low priority? C# | [
"",
"c#",
"process",
"shellexecute",
""
] |
I have a csv file and i need to import it to a table in sql 2005 or 2008. The column names and count in the csv are different from the table column names and count. The csv is splitted by a ';' .
Example
CSV FILEcontents:
```
FirstName;LastName;Country;Age
Roger;Mouthout;Belgium;55
```
SQL Person Table
```
Columns: FName,LName,Country
``` | I'd create a temporary table, bulk insert the lot, select into the new table what you need and drop the temporary table.
Something like
```
CREATE TABLE dbo.TempImport
(
FirstName varchar(255),
LastName varchar(255),
Country varchar(255),
Age varchar(255)
)
GO
BULK INSERT dbo.TempImport FROM 'PathToMyTextFile' WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
FName,
LName,
Country
)
SELECT FirstName,
LastName,
Country
FROM dbo.TempImport
GO
DROP TABLE dbo.TempImport
GO
``` | You can use a format file when importing with bcp:
Create a format file for your table:
```
bcp [table_name] format nul -f [format_file_name.fmt] -c -T
9.0
4
1 SQLCHAR 0 100 "," 1 FName SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 100 "," 2 LName SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 100 "," 3 Country SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 100 "\r\n" 0 Age SQL_Latin1_General_CP1_CI_AS
```
Edit the import file. The trick is to add a dummy row for the field you want to skip, and add a '0'
as server column order.
Then import the data using this format file, specifying your inputfile, this format file and the seperator:
```
bcp [table_name] in [data_file_name] -t , -f [format_file_name.fmt] -T
``` | Use bcp to import csv file to sql 2005 or 2008 | [
"",
"sql",
"sql-server-2005",
"t-sql",
"sql-server-2008",
"bcp",
""
] |
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.
For example if we have {2:3, 3:2, 5:1} (2^3 \* 3^2 \* 5 = 360)
Then I could write:
```
for i in range(4):
for j in range(3):
for k in range(1):
print 2**i * 3**j * 5**k
```
But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument? | Well, not only you have 3 loops, but this approach won't work if you have more than 3 factors :)
One possible way:
```
def genfactors(fdict):
factors = set([1])
for factor, count in fdict.iteritems():
for ignore in range(count):
factors.update([n*factor for n in factors])
# that line could also be:
# factors.update(map(lambda e: e*factor, factors))
return factors
factors = {2:3, 3:2, 5:1}
for factor in genfactors(factors):
print factor
```
Also, you can avoid duplicating some work in the inner loop: if your working set is (1,3), and want to apply to 2^3 factors, we were doing:
* `(1,3) U (1,3)*2 = (1,2,3,6)`
* `(1,2,3,6) U (1,2,3,6)*2 = (1,2,3,4,6,12)`
* `(1,2,3,4,6,12) U (1,2,3,4,6,12)*2 = (1,2,3,4,6,8,12,24)`
See how many duplicates we have in the second sets?
But we can do instead:
* `(1,3) + (1,3)*2 = (1,2,3,6)`
* `(1,2,3,6) + ((1,3)*2)*2 = (1,2,3,4,6,12)`
* `(1,2,3,4,6,12) + (((1,3)*2)*2)*2 = (1,2,3,4,6,8,12,24)`
The solution looks even nicer without the sets:
```
def genfactors(fdict):
factors = [1]
for factor, count in fdict.iteritems():
newfactors = factors
for ignore in range(count):
newfactors = map(lambda e: e*factor, newfactors)
factors += newfactors
return factors
``` | I have [blogged about this](http://numericalrecipes.wordpress.com/tag/divisors/), and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators:
```
def divisors(factors) :
"""
Generates all divisors, unordered, from the prime factorization.
"""
ps = sorted(set(factors))
omega = len(ps)
def rec_gen(n = 0) :
if n == omega :
yield 1
else :
pows = [1]
for j in xrange(factors.count(ps[n])) :
pows += [pows[-1] * ps[n]]
for q in rec_gen(n + 1) :
for p in pows :
yield p * q
for p in rec_gen() :
yield p
```
Note that the way it is written, it takes a list of prime factors, not a dictionary, i.e. `[2, 2, 2, 3, 3, 5]` instead of `{2 : 3, 3 : 2, 5 : 1}`. | Python factorization | [
"",
"python",
"algorithm",
""
] |
Hey, I'm currently trying to send an image file to a web server using a web request, a memory stream and an image object.
This is my current method for sending the request:
```
public void Send(Image image)
{
//Assign the request here too, just in case
Request = (HttpWebRequest)WebRequest.Create(FormURL);
Request.Method = "POST";
Request.ContentType = "multipart/form-data; boundary=" + CONTENT_BOUNDARY;
Request.Headers.Add("Cache-Control", "no-cache");
Request.KeepAlive = true;
Request.ContentLength = GetFormElements().Length +
GetFileHeader(FileName).Length +
FILE_TRAIL.Length +
ConvertImageToByteArray(image).Length;
//Must be done in this order for stream to write properly:
//----
//Form elements
//File header
//Image
//File trailer
//----
WriteStringToStream(FileStream, GetFormElements());
WriteStringToStream(FileStream, GetFileHeader(FileName));
WriteImageToStream(FileStream, image);
WriteStringToStream(FileStream, FILE_TRAIL);
string PostData = ASCIIEncoding.ASCII.GetString(ConvertImageToByteArray(image));
StreamWriter SW = new StreamWriter(Request.GetRequestStream(), Encoding.ASCII);
SW.Write(PostData);
GetRequestResponse();
Console.WriteLine(Request.HaveResponse);
FileStream.Close();
Request = null;
}
```
The problem I am having is that I'm not getting ANY response from the server at all, despite the stream being what looks to be a correct length (I removed some debug outputs from the code above)
If necessary, I can post other parts of my class, but for now here are the writing functions:
WriteStringToStream:
```
private void WriteStringToStream(System.IO.MemoryStream stream, string String)
{
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(String);
stream.Write(PostData, 0, PostData.Length);
}
```
WriteImageToSteam:
```
private void WriteImageToStream(System.IO.MemoryStream Stream, Image img)
{
Stream.Write(ConvertImageToByteArray(img), 0, ConvertImageToByteArray(img).Length);
}
```
ConvertImageToByteArray:
```
private Byte[] ConvertImageToByteArray(Image img)
{
//Method taken from http://www.csharp-station.com/Articles/Thumbnails.aspx and adapted
MemoryStream memStream = new MemoryStream();
img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteArray = new Byte[memStream.Length];
memStream.Position = 0;
memStream.Read(byteArray, 0, (int)memStream.Length);
return byteArray;
}
``` | Problem solved :) I now have a response - even if it isn't what I was expecting ... | You should close SW before sending the request.
Also, instead of converting the byte array to ASCII and then writing it to a StreamWriter, you should write the byte array directly to the request stream. (And then close the request stream before sending the request) | C# read image object in to web request | [
"",
"c#",
"image",
"httpwebrequest",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.