qid
int64 1
3.11M
| question
stringlengths 10
32.1k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
33.7k
| response_k
stringlengths 3
34.7k
|
---|---|---|---|---|---|
509,662 | I am considering porting a small portion of the code in a C# project of mine to C/ASM for performance benefits. (This section of code uses many bitwise operations and is one of the few places where there may exist a real performance increase by using native code.) I then plan to simply call the native function in the separate DLL via P/Invoke. Now, the only data that will be passed between the managed and native code will be purely primitive types (bool, int, long, 1D arrays, etc.). So my question is: will there be any significant overhead using P/invoke simply with primitive types? I am aware that there is a substatial overhead when using more complex types, since they need to be marshalled (pinned/copied), but perhaps in my situation it will be relatively efficient (compared to calling the code from within the native DLL itself even)? If someone could clarify this matter for me, explaining the degrees of performance advantages/hits and the reasons behind them, it would be much appreciated. An alternative way to accomplish the whole task would also be welcome, though since C# lacks support for inline assembly/CIL, I don't believe there is one. | 2009/02/04 | [
"https://Stackoverflow.com/questions/509662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44389/"
] | From MSDN (<http://msdn.microsoft.com/en-us/library/aa712982.aspx>):
"PInvoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between int and Int32."
So, it's reasonably cheap, but as always you should measure carefully to be sure you are benefitting from it, and bear in mind any maintenance overhead. As an aside, I would recommend C++/CLI ("managed" C++) over P/Invoke for any complex interop, especially if you're comfortable with C++. | I would personally setup a test harness with a simple expression written in C# and unmanaged C++, then profile the app to see what kind of performance delta you're working with.
Something else to consider is that you'd be introducing a maintenance issue with the app, especially if you have junior-level developers expected to maintain the code. Make sure you know what you're gaining and what what you're losing respective to performance as well as code-clarity and maintainability.
As an aside, JIT'd C# code should have performance on par with C++ with respect to arithmetic operations. |
509,662 | I am considering porting a small portion of the code in a C# project of mine to C/ASM for performance benefits. (This section of code uses many bitwise operations and is one of the few places where there may exist a real performance increase by using native code.) I then plan to simply call the native function in the separate DLL via P/Invoke. Now, the only data that will be passed between the managed and native code will be purely primitive types (bool, int, long, 1D arrays, etc.). So my question is: will there be any significant overhead using P/invoke simply with primitive types? I am aware that there is a substatial overhead when using more complex types, since they need to be marshalled (pinned/copied), but perhaps in my situation it will be relatively efficient (compared to calling the code from within the native DLL itself even)? If someone could clarify this matter for me, explaining the degrees of performance advantages/hits and the reasons behind them, it would be much appreciated. An alternative way to accomplish the whole task would also be welcome, though since C# lacks support for inline assembly/CIL, I don't believe there is one. | 2009/02/04 | [
"https://Stackoverflow.com/questions/509662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44389/"
] | I would personally setup a test harness with a simple expression written in C# and unmanaged C++, then profile the app to see what kind of performance delta you're working with.
Something else to consider is that you'd be introducing a maintenance issue with the app, especially if you have junior-level developers expected to maintain the code. Make sure you know what you're gaining and what what you're losing respective to performance as well as code-clarity and maintainability.
As an aside, JIT'd C# code should have performance on par with C++ with respect to arithmetic operations. | This link provides some insights: <http://www.codeproject.com/Articles/253444/PInvoke-Performance>
Also note the performance difference when [SuppressUnmanagedCodeSecurity] attribute is applied. |
509,662 | I am considering porting a small portion of the code in a C# project of mine to C/ASM for performance benefits. (This section of code uses many bitwise operations and is one of the few places where there may exist a real performance increase by using native code.) I then plan to simply call the native function in the separate DLL via P/Invoke. Now, the only data that will be passed between the managed and native code will be purely primitive types (bool, int, long, 1D arrays, etc.). So my question is: will there be any significant overhead using P/invoke simply with primitive types? I am aware that there is a substatial overhead when using more complex types, since they need to be marshalled (pinned/copied), but perhaps in my situation it will be relatively efficient (compared to calling the code from within the native DLL itself even)? If someone could clarify this matter for me, explaining the degrees of performance advantages/hits and the reasons behind them, it would be much appreciated. An alternative way to accomplish the whole task would also be welcome, though since C# lacks support for inline assembly/CIL, I don't believe there is one. | 2009/02/04 | [
"https://Stackoverflow.com/questions/509662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44389/"
] | From MSDN (<http://msdn.microsoft.com/en-us/library/aa712982.aspx>):
"PInvoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between int and Int32."
So, it's reasonably cheap, but as always you should measure carefully to be sure you are benefitting from it, and bear in mind any maintenance overhead. As an aside, I would recommend C++/CLI ("managed" C++) over P/Invoke for any complex interop, especially if you're comfortable with C++. | This link provides some insights: <http://www.codeproject.com/Articles/253444/PInvoke-Performance>
Also note the performance difference when [SuppressUnmanagedCodeSecurity] attribute is applied. |
621,396 | I did the mistake of creating my entire web application and not testing it on IE along the way. I only tested it on Firefox and Safari. The web app runs fine on both Safari and Firefox but it gives a Permission Denied error on IE.
I am using Google AuthSub authentication and so for authenticating using Google Account, it first redirects to allow the app access to Google Account. After authentication, IE changes 'http' to 'https'. This does not happen with either Firefox or Safari. They remain with the 'http' protocol.
IE then gives a Permission Denied error. Is the JavaScript conflicting with 'https' in any way?
The app is here -> <http://ankitahuja.com/apps/proxycal>
and the error-causing page is -> <http://ankitahuja.com/apps/proxycal/proxycal.php> | 2009/03/07 | [
"https://Stackoverflow.com/questions/621396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73731/"
] | When I open up the proxycal.php page in both IE and FF, an error is raised on this line in the Javascript (in `function _run`):
```
calendarService = new google.gdata.calendar.CalendarService('proxycal');
```
Here, `calendar` is not a member of `google.gdata`.
I suggest you debug through the call stack to find out what is not being initialized. | In IE you can use `XDomainRequest`, but not for https from http, which is blocked and [This is an expected by-design behavior](https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=333380) (though not expected in FF/Chrome) |
621,396 | I did the mistake of creating my entire web application and not testing it on IE along the way. I only tested it on Firefox and Safari. The web app runs fine on both Safari and Firefox but it gives a Permission Denied error on IE.
I am using Google AuthSub authentication and so for authenticating using Google Account, it first redirects to allow the app access to Google Account. After authentication, IE changes 'http' to 'https'. This does not happen with either Firefox or Safari. They remain with the 'http' protocol.
IE then gives a Permission Denied error. Is the JavaScript conflicting with 'https' in any way?
The app is here -> <http://ankitahuja.com/apps/proxycal>
and the error-causing page is -> <http://ankitahuja.com/apps/proxycal/proxycal.php> | 2009/03/07 | [
"https://Stackoverflow.com/questions/621396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73731/"
] | I've run into that error before in IE. Most often, it was because I was fetching data from another domain using `XmlHttpRequest`. Check the "allow data from other domains" setting in IE's Internet Options, make sure it's allowed and then see if you get the same error. | In IE you can use `XDomainRequest`, but not for https from http, which is blocked and [This is an expected by-design behavior](https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=333380) (though not expected in FF/Chrome) |
896,602 | I am some ATL code that uses smart COM pointers to iterate through MS Outlook contacts, and on some PC's I am getting a COM error 0x80004003 ('Invalid Pointer') for each contact. The same code works fine on other PCs. The code looks like this:
```
_ApplicationPtr ptr;
ptr.CreateInstance(CLSID_Application);
_NameSpacePtr ns = ptr->GetNamespace(_T("MAPI"));
MAPIFolderPtr folder = ns->GetDefaultFolder(olFolderContacts);
_ItemsPtr items = folder->Items;
const long count = items->GetCount();
for (long i = 1; i <= count; i++)
{
try
{
_ContactItemPtr contactitem = items->Item(i);
// The following line throws a 0x80004003 exception on some machines
ATLTRACE(_T("\tContact name: %s\n"), static_cast<LPCTSTR>(contactitem->FullName));
}
catch (const _com_error& e)
{
ATLTRACE(_T("%s\n"), e.ErrorMessage());
}
}
```
I wonder if any other applications/add-ins could be causing this? Any help would be welcome. | 2009/05/22 | [
"https://Stackoverflow.com/questions/896602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | FullName is a property and you do the GET operation (it's probably something like this in IDL: get\_FullName([out,retval] BSTR \*o\_sResult)). Such operation works ok with null values.
My assumption is that `contactItem` smart pointer points to any valid COM object. In such case the formatting operation done by `ATLTRACE` can cause the problem. Internally it behaves probably like standard `sprintf("",args...)` function.
To avoid such problems just do something like below:
```
ATLTRACE(_T("\tContact name: %s\n"),
_bstr_t(contactitem->FullName)?static_cast<LPCTSTR>(contactitem->FullName):"(Empty)")
``` | Just a guess:
Maybe the "FullName" field in the address book is empty and that's why the pointer is invalid?
hard to tell, because your code doesn't indicate which COM-interfaces you're using. |
896,602 | I am some ATL code that uses smart COM pointers to iterate through MS Outlook contacts, and on some PC's I am getting a COM error 0x80004003 ('Invalid Pointer') for each contact. The same code works fine on other PCs. The code looks like this:
```
_ApplicationPtr ptr;
ptr.CreateInstance(CLSID_Application);
_NameSpacePtr ns = ptr->GetNamespace(_T("MAPI"));
MAPIFolderPtr folder = ns->GetDefaultFolder(olFolderContacts);
_ItemsPtr items = folder->Items;
const long count = items->GetCount();
for (long i = 1; i <= count; i++)
{
try
{
_ContactItemPtr contactitem = items->Item(i);
// The following line throws a 0x80004003 exception on some machines
ATLTRACE(_T("\tContact name: %s\n"), static_cast<LPCTSTR>(contactitem->FullName));
}
catch (const _com_error& e)
{
ATLTRACE(_T("%s\n"), e.ErrorMessage());
}
}
```
I wonder if any other applications/add-ins could be causing this? Any help would be welcome. | 2009/05/22 | [
"https://Stackoverflow.com/questions/896602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | FullName is a property and you do the GET operation (it's probably something like this in IDL: get\_FullName([out,retval] BSTR \*o\_sResult)). Such operation works ok with null values.
My assumption is that `contactItem` smart pointer points to any valid COM object. In such case the formatting operation done by `ATLTRACE` can cause the problem. Internally it behaves probably like standard `sprintf("",args...)` function.
To avoid such problems just do something like below:
```
ATLTRACE(_T("\tContact name: %s\n"),
_bstr_t(contactitem->FullName)?static_cast<LPCTSTR>(contactitem->FullName):"(Empty)")
``` | Does this make any difference?
```
ATLTRACE(_T("\tContact name: %s\n"), static_cast<LPCTSTR>(contactitem->GetFullName()));
``` |
896,602 | I am some ATL code that uses smart COM pointers to iterate through MS Outlook contacts, and on some PC's I am getting a COM error 0x80004003 ('Invalid Pointer') for each contact. The same code works fine on other PCs. The code looks like this:
```
_ApplicationPtr ptr;
ptr.CreateInstance(CLSID_Application);
_NameSpacePtr ns = ptr->GetNamespace(_T("MAPI"));
MAPIFolderPtr folder = ns->GetDefaultFolder(olFolderContacts);
_ItemsPtr items = folder->Items;
const long count = items->GetCount();
for (long i = 1; i <= count; i++)
{
try
{
_ContactItemPtr contactitem = items->Item(i);
// The following line throws a 0x80004003 exception on some machines
ATLTRACE(_T("\tContact name: %s\n"), static_cast<LPCTSTR>(contactitem->FullName));
}
catch (const _com_error& e)
{
ATLTRACE(_T("%s\n"), e.ErrorMessage());
}
}
```
I wonder if any other applications/add-ins could be causing this? Any help would be welcome. | 2009/05/22 | [
"https://Stackoverflow.com/questions/896602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | FullName is a property and you do the GET operation (it's probably something like this in IDL: get\_FullName([out,retval] BSTR \*o\_sResult)). Such operation works ok with null values.
My assumption is that `contactItem` smart pointer points to any valid COM object. In such case the formatting operation done by `ATLTRACE` can cause the problem. Internally it behaves probably like standard `sprintf("",args...)` function.
To avoid such problems just do something like below:
```
ATLTRACE(_T("\tContact name: %s\n"),
_bstr_t(contactitem->FullName)?static_cast<LPCTSTR>(contactitem->FullName):"(Empty)")
``` | In my example you format NULL value to a proper text value.
If the question is about the difference between FullName(as a property) and GetFullName() (as a method) then the answer is no. Property and method should give the same result. Sometimes property can be mapped to different methods then setXXX and getXXX. It can be achieved by using some specific syntax in IDL (and in reality in TLB after compilation of IDL to TLB). If property FullName is not mapped to method GetFullName then you will achieve different result.
So please examine file \*.tlh after importing some type library to your project... |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies. | Does your ASPX have the event handler wired up?
```
<asp:Button id="btnCommand" runat="server" onClick="b_Command" text="Submit" />
``` |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies. | The buttons need to be created *before* the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.
As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event will know it needs to run.
Alternatively, you could place the buttons on the page statically. Just put enough there to handle whatever the search returns. If you're thinking that maybe that would be *way* too many items, then ask your self this: will your users really want to sort through that many items? Maybe you should consider paging this data, in which case static buttons aren't as big a deal any more. |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The buttons need to be created *before* the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.
As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event will know it needs to run.
Alternatively, you could place the buttons on the page statically. Just put enough there to handle whatever the search returns. If you're thinking that maybe that would be *way* too many items, then ask your self this: will your users really want to sort through that many items? Maybe you should consider paging this data, in which case static buttons aren't as big a deal any more. | Does your ASPX have the event handler wired up?
```
<asp:Button id="btnCommand" runat="server" onClick="b_Command" text="Submit" />
``` |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | What happens when the postback event handling tries to find the control it dosen't exists on the collection.
Checkout Denis DynamicControlsPlaceholder @ <http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx>
Hope it helps
Bruno Figueiredo
<http://www.brunofigueiredo.com> | Does your ASPX have the event handler wired up?
```
<asp:Button id="btnCommand" runat="server" onClick="b_Command" text="Submit" />
``` |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies. | What happens when the postback event handling tries to find the control it dosen't exists on the collection.
Checkout Denis DynamicControlsPlaceholder @ <http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx>
Hope it helps
Bruno Figueiredo
<http://www.brunofigueiredo.com> |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies. | I agree with Joel about caching the search results. As for the buttons you can create them dynamically at the init or load phases of the page lifecycle but be aware that if you remove a button and then add it back programmatically you will mess up your state.
In one of my projects we have a dynamic form that generates field son the fly and the way we make it work is through an array that is stored in the cache or in the viewstate for the page. The array contains the buttons to display and on each page load it re-creates the buttons so that state can be loaded properly into them. Then if I need more buttons or a whole new set I flag the hide value in the array and add a new set of values in the array for the new set of corresponding buttons. This way state is not lost and the buttons continue to work.
You also need to ensure that you add a handler for the on\_click event for your buttons if you create them programmatically which I think I see in your code up at the top. |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The buttons need to be created *before* the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.
As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event will know it needs to run.
Alternatively, you could place the buttons on the page statically. Just put enough there to handle whatever the search returns. If you're thinking that maybe that would be *way* too many items, then ask your self this: will your users really want to sort through that many items? Maybe you should consider paging this data, in which case static buttons aren't as big a deal any more. | Here is a sample with custom viewstate handling (note that buttons have `EnableViewState = false`):
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Execute heavy search 1 to generate buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" }
};
}
AddButtons();
}
void b_Command(object sender, CommandEventArgs e)
{
TextBox1.Text = ((Button)sender).Text;
// Execute heavy search 2 to generate new buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" },
new ButtonState() { ID = "Btn2", Text = "Selection 2" }
};
AddButtons();
}
private void AddButtons()
{
Panel1.Controls.Clear();
foreach (ButtonState buttonState in this.ButtonTexts)
{
Button b = new Button();
b.EnableViewState = false;
b.ID = buttonState.ID;
b.Text = buttonState.Text;
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
private ButtonState[] ButtonTexts
{
get
{
ButtonState[] list = ViewState["ButtonTexts"] as ButtonState[];
if (list == null)
ButtonTexts = new ButtonState[0];
return list;
}
set { ViewState["ButtonTexts"] = value; }
}
[Serializable]
class ButtonState
{
public string ID { get; set; }
public string Text { get; set; }
}
``` |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | What happens when the postback event handling tries to find the control it dosen't exists on the collection.
Checkout Denis DynamicControlsPlaceholder @ <http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx>
Hope it helps
Bruno Figueiredo
<http://www.brunofigueiredo.com> | I agree with Joel about caching the search results. As for the buttons you can create them dynamically at the init or load phases of the page lifecycle but be aware that if you remove a button and then add it back programmatically you will mess up your state.
In one of my projects we have a dynamic form that generates field son the fly and the way we make it work is through an array that is stored in the cache or in the viewstate for the page. The array contains the buttons to display and on each page load it re-creates the buttons so that state can be loaded properly into them. Then if I need more buttons or a whole new set I flag the hide value in the array and add a new set of values in the array for the new set of corresponding buttons. This way state is not lost and the buttons continue to work.
You also need to ensure that you add a handler for the on\_click event for your buttons if you create them programmatically which I think I see in your code up at the top. |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page.
If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).
so your code would become something like:
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.recreateButtons();
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
//store this stuff in ViewState for the very first time
}
}
void b_Command(object sender, CommandEventArgs e)
{
//Execute heavy search 2 to generate new buttons
//TODO: store data into ViewState or Session
//and maybe create some new buttons
}
void recreateButtons()
{
//retrieve data from ViewState or Session and create all the buttons
//wiring them up to eventHandler
}
}
}
```
If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies. | Here is a sample with custom viewstate handling (note that buttons have `EnableViewState = false`):
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Execute heavy search 1 to generate buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" }
};
}
AddButtons();
}
void b_Command(object sender, CommandEventArgs e)
{
TextBox1.Text = ((Button)sender).Text;
// Execute heavy search 2 to generate new buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" },
new ButtonState() { ID = "Btn2", Text = "Selection 2" }
};
AddButtons();
}
private void AddButtons()
{
Panel1.Controls.Clear();
foreach (ButtonState buttonState in this.ButtonTexts)
{
Button b = new Button();
b.EnableViewState = false;
b.ID = buttonState.ID;
b.Text = buttonState.Text;
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
private ButtonState[] ButtonTexts
{
get
{
ButtonState[] list = ViewState["ButtonTexts"] as ButtonState[];
if (list == null)
ButtonTexts = new ButtonState[0];
return list;
}
set { ViewState["ButtonTexts"] = value; }
}
[Serializable]
class ButtonState
{
public string ID { get; set; }
public string Text { get; set; }
}
``` |
272,928 | I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?
```
namespace CloudNavigation
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// how can I re-generate the button and hook up the event here
// without executing heavy search 1
}
else
{
// Execute heavy search 1 to generate buttons
Button b = new Button();
b.Text = "Selection 1";
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
void b_Command(object sender, CommandEventArgs e)
{
// Execute heavy search 2 to generate new buttons
Button b2 = new Button();
b2.Text = "Selection 2";
b2.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b2);
}
}
}
``` | 2008/11/07 | [
"https://Stackoverflow.com/questions/272928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] | What happens when the postback event handling tries to find the control it dosen't exists on the collection.
Checkout Denis DynamicControlsPlaceholder @ <http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx>
Hope it helps
Bruno Figueiredo
<http://www.brunofigueiredo.com> | Here is a sample with custom viewstate handling (note that buttons have `EnableViewState = false`):
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Execute heavy search 1 to generate buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" }
};
}
AddButtons();
}
void b_Command(object sender, CommandEventArgs e)
{
TextBox1.Text = ((Button)sender).Text;
// Execute heavy search 2 to generate new buttons
ButtonTexts = new ButtonState[] {
new ButtonState() { ID = "Btn1", Text = "Selection 1" },
new ButtonState() { ID = "Btn2", Text = "Selection 2" }
};
AddButtons();
}
private void AddButtons()
{
Panel1.Controls.Clear();
foreach (ButtonState buttonState in this.ButtonTexts)
{
Button b = new Button();
b.EnableViewState = false;
b.ID = buttonState.ID;
b.Text = buttonState.Text;
b.Command += new CommandEventHandler(b_Command);
Panel1.Controls.Add(b);
}
}
private ButtonState[] ButtonTexts
{
get
{
ButtonState[] list = ViewState["ButtonTexts"] as ButtonState[];
if (list == null)
ButtonTexts = new ButtonState[0];
return list;
}
set { ViewState["ButtonTexts"] = value; }
}
[Serializable]
class ButtonState
{
public string ID { get; set; }
public string Text { get; set; }
}
``` |
2,974,916 | does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of `(with-profiling ...)` in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2974916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207663/"
] | I found VisualVM (see [here](https://visualvm.dev.java.net/) and [here](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html)) to be very convenient. Its use with Clojure has been described about a year ago in [this blog post](http://www.fatvat.co.uk/2009/05/jvisualvm-and-clojure.html); as far as I can see, it's not outdated in any way.
Note that the GUI from which one starts the VisualVM profiler has a prominent text area where one can enter classes / packages to be excluded from profiling -- I find the results rather more useful when `clojure.*` is on that list. | Just found [`profile` in Clojure contrib](http://richhickey.github.com/clojure-contrib/#profile).
It doesn't work for large amounts of code (it blew up with OutOfMemoryError on a Project Euler solution which VisualVM handled just fine) and it requires you to insert profiling calls in the functions you want to profile.
Still, it's a better alternative to VisualVM in the cases where you just want to profile a couple of functions. |
2,974,916 | does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of `(with-profiling ...)` in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2974916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207663/"
] | I found VisualVM (see [here](https://visualvm.dev.java.net/) and [here](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html)) to be very convenient. Its use with Clojure has been described about a year ago in [this blog post](http://www.fatvat.co.uk/2009/05/jvisualvm-and-clojure.html); as far as I can see, it's not outdated in any way.
Note that the GUI from which one starts the VisualVM profiler has a prominent text area where one can enter classes / packages to be excluded from profiling -- I find the results rather more useful when `clojure.*` is on that list. | There's a newish Clojure library which offers profiling: <https://github.com/ptaoussanis/timbre> |
2,974,916 | does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of `(with-profiling ...)` in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2974916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207663/"
] | I found VisualVM (see [here](https://visualvm.dev.java.net/) and [here](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html)) to be very convenient. Its use with Clojure has been described about a year ago in [this blog post](http://www.fatvat.co.uk/2009/05/jvisualvm-and-clojure.html); as far as I can see, it's not outdated in any way.
Note that the GUI from which one starts the VisualVM profiler has a prominent text area where one can enter classes / packages to be excluded from profiling -- I find the results rather more useful when `clojure.*` is on that list. | Quick heads-up that I've deprecated Timbre's profiling for a new dedicated Clojure + ClojureScript profiling lib at <https://github.com/ptaoussanis/tufte>.
That's basically a refinement of the stuff from Timbre, plus dedicated docs.
The README includes a [comparison](https://github.com/ptaoussanis/tufte#why-not-just-use-yourkit-jprofiler-or-visualvm) with JVM tools like VisualVM, YourKit, etc. |
2,974,916 | does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of `(with-profiling ...)` in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2974916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207663/"
] | There's a newish Clojure library which offers profiling: <https://github.com/ptaoussanis/timbre> | Just found [`profile` in Clojure contrib](http://richhickey.github.com/clojure-contrib/#profile).
It doesn't work for large amounts of code (it blew up with OutOfMemoryError on a Project Euler solution which VisualVM handled just fine) and it requires you to insert profiling calls in the functions you want to profile.
Still, it's a better alternative to VisualVM in the cases where you just want to profile a couple of functions. |
2,974,916 | does anyone know of a good profiling tool or library for Clojure?
I would prefer something that could be used from the REPL, along the lines of `(with-profiling ...)` in Allegro Common Lisp back in the day.
Is there anything along those lines?
Or do you have any experience with (non-commercial) Java profilers that work well with Clojure? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2974916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207663/"
] | There's a newish Clojure library which offers profiling: <https://github.com/ptaoussanis/timbre> | Quick heads-up that I've deprecated Timbre's profiling for a new dedicated Clojure + ClojureScript profiling lib at <https://github.com/ptaoussanis/tufte>.
That's basically a refinement of the stuff from Timbre, plus dedicated docs.
The README includes a [comparison](https://github.com/ptaoussanis/tufte#why-not-just-use-yourkit-jprofiler-or-visualvm) with JVM tools like VisualVM, YourKit, etc. |
1,024,437 | This is a snippet from Google AppEngine tutorial.
```
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
```
I'm not quite sure what **`debug=True`** does inside the constructor call.
Does it create a local variable with name `debug`, assign `True` to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor? | 2009/06/21 | [
"https://Stackoverflow.com/questions/1024437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126348/"
] | Python functions accept keyword arguments. If you define a function like so:
```
def my_func(a, b='abc', c='def'):
print a, b, c
```
You can call it like this:
```
my_func('hello', c='world')
```
And the result will be:
```
hello abc world
```
You can also support dynamic keyword arguments, using special syntax:
```
def my_other_func(a, *b, **c):
print a, b, c
```
* `*b` means that the `b` variable will take all non-named arguments after `a`, as a `tuple` object.
* `**c` means that the `c` variable will take all named arguments, as a `dict` object.
If you call the function like this:
```
my_other_func('hello', 'world', 'what a', state='fine', what='day')
```
You will get:
```
hello ('world', 'what a') {'state': 'fine', 'what': 'day'}
``` | It's using named arguments. See [Using Optional and Named Arguments](http://diveintopython.net/power_of_introspection/optional_arguments.html). |
1,024,437 | This is a snippet from Google AppEngine tutorial.
```
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
```
I'm not quite sure what **`debug=True`** does inside the constructor call.
Does it create a local variable with name `debug`, assign `True` to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor? | 2009/06/21 | [
"https://Stackoverflow.com/questions/1024437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126348/"
] | Python functions accept keyword arguments. If you define a function like so:
```
def my_func(a, b='abc', c='def'):
print a, b, c
```
You can call it like this:
```
my_func('hello', c='world')
```
And the result will be:
```
hello abc world
```
You can also support dynamic keyword arguments, using special syntax:
```
def my_other_func(a, *b, **c):
print a, b, c
```
* `*b` means that the `b` variable will take all non-named arguments after `a`, as a `tuple` object.
* `**c` means that the `c` variable will take all named arguments, as a `dict` object.
If you call the function like this:
```
my_other_func('hello', 'world', 'what a', state='fine', what='day')
```
You will get:
```
hello ('world', 'what a') {'state': 'fine', 'what': 'day'}
``` | Neither -- rather, `webapp.WSGIApplication` takes an optional argument named `debug`, and this code is passing the value `True` for that parameter.
The reference page for `WSGIApplication` is [here](http://code.google.com/appengine/docs/python/tools/webapp/wsgiapplicationclass.html) and it clearly shows the optional `debug` argument and the fact that it defaults to `False` unless explicitly passed in.
As the page further makes clear, passing `debug` as `True` means that helpful debugging information is shown to the browser if and when an exception occurs while handling the request.
How exactly that effect is obtained (in particular, whether it implies the existence of an attribute on the instance of `WSGIApplication`, or how that hypothetical attribute might be named) is an internal, undocumented implementation detail, which we're not supposed to worry about (of course, you can study the sources of `WSGIApplication` in the SDK if you *do* worry, or just want to learn more about one possible implementation of these specs!-). |
1,038,670 | I'm writing a query to do some stuff. But its not working the way I want it to:
```
select CORR_ID from TABLE1
where CORR_ID not in (select id from TABLE2)
```
The problem is, TABLE2.id is a long, while TABLE1.CORR\_ID is a string.
So how can I make it work?
PS: I'm using IBM UDB. | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119053/"
] | Okay, I found a method:
```
select CORR_ID from TABLE1 where CORR_ID not in
(select CAST( CAST(id AS CHAR(50)) AS VARCHAR(50) ) from TABLE2)
```
This is pretty intriguing: You can't cast a BIGINT to VARCHAR, but:
* you can cast a BIGINT to CHAR
* and you can cast a CHAR TO VARCHAR
this is ridiculous! | You should be able to cast the selected id column to match the data type of corr\_id
select CORR\_ID from TABLE1
where CORR\_ID not in (select cast(id as varchar) from TABLE2) |
1,038,670 | I'm writing a query to do some stuff. But its not working the way I want it to:
```
select CORR_ID from TABLE1
where CORR_ID not in (select id from TABLE2)
```
The problem is, TABLE2.id is a long, while TABLE1.CORR\_ID is a string.
So how can I make it work?
PS: I'm using IBM UDB. | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119053/"
] | DB2 allows a VARCHAR and CHAR column to be compared without additional casting, so all you really need to do is cast the number.
SELECT corr\_id FROM table1 WHERE corr\_id NOT IN (SELECT CHAR( id ) FROM table2 ) | You should be able to cast the selected id column to match the data type of corr\_id
select CORR\_ID from TABLE1
where CORR\_ID not in (select cast(id as varchar) from TABLE2) |
1,038,670 | I'm writing a query to do some stuff. But its not working the way I want it to:
```
select CORR_ID from TABLE1
where CORR_ID not in (select id from TABLE2)
```
The problem is, TABLE2.id is a long, while TABLE1.CORR\_ID is a string.
So how can I make it work?
PS: I'm using IBM UDB. | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119053/"
] | Okay, I found a method:
```
select CORR_ID from TABLE1 where CORR_ID not in
(select CAST( CAST(id AS CHAR(50)) AS VARCHAR(50) ) from TABLE2)
```
This is pretty intriguing: You can't cast a BIGINT to VARCHAR, but:
* you can cast a BIGINT to CHAR
* and you can cast a CHAR TO VARCHAR
this is ridiculous! | DB2 allows a VARCHAR and CHAR column to be compared without additional casting, so all you really need to do is cast the number.
SELECT corr\_id FROM table1 WHERE corr\_id NOT IN (SELECT CHAR( id ) FROM table2 ) |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | You can use `performSelector:withObject:withDelay:` to wait for a given time to pass (create another method that has the code to do later.
However, this can introduce lots of subtle timing bugs, so I'd suggest using it for only the most extreme of cases.
I think you could probably do something with `viewDidAppear:` look for a flag that you've set in `didFinishPicking…` indicating that you're waiting for the imagePicker's animation to end. Since it's didAppear, the animations should be done by then. | I've encountered a similar issue with dismissModalViewController and it has been driving me nuts. The only way I've been able to deal with it is by doing something like this, which is similar to what was suggested above. I don't like this solution but I haven't been able to figure out how to avoid it.
```
if ([self retainCount] == 1)
[self dismissModalViewControllerAnimated:YES];
else {
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
}
- (void)onTimer:(NSTimer*)theTimer {
[self dismissModalViewControllerAnimated:YES];
[theTimer invalidate];
}
```
The problem I noticed is that here is a timing issue surrounding when some object releases its hold on the modal view controller. And if I call dismissModalViewController when the retainCount is still 2 then the call just fails...nothing happens. But if I wait a second, the retain count always drops down to 1 and then the call to dismissModalViewController succeeds. |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | You can use `performSelector:withObject:withDelay:` to wait for a given time to pass (create another method that has the code to do later.
However, this can introduce lots of subtle timing bugs, so I'd suggest using it for only the most extreme of cases.
I think you could probably do something with `viewDidAppear:` look for a flag that you've set in `didFinishPicking…` indicating that you're waiting for the imagePicker's animation to end. Since it's didAppear, the animations should be done by then. | While the transition is happening, all views reside on an intermediate view (of type `UITransitionView`). So just pick some outlet of which you know that it is a direct subview of the main window and check whether `!([[outlet superview] isKindOfClass:[UIWindow class]])` and delay the execution using `performSelector:withObject:withDelay:`, pass all the relevant information to call the same method you’re in and simply return.
As soon as the transition is finished, the condition will not be met anymore and the new animation can happen. This method is not prone to the timing complexities which can happen if you just call `performSelector:withObject:withDelay:` once.
I used this just recently and it works very well (I just happened to have an outlet to the main window which makes this even simpler):
```
//Called after [initialRootViewController dismissModalViewControllerAnimated:YES]
- (void)showTable {
if([initialRootViewController.view superview] != window) {
//View is still animating
[self performSelector:@selector(showTable) withObject:nil afterDelay:0.1];
return;
}
self.nibContents = [[NSBundle mainBundle] loadNibNamed:@"MainView" owner:self options:nil];
[UIView transitionFromView:initialRootViewController.view toView:rootViewController.view duration:0.3 options:UIViewAnimationOptionTransitionCurlUp|UIViewAnimationOptionBeginFromCurrentState completion:^(BOOL finished){
self.initialRootViewController = nil;
}];
}
``` |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | You can use `performSelector:withObject:withDelay:` to wait for a given time to pass (create another method that has the code to do later.
However, this can introduce lots of subtle timing bugs, so I'd suggest using it for only the most extreme of cases.
I think you could probably do something with `viewDidAppear:` look for a flag that you've set in `didFinishPicking…` indicating that you're waiting for the imagePicker's animation to end. Since it's didAppear, the animations should be done by then. | I am having a similar issue and believe it is a design issue. I would suggest instead of doing:
root vc presents image vc
root vc dismisses image vc
*[simultaneous dismiss and present cause problems here]*
root vc presents email vc
root vc dismisses email vc
You do:
root vc presents image vc
image vc presents email vc
root vc dismisses the vc stack
Keep in mind that dismissModalViewController can dismiss a whole stack of controllers to get to the caller. See the documentation for [UIViewController](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html).
vc = View Controller |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | You can use `performSelector:withObject:withDelay:` to wait for a given time to pass (create another method that has the code to do later.
However, this can introduce lots of subtle timing bugs, so I'd suggest using it for only the most extreme of cases.
I think you could probably do something with `viewDidAppear:` look for a flag that you've set in `didFinishPicking…` indicating that you're waiting for the imagePicker's animation to end. Since it's didAppear, the animations should be done by then. | I am using an image picker and dismissModalViewControllerAnimated is undoing one of my objects. I found that I have to save and restore my value.
This is what worked for me (Group and BigBlockViewController are my classes):
```
Group *workAround = bigBlockViewController.selectedGroup;
[picker dismissModalViewControllerAnimated:YES];
bigBlockViewController.selectedGroup = workaround;
```
My photo picker is performed from a flipsideViewController |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | I've encountered a similar issue with dismissModalViewController and it has been driving me nuts. The only way I've been able to deal with it is by doing something like this, which is similar to what was suggested above. I don't like this solution but I haven't been able to figure out how to avoid it.
```
if ([self retainCount] == 1)
[self dismissModalViewControllerAnimated:YES];
else {
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
}
- (void)onTimer:(NSTimer*)theTimer {
[self dismissModalViewControllerAnimated:YES];
[theTimer invalidate];
}
```
The problem I noticed is that here is a timing issue surrounding when some object releases its hold on the modal view controller. And if I call dismissModalViewController when the retainCount is still 2 then the call just fails...nothing happens. But if I wait a second, the retain count always drops down to 1 and then the call to dismissModalViewController succeeds. | I am having a similar issue and believe it is a design issue. I would suggest instead of doing:
root vc presents image vc
root vc dismisses image vc
*[simultaneous dismiss and present cause problems here]*
root vc presents email vc
root vc dismisses email vc
You do:
root vc presents image vc
image vc presents email vc
root vc dismisses the vc stack
Keep in mind that dismissModalViewController can dismiss a whole stack of controllers to get to the caller. See the documentation for [UIViewController](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html).
vc = View Controller |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | I've encountered a similar issue with dismissModalViewController and it has been driving me nuts. The only way I've been able to deal with it is by doing something like this, which is similar to what was suggested above. I don't like this solution but I haven't been able to figure out how to avoid it.
```
if ([self retainCount] == 1)
[self dismissModalViewControllerAnimated:YES];
else {
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
}
- (void)onTimer:(NSTimer*)theTimer {
[self dismissModalViewControllerAnimated:YES];
[theTimer invalidate];
}
```
The problem I noticed is that here is a timing issue surrounding when some object releases its hold on the modal view controller. And if I call dismissModalViewController when the retainCount is still 2 then the call just fails...nothing happens. But if I wait a second, the retain count always drops down to 1 and then the call to dismissModalViewController succeeds. | I am using an image picker and dismissModalViewControllerAnimated is undoing one of my objects. I found that I have to save and restore my value.
This is what worked for me (Group and BigBlockViewController are my classes):
```
Group *workAround = bigBlockViewController.selectedGroup;
[picker dismissModalViewControllerAnimated:YES];
bigBlockViewController.selectedGroup = workaround;
```
My photo picker is performed from a flipsideViewController |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | While the transition is happening, all views reside on an intermediate view (of type `UITransitionView`). So just pick some outlet of which you know that it is a direct subview of the main window and check whether `!([[outlet superview] isKindOfClass:[UIWindow class]])` and delay the execution using `performSelector:withObject:withDelay:`, pass all the relevant information to call the same method you’re in and simply return.
As soon as the transition is finished, the condition will not be met anymore and the new animation can happen. This method is not prone to the timing complexities which can happen if you just call `performSelector:withObject:withDelay:` once.
I used this just recently and it works very well (I just happened to have an outlet to the main window which makes this even simpler):
```
//Called after [initialRootViewController dismissModalViewControllerAnimated:YES]
- (void)showTable {
if([initialRootViewController.view superview] != window) {
//View is still animating
[self performSelector:@selector(showTable) withObject:nil afterDelay:0.1];
return;
}
self.nibContents = [[NSBundle mainBundle] loadNibNamed:@"MainView" owner:self options:nil];
[UIView transitionFromView:initialRootViewController.view toView:rootViewController.view duration:0.3 options:UIViewAnimationOptionTransitionCurlUp|UIViewAnimationOptionBeginFromCurrentState completion:^(BOOL finished){
self.initialRootViewController = nil;
}];
}
``` | I am having a similar issue and believe it is a design issue. I would suggest instead of doing:
root vc presents image vc
root vc dismisses image vc
*[simultaneous dismiss and present cause problems here]*
root vc presents email vc
root vc dismisses email vc
You do:
root vc presents image vc
image vc presents email vc
root vc dismisses the vc stack
Keep in mind that dismissModalViewController can dismiss a whole stack of controllers to get to the caller. See the documentation for [UIViewController](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html).
vc = View Controller |
1,160,382 | I have a weird timing issue, it seems. I open a uiimagepicker as a modal view. When the user picks an image or I want to take the image, save it to a variable, then open an email interface as a modalview.
My problem is that I am calling dismissModalViewController on the imagepicker, then calling presentmodalviewcontroller for my email interface, but the imagepicker isn't going away in time for the email view to be presented. Is there a way to 'wait' for that line of code to complete?
```
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if( [[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"] ){
[self dismissModalViewControllerAnimated:YES];
imageFromCamera = [[UIImageView alloc] initWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[self presentModalViewController:mailView animated:YES];
[mailView release];
}
}
```
I'm pretty sure I've designed something wrong, but help me out if you can. | 2009/07/21 | [
"https://Stackoverflow.com/questions/1160382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142159/"
] | While the transition is happening, all views reside on an intermediate view (of type `UITransitionView`). So just pick some outlet of which you know that it is a direct subview of the main window and check whether `!([[outlet superview] isKindOfClass:[UIWindow class]])` and delay the execution using `performSelector:withObject:withDelay:`, pass all the relevant information to call the same method you’re in and simply return.
As soon as the transition is finished, the condition will not be met anymore and the new animation can happen. This method is not prone to the timing complexities which can happen if you just call `performSelector:withObject:withDelay:` once.
I used this just recently and it works very well (I just happened to have an outlet to the main window which makes this even simpler):
```
//Called after [initialRootViewController dismissModalViewControllerAnimated:YES]
- (void)showTable {
if([initialRootViewController.view superview] != window) {
//View is still animating
[self performSelector:@selector(showTable) withObject:nil afterDelay:0.1];
return;
}
self.nibContents = [[NSBundle mainBundle] loadNibNamed:@"MainView" owner:self options:nil];
[UIView transitionFromView:initialRootViewController.view toView:rootViewController.view duration:0.3 options:UIViewAnimationOptionTransitionCurlUp|UIViewAnimationOptionBeginFromCurrentState completion:^(BOOL finished){
self.initialRootViewController = nil;
}];
}
``` | I am using an image picker and dismissModalViewControllerAnimated is undoing one of my objects. I found that I have to save and restore my value.
This is what worked for me (Group and BigBlockViewController are my classes):
```
Group *workAround = bigBlockViewController.selectedGroup;
[picker dismissModalViewControllerAnimated:YES];
bigBlockViewController.selectedGroup = workaround;
```
My photo picker is performed from a flipsideViewController |
2,073,544 | How do I set the database name dynamically in a SQL Server stored procedure? | 2010/01/15 | [
"https://Stackoverflow.com/questions/2073544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748769/"
] | Stored Procedures are database specific. If you want to access data from another database dynamically, you are going to have to create dynamic SQL and execute it.
```
Declare @strSQL VarChar (MAX)
Declare @DatabaseNameParameter VarChar (100) = 'MyOtherDB'
SET @strSQL = 'SELECT * FROM ' + @DatabaseNameParameter + '.Schema.TableName'
```
You can use if clauses to set the `@DatabaseNameParameter` to the DB of your liking.
Execute the statement to get your results. | This is *not* dynamic SQL and works for stored procs
```
Declare @ThreePartName varchar (1000)
Declare @DatabaseNameParameter varchar (100)
SET @DatabaseNameParameter = 'MyOtherDB'
SET @ThreePartName = @DatabaseNameParameter + '.Schema.MyOtherSP'
EXEC @ThreePartName @p1, @p2... --Look! No brackets
``` |
2,073,544 | How do I set the database name dynamically in a SQL Server stored procedure? | 2010/01/15 | [
"https://Stackoverflow.com/questions/2073544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748769/"
] | Stored Procedures are database specific. If you want to access data from another database dynamically, you are going to have to create dynamic SQL and execute it.
```
Declare @strSQL VarChar (MAX)
Declare @DatabaseNameParameter VarChar (100) = 'MyOtherDB'
SET @strSQL = 'SELECT * FROM ' + @DatabaseNameParameter + '.Schema.TableName'
```
You can use if clauses to set the `@DatabaseNameParameter` to the DB of your liking.
Execute the statement to get your results. | Sometimes, the use of SYNONYMs is a good strategy:
```
CREATE SYNONYM [schema.]name FOR [[[linkedserver.]database.]schema.]name
```
Then, refer to the object by its synonym in your stored procedure.
Altering where the synonym points IS a matter of dynamic SQL, but then your main stored procedures can be totally dynamic SQL-free. Create a table to manage all the objects you need to reference, and a stored procedure that switches all the desired synonyms to the right context.
This functionality is only available in SQL Server 2005 and up.
This method will NOT be suitable for frequent switching or for situations where different connections need to use different databases. I use it for a database that occasionally moves around between servers (it can run in the prod database or on the replication database and they have different names). After restoring the database to its new home, I run my switcheroo SP on it and everything is working in about 8 seconds. |
2,073,544 | How do I set the database name dynamically in a SQL Server stored procedure? | 2010/01/15 | [
"https://Stackoverflow.com/questions/2073544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748769/"
] | Sometimes, the use of SYNONYMs is a good strategy:
```
CREATE SYNONYM [schema.]name FOR [[[linkedserver.]database.]schema.]name
```
Then, refer to the object by its synonym in your stored procedure.
Altering where the synonym points IS a matter of dynamic SQL, but then your main stored procedures can be totally dynamic SQL-free. Create a table to manage all the objects you need to reference, and a stored procedure that switches all the desired synonyms to the right context.
This functionality is only available in SQL Server 2005 and up.
This method will NOT be suitable for frequent switching or for situations where different connections need to use different databases. I use it for a database that occasionally moves around between servers (it can run in the prod database or on the replication database and they have different names). After restoring the database to its new home, I run my switcheroo SP on it and everything is working in about 8 seconds. | This is *not* dynamic SQL and works for stored procs
```
Declare @ThreePartName varchar (1000)
Declare @DatabaseNameParameter varchar (100)
SET @DatabaseNameParameter = 'MyOtherDB'
SET @ThreePartName = @DatabaseNameParameter + '.Schema.MyOtherSP'
EXEC @ThreePartName @p1, @p2... --Look! No brackets
``` |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | Usually, each of the users sends a HTTP request for the page. The server receives the requests and delegates them to different workers (processes or threads).
Depending on the URL given, the server reads a file and sends it back to the user. If the file is a dynamic file such as a PHP file, the file is executed before it's send back to the user.
Once the requested file has been sent back, the server usually closes the connection after a few seconds.
For more, see: [HowStuffWorks Web Servers](http://computer.howstuffworks.com/web-server2.htm) | Apache 2 has two different modes of operation. One is running as a [threaded server](http://en.wikipedia.org/wiki/Thread_(computer_science)) the other is using a mode called "prefork" ([multiple processes](http://en.wikipedia.org/wiki/Fork_(operating_system))). |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | Usually, each of the users sends a HTTP request for the page. The server receives the requests and delegates them to different workers (processes or threads).
Depending on the URL given, the server reads a file and sends it back to the user. If the file is a dynamic file such as a PHP file, the file is executed before it's send back to the user.
Once the requested file has been sent back, the server usually closes the connection after a few seconds.
For more, see: [HowStuffWorks Web Servers](http://computer.howstuffworks.com/web-server2.htm) | The requests will be processed simultaneously, to the best ability of the HTTP daemon.
Typically, the HTTP daemon will spawn either several processes or several threads and each one will handle one client request. The server may keep spare threads/processes so that when a client makes a request, it doesn't have to wait for the thread/process to be created. Each thread/process may be mapped to a different processor or core so that they can be processed more quickly. In most circumstances, however, what holds the requests is network I/O, not lack of raw computing, so there is frequently no slowdown from having a number of processors/cores significantly lower than the number of requests handled at one time. |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | Usually, each of the users sends a HTTP request for the page. The server receives the requests and delegates them to different workers (processes or threads).
Depending on the URL given, the server reads a file and sends it back to the user. If the file is a dynamic file such as a PHP file, the file is executed before it's send back to the user.
Once the requested file has been sent back, the server usually closes the connection after a few seconds.
For more, see: [HowStuffWorks Web Servers](http://computer.howstuffworks.com/web-server2.htm) | HTTP uses **TCP** which is a connection-based protocol. That is, clients establish a TCP connection while they're communicating with the server.
Multiple clients are allowed to connect to the same destination port on the same destination machine at the same time. The server just opens up multiple simultaneous connections.
Apache (and most other HTTP servers) have a multi-processing module (**MPM**). This is responsible for allocating Apache threads/processes to handle connections. These processes or threads can then run in parallel on their own connection, without blocking each other. Apache's MPM also tends to keep open "spare" threads or processes even when no connections are open, which helps speed up subsequent requests.
The program [**ab**](http://httpd.apache.org/docs/2.0/programs/ab.html) (short for ApacheBench) which comes with Apache lets you test what happens when you open up multiple connections to your HTTP server at once.
Apache's configuration files will normally set a limit for the number of simultaneous connections it will accept. This will be set to a reasonable number, such that during normal operation this limit should never be reached.
Note too that the HTTP protocol (from version 1.1) allows for a connection to be kept open, so that the client can make multiple HTTP requests before closing the connection, potentially reducing the number of simultaneous connections they need to make.
More on Apache's MPMs:
Apache itself can use a number of different multi-processing modules (MPMs). Apache 1.x normally used a module called "prefork", which creates a number of Apache processes in advance, so that incoming connections can often be sent to an existing process. This is as I described above.
Apache 2.x normally uses an MPM called "worker", which uses [**multithreading**](http://en.wikipedia.org/wiki/Thread_%28computer_science%29) (running multiple execution threads within a single process) to achieve the same thing. The advantage of multithreading over separate processes is that threading is a lot more light-weight compared to opening separate processes, and may even use a bit less memory. It's very fast.
The disadvantage of multithreading is you can't run things like mod\_php. When you're multithreading, all your add-in libraries need to be "thread-safe" - that is, they need to be aware of running in a multithreaded environment. It's harder to write a multi-threaded application. Because threads within a process share some memory/resources between them, this can easily create race condition bugs where threads read or write to memory when another thread is in the process of writing to it. Getting around this requires techniques such as [locking](http://en.wikipedia.org/wiki/Lock_%28computer_science%29). Many of PHP's built-in libraries are not thread-safe, so those wishing to use mod\_php cannot use Apache's "worker" MPM. |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | Usually, each of the users sends a HTTP request for the page. The server receives the requests and delegates them to different workers (processes or threads).
Depending on the URL given, the server reads a file and sends it back to the user. If the file is a dynamic file such as a PHP file, the file is executed before it's send back to the user.
Once the requested file has been sent back, the server usually closes the connection after a few seconds.
For more, see: [HowStuffWorks Web Servers](http://computer.howstuffworks.com/web-server2.htm) | The server (apache) is *multi-threaded*, meaning it can run multiple programs at once. A few years ago, a single CPU could switch back and forth quickly between multiple threads, giving on the appearance that two things were happening at once. These days, computers have multiple processors, so the computer can actually run two threads of code simultaneously. That being said, threads aren't really mapped to processors in any simple way.
With that ability, a PHP program can be thought of as a single thread of execution. If two requests reach the server at the same time, two threads can be used to process the request simultaneously. They will probably both get about the same amount of CPU, so if they are doing the same thing, they will complete at approximately the same time.
One of the most common issues with multi-threading is "race conditions"-- where you two requests are doing the same thing ("racing" to do the same thing), if it is a single resource, one of them is going to win. If they both insert a record into the database, they can't both get the same id-- one of them will win. So you need to be careful when writing code to realize other requests are going on at the same time and may modify your database, write files or change globals.
That being said, the programming model allows you to mostly ignore this complexity. |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | HTTP uses **TCP** which is a connection-based protocol. That is, clients establish a TCP connection while they're communicating with the server.
Multiple clients are allowed to connect to the same destination port on the same destination machine at the same time. The server just opens up multiple simultaneous connections.
Apache (and most other HTTP servers) have a multi-processing module (**MPM**). This is responsible for allocating Apache threads/processes to handle connections. These processes or threads can then run in parallel on their own connection, without blocking each other. Apache's MPM also tends to keep open "spare" threads or processes even when no connections are open, which helps speed up subsequent requests.
The program [**ab**](http://httpd.apache.org/docs/2.0/programs/ab.html) (short for ApacheBench) which comes with Apache lets you test what happens when you open up multiple connections to your HTTP server at once.
Apache's configuration files will normally set a limit for the number of simultaneous connections it will accept. This will be set to a reasonable number, such that during normal operation this limit should never be reached.
Note too that the HTTP protocol (from version 1.1) allows for a connection to be kept open, so that the client can make multiple HTTP requests before closing the connection, potentially reducing the number of simultaneous connections they need to make.
More on Apache's MPMs:
Apache itself can use a number of different multi-processing modules (MPMs). Apache 1.x normally used a module called "prefork", which creates a number of Apache processes in advance, so that incoming connections can often be sent to an existing process. This is as I described above.
Apache 2.x normally uses an MPM called "worker", which uses [**multithreading**](http://en.wikipedia.org/wiki/Thread_%28computer_science%29) (running multiple execution threads within a single process) to achieve the same thing. The advantage of multithreading over separate processes is that threading is a lot more light-weight compared to opening separate processes, and may even use a bit less memory. It's very fast.
The disadvantage of multithreading is you can't run things like mod\_php. When you're multithreading, all your add-in libraries need to be "thread-safe" - that is, they need to be aware of running in a multithreaded environment. It's harder to write a multi-threaded application. Because threads within a process share some memory/resources between them, this can easily create race condition bugs where threads read or write to memory when another thread is in the process of writing to it. Getting around this requires techniques such as [locking](http://en.wikipedia.org/wiki/Lock_%28computer_science%29). Many of PHP's built-in libraries are not thread-safe, so those wishing to use mod\_php cannot use Apache's "worker" MPM. | Apache 2 has two different modes of operation. One is running as a [threaded server](http://en.wikipedia.org/wiki/Thread_(computer_science)) the other is using a mode called "prefork" ([multiple processes](http://en.wikipedia.org/wiki/Fork_(operating_system))). |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | HTTP uses **TCP** which is a connection-based protocol. That is, clients establish a TCP connection while they're communicating with the server.
Multiple clients are allowed to connect to the same destination port on the same destination machine at the same time. The server just opens up multiple simultaneous connections.
Apache (and most other HTTP servers) have a multi-processing module (**MPM**). This is responsible for allocating Apache threads/processes to handle connections. These processes or threads can then run in parallel on their own connection, without blocking each other. Apache's MPM also tends to keep open "spare" threads or processes even when no connections are open, which helps speed up subsequent requests.
The program [**ab**](http://httpd.apache.org/docs/2.0/programs/ab.html) (short for ApacheBench) which comes with Apache lets you test what happens when you open up multiple connections to your HTTP server at once.
Apache's configuration files will normally set a limit for the number of simultaneous connections it will accept. This will be set to a reasonable number, such that during normal operation this limit should never be reached.
Note too that the HTTP protocol (from version 1.1) allows for a connection to be kept open, so that the client can make multiple HTTP requests before closing the connection, potentially reducing the number of simultaneous connections they need to make.
More on Apache's MPMs:
Apache itself can use a number of different multi-processing modules (MPMs). Apache 1.x normally used a module called "prefork", which creates a number of Apache processes in advance, so that incoming connections can often be sent to an existing process. This is as I described above.
Apache 2.x normally uses an MPM called "worker", which uses [**multithreading**](http://en.wikipedia.org/wiki/Thread_%28computer_science%29) (running multiple execution threads within a single process) to achieve the same thing. The advantage of multithreading over separate processes is that threading is a lot more light-weight compared to opening separate processes, and may even use a bit less memory. It's very fast.
The disadvantage of multithreading is you can't run things like mod\_php. When you're multithreading, all your add-in libraries need to be "thread-safe" - that is, they need to be aware of running in a multithreaded environment. It's harder to write a multi-threaded application. Because threads within a process share some memory/resources between them, this can easily create race condition bugs where threads read or write to memory when another thread is in the process of writing to it. Getting around this requires techniques such as [locking](http://en.wikipedia.org/wiki/Lock_%28computer_science%29). Many of PHP's built-in libraries are not thread-safe, so those wishing to use mod\_php cannot use Apache's "worker" MPM. | The requests will be processed simultaneously, to the best ability of the HTTP daemon.
Typically, the HTTP daemon will spawn either several processes or several threads and each one will handle one client request. The server may keep spare threads/processes so that when a client makes a request, it doesn't have to wait for the thread/process to be created. Each thread/process may be mapped to a different processor or core so that they can be processed more quickly. In most circumstances, however, what holds the requests is network I/O, not lack of raw computing, so there is frequently no slowdown from having a number of processors/cores significantly lower than the number of requests handled at one time. |
2,962,996 | I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:
LOG4CXX\_DEBUG(logger, "test " << var1 << " and " << var3 " and .....)
I prefer using printf like variable length arguments:
LOG4CXX\_DEBUG(logger, "test %d and %d", var1, var3)
So I implemented this small wrapper on top of log4cxx
```
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <log4cxx/logger.h>
#include "log4cxx/basicconfigurator.h"
const char * log_format(const char *fmt, ...);
#define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__))
#define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__))
static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger());
int main(int argc, char **argv)
{
log4cxx::BasicConfigurator::configure();
MYLOG_INFO(logger, "Start ");
MYLOG_WARN(logger, "In running this in %d threads safe?", 1000);
MYLOG_INFO(logger, "End ");
return 0;
}
const char *log_format(const char *fmt, ...)
{
va_list va;
static char formatted[1024];
va_start(va, fmt);
vsnprintf(formatted, 1024, fmt, va);
va_end(va);
return formatted;
}
```
And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.
I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log\_format method? something that I wan't to avoid due to performance implications.
To compile and test this program (in Ubuntu) use :
```
g++ -o loggertest loggertest.cpp -llog4cxx
``` | 2010/06/03 | [
"https://Stackoverflow.com/questions/2962996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113299/"
] | HTTP uses **TCP** which is a connection-based protocol. That is, clients establish a TCP connection while they're communicating with the server.
Multiple clients are allowed to connect to the same destination port on the same destination machine at the same time. The server just opens up multiple simultaneous connections.
Apache (and most other HTTP servers) have a multi-processing module (**MPM**). This is responsible for allocating Apache threads/processes to handle connections. These processes or threads can then run in parallel on their own connection, without blocking each other. Apache's MPM also tends to keep open "spare" threads or processes even when no connections are open, which helps speed up subsequent requests.
The program [**ab**](http://httpd.apache.org/docs/2.0/programs/ab.html) (short for ApacheBench) which comes with Apache lets you test what happens when you open up multiple connections to your HTTP server at once.
Apache's configuration files will normally set a limit for the number of simultaneous connections it will accept. This will be set to a reasonable number, such that during normal operation this limit should never be reached.
Note too that the HTTP protocol (from version 1.1) allows for a connection to be kept open, so that the client can make multiple HTTP requests before closing the connection, potentially reducing the number of simultaneous connections they need to make.
More on Apache's MPMs:
Apache itself can use a number of different multi-processing modules (MPMs). Apache 1.x normally used a module called "prefork", which creates a number of Apache processes in advance, so that incoming connections can often be sent to an existing process. This is as I described above.
Apache 2.x normally uses an MPM called "worker", which uses [**multithreading**](http://en.wikipedia.org/wiki/Thread_%28computer_science%29) (running multiple execution threads within a single process) to achieve the same thing. The advantage of multithreading over separate processes is that threading is a lot more light-weight compared to opening separate processes, and may even use a bit less memory. It's very fast.
The disadvantage of multithreading is you can't run things like mod\_php. When you're multithreading, all your add-in libraries need to be "thread-safe" - that is, they need to be aware of running in a multithreaded environment. It's harder to write a multi-threaded application. Because threads within a process share some memory/resources between them, this can easily create race condition bugs where threads read or write to memory when another thread is in the process of writing to it. Getting around this requires techniques such as [locking](http://en.wikipedia.org/wiki/Lock_%28computer_science%29). Many of PHP's built-in libraries are not thread-safe, so those wishing to use mod\_php cannot use Apache's "worker" MPM. | The server (apache) is *multi-threaded*, meaning it can run multiple programs at once. A few years ago, a single CPU could switch back and forth quickly between multiple threads, giving on the appearance that two things were happening at once. These days, computers have multiple processors, so the computer can actually run two threads of code simultaneously. That being said, threads aren't really mapped to processors in any simple way.
With that ability, a PHP program can be thought of as a single thread of execution. If two requests reach the server at the same time, two threads can be used to process the request simultaneously. They will probably both get about the same amount of CPU, so if they are doing the same thing, they will complete at approximately the same time.
One of the most common issues with multi-threading is "race conditions"-- where you two requests are doing the same thing ("racing" to do the same thing), if it is a single resource, one of them is going to win. If they both insert a record into the database, they can't both get the same id-- one of them will win. So you need to be careful when writing code to realize other requests are going on at the same time and may modify your database, write files or change globals.
That being said, the programming model allows you to mostly ignore this complexity. |
3,100,357 | following problem is bothering me and I can't find any reasonable explanation and a solution. Perhaps someone could enlighten me.
I have an application that calculates date difference (in days) - in a Search mask and in a Details mask. In the first mask I use days to filter out records with a duration search criteria (Search mask) and I do this with an SQL query:
```
WHERE...
...
AND DECODE(TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))), NULL,
TRUNC(to_number(SUBSTR((systimestamp - create_date),1,instr(systimestamp -
create_date,' ')))), TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))) ) >=140
AND DECODE(TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))), NULL,
TRUNC(to_number(SUBSTR((systimestamp - create_date),1,instr(systimestamp -
create_date,' ')))), TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))) ) <=140
```
In this special case I try to find out all the records that have a duration of 140 days.
In the second mask (Details) I show the record details, including its duration. This is done with the following java code:
```
public static Integer getDuration(Date caseDate, Date closeDate) {
Date beginDate = caseDate;
Date endDate = (closeDate != null)? closeDate: new Date();
long difference = endDate.getTime() - beginDate.getTime();
int daysDiff = (int) (difference / (24.0 * 60 * 60 * 1000));
return new Integer(daysDiff);
}
```
My problem is that when I search, I find some records that do correspond to the search criteria. For instance I find 4 records and all of them have a duration of 140 days. That's according to Oracle. But when I open the Details mask for some of them I get a duration of 139 days for example. So somehow Java and Oracle calculate date differences in a different way. It seems that in Oracle some rounding is being made, but I can't find where this happens. So any suggestions would be helpful. Thanks!
Greets,
almaak | 2010/06/23 | [
"https://Stackoverflow.com/questions/3100357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94841/"
] | The date could be the same but the time could be different. Resulting in 139 days when you calculate through milliseconds. (java)
I suggest not using millis but use the days to calculate.
Something like
```
public long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}}
```
or
```
/**
*
* @param c1 from
* @param c2 to
* @return amount of days between from and to
*/
public int diff(Calendar c1, Calendar c2) {
int years = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
if (years == 0) {
return c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
} else {
Calendar endOfYear = Calendar.getInstance();
endOfYear.set(Calendar.YEAR, c1.get(Calendar.YEAR));
endOfYear.set(Calendar.MONTH, 11);
endOfYear.set(Calendar.DAY_OF_MONTH, 31);
int days = endOfYear.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
for (int i=1;i <years;i++) {
endOfYear.add(Calendar.YEAR, 1);
days += endOfYear.get(Calendar.DAY_OF_YEAR);
}
days += c2.get(Calendar.DAY_OF_YEAR);
return days;
}
}
```
Side note:
The first example is slightly slower then the second, but if it's only for small differences it's neglectible. | I calculated this same way but I used dayDiff as long not as integer. So try it also, don't cast it. It should work fine. |
3,100,357 | following problem is bothering me and I can't find any reasonable explanation and a solution. Perhaps someone could enlighten me.
I have an application that calculates date difference (in days) - in a Search mask and in a Details mask. In the first mask I use days to filter out records with a duration search criteria (Search mask) and I do this with an SQL query:
```
WHERE...
...
AND DECODE(TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))), NULL,
TRUNC(to_number(SUBSTR((systimestamp - create_date),1,instr(systimestamp -
create_date,' ')))), TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))) ) >=140
AND DECODE(TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))), NULL,
TRUNC(to_number(SUBSTR((systimestamp - create_date),1,instr(systimestamp -
create_date,' ')))), TRUNC(to_number(SUBSTR((close_date -
create_date),1,instr(close_date - create_date,' ')))) ) <=140
```
In this special case I try to find out all the records that have a duration of 140 days.
In the second mask (Details) I show the record details, including its duration. This is done with the following java code:
```
public static Integer getDuration(Date caseDate, Date closeDate) {
Date beginDate = caseDate;
Date endDate = (closeDate != null)? closeDate: new Date();
long difference = endDate.getTime() - beginDate.getTime();
int daysDiff = (int) (difference / (24.0 * 60 * 60 * 1000));
return new Integer(daysDiff);
}
```
My problem is that when I search, I find some records that do correspond to the search criteria. For instance I find 4 records and all of them have a duration of 140 days. That's according to Oracle. But when I open the Details mask for some of them I get a duration of 139 days for example. So somehow Java and Oracle calculate date differences in a different way. It seems that in Oracle some rounding is being made, but I can't find where this happens. So any suggestions would be helpful. Thanks!
Greets,
almaak | 2010/06/23 | [
"https://Stackoverflow.com/questions/3100357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94841/"
] | The date could be the same but the time could be different. Resulting in 139 days when you calculate through milliseconds. (java)
I suggest not using millis but use the days to calculate.
Something like
```
public long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}}
```
or
```
/**
*
* @param c1 from
* @param c2 to
* @return amount of days between from and to
*/
public int diff(Calendar c1, Calendar c2) {
int years = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
if (years == 0) {
return c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
} else {
Calendar endOfYear = Calendar.getInstance();
endOfYear.set(Calendar.YEAR, c1.get(Calendar.YEAR));
endOfYear.set(Calendar.MONTH, 11);
endOfYear.set(Calendar.DAY_OF_MONTH, 31);
int days = endOfYear.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
for (int i=1;i <years;i++) {
endOfYear.add(Calendar.YEAR, 1);
days += endOfYear.get(Calendar.DAY_OF_YEAR);
}
days += c2.get(Calendar.DAY_OF_YEAR);
return days;
}
}
```
Side note:
The first example is slightly slower then the second, but if it's only for small differences it's neglectible. | The problem here is that you think both columns are DATE columns, where at least one of the two is really a TIMESTAMP column. When you extract one date from another, you get a NUMBER. But when you extract a date from a timestamp, or vice versa, you get an INTERVAL.
An example
A table with a DATE and a TIMESTAMP:
```
SQL> create table mytable (close_date,create_date)
2 as
3 select date '2010-11-01', systimestamp from dual union all
4 select date '2010-11-11', systimestamp from dual union all
5 select date '2010-12-01', systimestamp from dual
6 /
Table created.
SQL> desc mytable
Name Null? Type
----------------------------------------- -------- ----------------------------
CLOSE_DATE DATE
CREATE_DATE TIMESTAMP(6) WITH TIME ZONE
```
Extract a TIMESTAMP from a DATE column, leads to an INTERVAL:
```
SQL> select close_date - create_date
2 from mytable
3 /
CLOSE_DATE-CREATE_DATE
---------------------------------------------------------------------------
+000000130 11:20:11.672623
+000000140 11:20:11.672623
+000000160 11:20:11.672623
3 rows selected.
```
And there is no need to fiddle with TO\_NUMBER's and SUBSTR's. Just use the EXTRACT function to get the component you want from an interval:
```
SQL> select extract(day from (close_date - create_date))
2 from mytable
3 /
EXTRACT(DAYFROM(CLOSE_DATE-CREATE_DATE))
----------------------------------------
130
140
160
3 rows selected.
```
Regards,
Rob.
And here is an example with two TIMESTAMPS and which shows that INTERVAL's are truncated, not rounded:
```
SQL> create table mytable (close_date,create_date)
2 as
3 select to_timestamp('2010-11-01','yyyy-mm-dd'), trunc(systimestamp,'dd') + interval '6' hour from dual union all
4 select to_timestamp('2010-11-11','yyyy-mm-dd'), trunc(systimestamp,'dd') + interval '12' hour from dual union all
5 select to_timestamp('2010-12-01','yyyy-mm-dd'), trunc(systimestamp,'dd') + interval '18' hour from dual
6 /
Table created.
SQL> desc mytable
Name Null? Type
----------------------------------------- -------- ----------------------------
CLOSE_DATE TIMESTAMP(9)
CREATE_DATE DATE
SQL> select close_date - create_date
2 from mytable
3 /
CLOSE_DATE-CREATE_DATE
---------------------------------------------------------------------------
+000000130 18:00:00.000000000
+000000140 12:00:00.000000000
+000000160 06:00:00.000000000
3 rows selected.
SQL> select extract(day from (close_date - create_date))
2 from mytable
3 /
EXTRACT(DAYFROM(CLOSE_DATE-CREATE_DATE))
----------------------------------------
130
140
160
3 rows selected.
``` |
695,000 | after doing
```
$ cat /dev/input/by-path/pci-0000:00:02.0-usb-0:2:1.0-event-kbd > ~/test_kbd
```
as root, I got a bunch of binary codes (which was expected). Now, I wanted to know how can I interpret this binary code to figure out what key has been pressed? What format is the output in? and is there a reference I could look at that would tell me what key each binary code stands for?
Thanks | 2009/03/29 | [
"https://Stackoverflow.com/questions/695000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78426/"
] | I would guess that they are scan codes. [This page](http://www.computer-engineering.org/ps2keyboard/scancodes2.html) lists the make and break codes of keys used by modern keyboards. For more information on PS/2 keyboard programming, see [Adam Chapweske's resources](http://www.computer-engineering.org/index.html). | This file provides keyboard events (in binary format).
Use
```
evtest /dev/input/by-path/pci-0000:00:02.0-usb-0:2:1.0-event-kbd
```
to get some information. |
1,236,550 | Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
```
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134046/"
] | You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions.
In C++, 5/4 = 1, *not* 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away.
On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point. | You're confusing integer division with floating point division. 3 is the correct answer with integer division. You'll get 4 if you convert those values to floating point numbers. |
1,236,550 | Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
```
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134046/"
] | You're confusing integer division with floating point division. 3 is the correct answer with integer division. You'll get 4 if you convert those values to floating point numbers. | Some of this is being evaluated using integer arithmetic. Try adding a decimal place to your numbers, e.g. `6.0` instead `6` to tell the compiler that you don't want integer arithmetic. |
1,236,550 | Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
```
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134046/"
] | You're confusing integer division with floating point division. 3 is the correct answer with integer division. You'll get 4 if you convert those values to floating point numbers. | ```
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
yields 3
```
s2 = -(0.*13.)/84.+6./42.-0./84.+24./12.+(6.*13.)/42.;
```
does what you are expecting. |
1,236,550 | Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
```
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134046/"
] | You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions.
In C++, 5/4 = 1, *not* 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away.
On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point. | Some of this is being evaluated using integer arithmetic. Try adding a decimal place to your numbers, e.g. `6.0` instead `6` to tell the compiler that you don't want integer arithmetic. |
1,236,550 | Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
```
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken | 2009/08/06 | [
"https://Stackoverflow.com/questions/1236550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134046/"
] | You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions.
In C++, 5/4 = 1, *not* 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away.
On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point. | ```
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
```
yields 3
```
s2 = -(0.*13.)/84.+6./42.-0./84.+24./12.+(6.*13.)/42.;
```
does what you are expecting. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | "Is there any way to detect at the end of the program which objects are loitering around waiting to be Disposed?"
Well, if all goes well, at the end of the program the CLR will call all object's finalizers, which, if the IDisposable pattern was implemented properly, will call the Dispose() methods. So at the end, everything will be cleared up properly.
The problem is that if you have a long running program, chances are some of your IDiposable instances are locking some resources that shouldn't be locked. For cases like this, user code should use the using block or call Dispose() as soon as it is done with an object, but there's really no way for a anyone except the code author to know that. | Determining when and where to call Dispose() is a very subjective thing, dependent on the nature of the program and how it uses disposable objects. Subjective problems are not something compilers are very good at. Instead, this is more a job for static analysis, which is the arena of tools like FxCop and StyleCop, or perhaps more advanced compilers like Spec#/Sing#. Static analysis uses rules to determine if subjective requirements, such as "Always ensure .Dispose() is called at some point.", are met.
I am honestly not sure if any static analyzers exist that are capable of checking whether .Dispose() is called. Even for static analysis as it exists today, that might be a bit on the too-subjective side of things. If you need a place to start looking, however, "Static Analysis for C#" is probably the best place. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | There shouldn't be any cases where you don't want to call Dispose, but the compiler cannot tell you **where** you should call dispose.
Suppose you write a factory class which creates and returns disposable objects. Should the compiler bug you for not calling Dispose when the cleanup should be the responsibility of your callers? | What if the disposable object is created in one class/module (say a factory) and is handed off to a different class/module to be used for a while before being disposed of? That use case should be OK, and the compiler shouldn't badger you about it. I suspect that's why there's no compile-time warning---the compiler assumes the `Dispose` call is in another file. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | There shouldn't be any cases where you don't want to call Dispose, but the compiler cannot tell you **where** you should call dispose.
Suppose you write a factory class which creates and returns disposable objects. Should the compiler bug you for not calling Dispose when the cleanup should be the responsibility of your callers? | A good example is the .NET 2.0 Ping class, which runs asynchronously. Unless it throws an exception, you don't actually call Dispose until the callback method. Note that this example has some slightly weird casting due to the way Ping implements the IDisposable interface, but also inherits Dispose() (and only the former works as intended).
```
private void Refresh( Object sender, EventArgs args )
{
Ping ping = null;
try
{
ping = new Ping();
ping.PingCompleted += PingComplete;
ping.SendAsync( defaultHost, null );
}
catch ( Exception )
{
( (IDisposable)ping ).Dispose();
this.isAlive = false;
}
}
private void PingComplete( Object sender, PingCompletedEventArgs args )
{
this.isAlive = ( args.Error == null && args.Reply.Status == IPStatus.Success );
( (IDisposable)sender ).Dispose();
}
``` |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | There shouldn't be any cases where you don't want to call Dispose, but the compiler cannot tell you **where** you should call dispose.
Suppose you write a factory class which creates and returns disposable objects. Should the compiler bug you for not calling Dispose when the cleanup should be the responsibility of your callers? | IDisposable is more for making use of the using keyword. It's not there to force you to call Dispose() - it's there to enable you to call it in a slick, non-obtrusive way:
```
class A : IDisposable {}
/// stuff
using(var a = new A()) {
a.method1();
}
```
after you leave the using block, Dispose() is called for you. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | IDisposable is more for making use of the using keyword. It's not there to force you to call Dispose() - it's there to enable you to call it in a slick, non-obtrusive way:
```
class A : IDisposable {}
/// stuff
using(var a = new A()) {
a.method1();
}
```
after you leave the using block, Dispose() is called for you. | Because the method creating the disposable object may be legitimately returning it as a value, that is, the compiler can't tell how the programming is intending to use it. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | "Is there any way to detect at the end of the program which objects are loitering around waiting to be Disposed?"
Well, if all goes well, at the end of the program the CLR will call all object's finalizers, which, if the IDisposable pattern was implemented properly, will call the Dispose() methods. So at the end, everything will be cleared up properly.
The problem is that if you have a long running program, chances are some of your IDiposable instances are locking some resources that shouldn't be locked. For cases like this, user code should use the using block or call Dispose() as soon as it is done with an object, but there's really no way for a anyone except the code author to know that. | Can I ask how you're certain that it's specifically objects which implement IDisposable? In my experience the most-likely zombie objects are objects which have not properly had all their event handlers removed (thereby leaving a reference to them from another 'live' object and not qualifying them as unreachable during garbage collection).
There are tools which can help track these down by taking a snapshot of the managed heap and stacks and allowing you to see what objects are considered in-use at a given point in time. A freebie is windbg using sos.dll; it'll take some googling for tutorials to show you the commands you need--but it works and it's free. A more user-friendly (don't confused that with "simple") option is Red Gate's ANTS Profiler running in Memory Profiling mode--it's a slick tool.
Edit: Regarding the usefulness of calling Dispose--it provides a deterministic way to cleanup objects. Garbage Collection only runs when your app has ran out of its allocated memory--it's an expensive task which basically stops your application from executing and looks at all objects in existance and builds a tree of "reachable" (in-use) objects, then cleans up the unreachable objects. Manually cleaning up an object frees it before GC ever has to run. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | There shouldn't be any cases where you don't want to call Dispose, but the compiler cannot tell you **where** you should call dispose.
Suppose you write a factory class which creates and returns disposable objects. Should the compiler bug you for not calling Dispose when the cleanup should be the responsibility of your callers? | Because the method creating the disposable object may be legitimately returning it as a value, that is, the compiler can't tell how the programming is intending to use it. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | "Is there any way to detect at the end of the program which objects are loitering around waiting to be Disposed?"
Well, if all goes well, at the end of the program the CLR will call all object's finalizers, which, if the IDisposable pattern was implemented properly, will call the Dispose() methods. So at the end, everything will be cleared up properly.
The problem is that if you have a long running program, chances are some of your IDiposable instances are locking some resources that shouldn't be locked. For cases like this, user code should use the using block or call Dispose() as soon as it is done with an object, but there's really no way for a anyone except the code author to know that. | What if the disposable object is created in one class/module (say a factory) and is handed off to a different class/module to be used for a while before being disposed of? That use case should be OK, and the compiler shouldn't badger you about it. I suspect that's why there's no compile-time warning---the compiler assumes the `Dispose` call is in another file. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | A good example is the .NET 2.0 Ping class, which runs asynchronously. Unless it throws an exception, you don't actually call Dispose until the callback method. Note that this example has some slightly weird casting due to the way Ping implements the IDisposable interface, but also inherits Dispose() (and only the former works as intended).
```
private void Refresh( Object sender, EventArgs args )
{
Ping ping = null;
try
{
ping = new Ping();
ping.PingCompleted += PingComplete;
ping.SendAsync( defaultHost, null );
}
catch ( Exception )
{
( (IDisposable)ping ).Dispose();
this.isAlive = false;
}
}
private void PingComplete( Object sender, PingCompletedEventArgs args )
{
this.isAlive = ( args.Error == null && args.Reply.Status == IPStatus.Success );
( (IDisposable)sender ).Dispose();
}
``` | Determining when and where to call Dispose() is a very subjective thing, dependent on the nature of the program and how it uses disposable objects. Subjective problems are not something compilers are very good at. Instead, this is more a job for static analysis, which is the arena of tools like FxCop and StyleCop, or perhaps more advanced compilers like Spec#/Sing#. Static analysis uses rules to determine if subjective requirements, such as "Always ensure .Dispose() is called at some point.", are met.
I am honestly not sure if any static analyzers exist that are capable of checking whether .Dispose() is called. Even for static analysis as it exists today, that might be a bit on the too-subjective side of things. If you need a place to start looking, however, "Static Analysis for C#" is probably the best place. |
437,618 | I've been debugging some code recently that was a bit memory leaky. It's a long running program that runs as a Windows service.
If you find a class wearing an `IDisposable` interface, it is telling you that some of the resources it uses are outside the abilities of the garbage collector to clean up for you.
The reason it is telling you this is that you, the user of this object, are now responsible for when these resources are cleaned up. Congratulations!
As a conscientious developer, you are nudged towards calling the `.Dispose()` method when you've finished with the object in order to release those unmanaged resources.
There is the nice `using()` pattern to help clean up these resources once they are finished with. Which just leaves finding which exact objects are causing the leakyness?
In order to aid tracking down these rogue unmanaged resources, is there any way to query what objects are loitering around waiting to be Disposed at any given point in time? | 2009/01/13 | [
"https://Stackoverflow.com/questions/437618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023/"
] | "Is there any way to detect at the end of the program which objects are loitering around waiting to be Disposed?"
Well, if all goes well, at the end of the program the CLR will call all object's finalizers, which, if the IDisposable pattern was implemented properly, will call the Dispose() methods. So at the end, everything will be cleared up properly.
The problem is that if you have a long running program, chances are some of your IDiposable instances are locking some resources that shouldn't be locked. For cases like this, user code should use the using block or call Dispose() as soon as it is done with an object, but there's really no way for a anyone except the code author to know that. | Because the method creating the disposable object may be legitimately returning it as a value, that is, the compiler can't tell how the programming is intending to use it. |
241,605 | I am working with a device that requires me to generate a 16 bit CRC.
The datasheet for the device says it needs the following CRC Definition:
```
CRC Type Length Polynomial Direction Preset Residue
CRC-CCITT 16 bits x16 + x12 + x5 + 1 Forward FFFF (16) 1D0F (16)
```
where preset=FFFF (16 bit) and Residue=1D0F (16 bit)
I searched for a CRC algorithm and found this link:
<http://www.lammertbies.nl/comm/info/crc-calculation.html>
It has both on it.
CRC-CCITT (0xFFFF)
CRC-CCITT (0x1D0F)
What's the difference between the preset and the residue? | 2008/10/27 | [
"https://Stackoverflow.com/questions/241605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You initialize the CRC register with the ***preset*** before feeding in your message.
The ***residue*** is what should be left in the CRC register after feeding through a message, plus its correct CRC.
If you just want to send a message, you won't see the residue value. But when the device runs your message+CRC through the CRC algorithm again, it'll see a final value of 0x1D0F if there were no transmission errors.
---
You can also demonstrate this to yourself without getting the device involved. This can help you confirm that your algorithm is doing something that, at least, resembles a CRC.
* First, calculate the CRC for your message.
* Append your message and that CRC, then pass the whole thing through a new CRC calculation (remember to reset to the preset value first.)
* If all went well, your CRC register should contain the residue value.
---
The best CRC explanation I've ever found is here:
<https://archive.org/stream/PainlessCRC/crc_v3.txt> | The difference is in what the algorithm does with the two values. I just looked at a CRC algorithm myself and it looks pretty simple.
Preset is the value it starts with and residue is XOR'd with the value at the end.
Now, the **reason** for choosing particular values for preset and residue, that I don't know. |
241,605 | I am working with a device that requires me to generate a 16 bit CRC.
The datasheet for the device says it needs the following CRC Definition:
```
CRC Type Length Polynomial Direction Preset Residue
CRC-CCITT 16 bits x16 + x12 + x5 + 1 Forward FFFF (16) 1D0F (16)
```
where preset=FFFF (16 bit) and Residue=1D0F (16 bit)
I searched for a CRC algorithm and found this link:
<http://www.lammertbies.nl/comm/info/crc-calculation.html>
It has both on it.
CRC-CCITT (0xFFFF)
CRC-CCITT (0x1D0F)
What's the difference between the preset and the residue? | 2008/10/27 | [
"https://Stackoverflow.com/questions/241605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You initialize the CRC register with the ***preset*** before feeding in your message.
The ***residue*** is what should be left in the CRC register after feeding through a message, plus its correct CRC.
If you just want to send a message, you won't see the residue value. But when the device runs your message+CRC through the CRC algorithm again, it'll see a final value of 0x1D0F if there were no transmission errors.
---
You can also demonstrate this to yourself without getting the device involved. This can help you confirm that your algorithm is doing something that, at least, resembles a CRC.
* First, calculate the CRC for your message.
* Append your message and that CRC, then pass the whole thing through a new CRC calculation (remember to reset to the preset value first.)
* If all went well, your CRC register should contain the residue value.
---
The best CRC explanation I've ever found is here:
<https://archive.org/stream/PainlessCRC/crc_v3.txt> | Something's not right here.
You're looking for a 16-bit CRC, but you've specified a 24-bit Preset and Residue. Post a link to the datasheet for the device you're looking at.
The best source for CRC information is, by the way, is [Ross Williams' guide to CRC.](http://www.ross.net/crc/download/crc_v3.txt)
edit: Ah-hah, I see the "24-bit" preset was just the formatting of the table. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | ```
string.Join(sep, new string[] {myNewBO[0].LastName, myNewBO[0].FirstName});
``` | There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | ```
string.Join(sep, new string[] {myNewBO[0].LastName, myNewBO[0].FirstName});
``` | I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | ```
string.Join(sep, new string[] {myNewBO[0].LastName, myNewBO[0].FirstName});
``` | What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append `.ToString()` to the end of FirstName and LastName. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | I prefer using `string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)`
Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string.
Edit
====
In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?"
Are you doing this in an Eval() or code behind etc....
One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string. | There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | I prefer using `string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)`
Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string.
Edit
====
In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?"
Are you doing this in an Eval() or code behind etc....
One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string. | I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | I prefer using `string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)`
Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string.
Edit
====
In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?"
Are you doing this in an Eval() or code behind etc....
One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string. | What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append `.ToString()` to the end of FirstName and LastName. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same. | There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need. | What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append `.ToString()` to the end of FirstName and LastName. |
480,263 | What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
```
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
```
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :) | 2009/01/26 | [
"https://Stackoverflow.com/questions/480263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45704/"
] | I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same. | What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append `.ToString()` to the end of FirstName and LastName. |
1,352,313 | While compiling my project I get:
```
The system is out of resources.
Consult the following stack trace for details.
java.lang.StackOverflowError
at com.sun.tools.javac.code.Type$WildcardType.isSuperBound(Type.java:435)
at com.sun.tools.javac.code.Types$1.visitWildcardType(Types.java:102)
at com.sun.tools.javac.code.Types$1.visitWildcardType(Types.java:98)
at com.sun.tools.javac.code.Type$WildcardType.accept(Type.java:416)
at com.sun.tools.javac.code.Types$MapVisitor.visit(Types.java:3232)
at com.sun.tools.javac.code.Types.upperBound(Types.java:95)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
...
```
How do you find the root of the problem?
I have found [a bug report](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6207386)... | 2009/08/29 | [
"https://Stackoverflow.com/questions/1352313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61628/"
] | The bug report you linked to indicates that the bug was fixed in JDK 6. Which version of the JDK are you using to build?
If you can't identify the part of your source that is causing the problem, perhaps you could try compiling with JDK 6 to see if it can identify the problem without crashing.
Otherwise, I would use the "divide and conquer" approach: Remove half your source code, compile, and see if it still crashes. Depending on whether it does or not, you will know which half the problem is in. Repeat. | I would start by running javac with the `-verbose` option to see which .java file was causing the problem. |
1,352,313 | While compiling my project I get:
```
The system is out of resources.
Consult the following stack trace for details.
java.lang.StackOverflowError
at com.sun.tools.javac.code.Type$WildcardType.isSuperBound(Type.java:435)
at com.sun.tools.javac.code.Types$1.visitWildcardType(Types.java:102)
at com.sun.tools.javac.code.Types$1.visitWildcardType(Types.java:98)
at com.sun.tools.javac.code.Type$WildcardType.accept(Type.java:416)
at com.sun.tools.javac.code.Types$MapVisitor.visit(Types.java:3232)
at com.sun.tools.javac.code.Types.upperBound(Types.java:95)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2977)
at com.sun.tools.javac.code.Types.adaptRecursive(Types.java:2986)
at com.sun.tools.javac.code.Types.adapt(Types.java:3016)
...
```
How do you find the root of the problem?
I have found [a bug report](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6207386)... | 2009/08/29 | [
"https://Stackoverflow.com/questions/1352313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61628/"
] | The bug report you linked to indicates that the bug was fixed in JDK 6. Which version of the JDK are you using to build?
If you can't identify the part of your source that is causing the problem, perhaps you could try compiling with JDK 6 to see if it can identify the problem without crashing.
Otherwise, I would use the "divide and conquer" approach: Remove half your source code, compile, and see if it still crashes. Depending on whether it does or not, you will know which half the problem is in. Repeat. | What about trying a different compiler, like the one in Eclipse? It's error messages are at least different, in my experience often more to the point. Also I haven't seen compilation failures like this yet. |
563,811 | We have a login control on a page named login.aspx which is set as the start page of the website. Once the user logs in, it is redirecting to default.aspx although our destinationpageurl is not set to any value.
If we set the destinationpageurl to somepage.aspx, it is working redirecting properly, but why is it redirecting to default.aspx by default, if the destinationpageurl is not set.
Thanks for any help,
Animesh | 2009/02/19 | [
"https://Stackoverflow.com/questions/563811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is it just redirecting to / and it's actually IIS which is serving default.aspx, based on the default document settings? | Redirection is required to set cookies. To write anything in cookie (session or anything) an action is needed to performed. Simlest action is redircetion.
While performing redirection it writes authentication information. |
563,811 | We have a login control on a page named login.aspx which is set as the start page of the website. Once the user logs in, it is redirecting to default.aspx although our destinationpageurl is not set to any value.
If we set the destinationpageurl to somepage.aspx, it is working redirecting properly, but why is it redirecting to default.aspx by default, if the destinationpageurl is not set.
Thanks for any help,
Animesh | 2009/02/19 | [
"https://Stackoverflow.com/questions/563811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The [defaultUrl](http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.defaulturl%28v=vs.110%29.aspx) under authentication tag in web.config the reason for automatic redirection to default.aspx.
```
<authentication mode="Forms">
<forms
name="401kApp"
loginUrl="/login.aspx"
cookieless="AutoDetect"
**defaultUrl="myCustomLogin.aspx">**
<credentials passwordFormat = "SHA1">
<user name="UserName"
password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
</credentials>
</forms>
```
Change this if you want to redirect to some other page instead of default.aspx . | Is it just redirecting to / and it's actually IIS which is serving default.aspx, based on the default document settings? |
563,811 | We have a login control on a page named login.aspx which is set as the start page of the website. Once the user logs in, it is redirecting to default.aspx although our destinationpageurl is not set to any value.
If we set the destinationpageurl to somepage.aspx, it is working redirecting properly, but why is it redirecting to default.aspx by default, if the destinationpageurl is not set.
Thanks for any help,
Animesh | 2009/02/19 | [
"https://Stackoverflow.com/questions/563811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The [defaultUrl](http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.defaulturl%28v=vs.110%29.aspx) under authentication tag in web.config the reason for automatic redirection to default.aspx.
```
<authentication mode="Forms">
<forms
name="401kApp"
loginUrl="/login.aspx"
cookieless="AutoDetect"
**defaultUrl="myCustomLogin.aspx">**
<credentials passwordFormat = "SHA1">
<user name="UserName"
password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
</credentials>
</forms>
```
Change this if you want to redirect to some other page instead of default.aspx . | Redirection is required to set cookies. To write anything in cookie (session or anything) an action is needed to performed. Simlest action is redircetion.
While performing redirection it writes authentication information. |
1,500,104 | I've been asked to research approaches to deal with an app we're supposed to be building. This app, hypothetically a Windows form written in C#, will issue commands directly to the server if it's connected, but if the app is offline, the state must be maintained as if it was connected and then sync up and issue data changes/commands to the server once it **is** connected.
I'm not sure where to start looking. This is something akin to Google Gears, but I don't think I have that option if we go a Winform route (which looks likely, given that there are other functions the application needs that a web app couldn't perform). Is the [Microsoft Sync framework](http://msdn.microsoft.com/en-us/sync/default.aspx) a viable option? Does Silverlight do anything like this? Any other options? I've Googled around a bit but would like the community input on what's best given the scenario. | 2009/09/30 | [
"https://Stackoverflow.com/questions/1500104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | The Microsoft Sync Framework definitely supports the scenario you describe, although I would say that it's fairly complicated to get it working.
One thing to understand about the Sync Framework is that it's really two quite distinct frameworks shipping in the same package:
* Sync Framework
* ADO.NET Sync services v. 2
The ADO.NET Sync services are by far the easiest to set up, but they are constrained to synchronizing two relational data stores (although you can set up a web service as a remote facade between the two).
The core Sync Framework has no such limitations, but is far more complex to implement. When I used it about six months ago, I found that the best source to learn from was the SDK, and particularly the File/Folder sync sample code.
As far as I could tell, there was little to no sharing of code and types between the two 'frameworks', so you will have to pick one or the other.
In either case, there are no constraints on how you host the sync code, so Windows Forms is just one option among many. | If I understand correctly, this doesn't sound like an actual data synchronization issue to me where you want to keep two databases in sync. it sounds more like you want a reliable mechanism for a client to call functions on a server in an environment where the connection is unstable, and if the connection is not present at the time, you want the function called as soon as the connection is back up.
If my understanding is right, this is one option. if not, this will probably not be helpful.
---
This is a very short answer to an in-depth problem, but we had a similar situation and this is how we handled it.
We have a client application that needs to monitor some data on a PC in a store. When certain events happen, this client application needs to update our server in the corporate offices, preferably Real-Time. However, the connection is not 100% reliable, so we needed a similar mechanism.
We solved this by trying to write to the server via a web service. If there is an error calling the web service, the command is serialized as an XML file in a folder named "waiting to upload".
We have a routine running in our client app on a timer set for every *n* minutes. When the timer elapses, it checks for XML files in this folder. If found, it attempts to call the web service using the information saved in the file, and so on until it is successful. Upon a successful call, the XML file is deleted.
It sounds hack-ish, but it was simple to code and has worked flawlessly for five years now. It's actually been our most trouble-free application all-around and we've implemented the pattern elsewhere successfully |
2,141,072 | I've added checkboxes to my treeview, and am using the AfterSelect event (also tried AfterChecked).
My tree view is like this
1 State
1.1 City1
1.2 City2
1.3 City3
2 State
2.1 City1
2.2 City2
2.3 City3
etc.
I'm trying to run an event, so when a checkbox is clicked, the tag is added to an array ready for processing later. I also need to use it so if a state is clicked, it selects all the cities under that leaf.
```
treeSections.AfterSelect += node_AfterCheck;
private void node_AfterCheck(object sender, TreeViewEventArgs e)
{
MessageBox.Show("testing");
}
```
The above code works on the treeview if it has no heirarchy. But don't work on the treeview with the states and cities unless the text/label for each leaf is double clicked.
Any ideas? | 2010/01/26 | [
"https://Stackoverflow.com/questions/2141072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256409/"
] | I suggest using the combination of TreeView.NodeMouseClick and TreeView.KeyUp events... the click event will provide you the clicked node via event args and with the keyup you can use the currently selected node. Follow the example below...
```
//This is basic - you may need to modify logically to fit your needs
void ManageTreeChecked(TreeNode node)
{
foreach(TreeNode n in node.Nodes)
{
n.Checked = node.Checked;
}
}
private void convTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
ManageTreeChecked(e.Node);
}
private void convTreeView_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
ManageTreeChecked(convTreeView.SelectedNode);
}
}
```
Using the node given each event you can now cycle through the Nodes collection on that node and modify it to be checked/unchecked given the status of the checked status of the node you acted upon.
You can even get fancy enough to uncheck a parent node when all child nodes are unchecked. If you desire a 3-state treenode (All Checked, Some Checked and None Checked) then you have to create it or find one that has been created.
Enjoy, best of luck. | Some code for you to consider :
Not considered here :
1. what to about which node is selected when checking, when a child node selection forces a parent node to be selected (because all other child nodes are selected).
2. could be other cases related to selection not considered here.
Assumptions :
1. you are in a TreeView with a single-node selection mode
2. only two levels of depth, as in OP's sample ("heavy duty" recursion not required)
3. everything done with the mouse only : extra actions like keyboard keypress not required.
4. if all child nodes are checked, parent node is auto-checked
5. unchecking any child node will uncheck a checked parent node
6. checking or unchecking the parent node will set all child nodes to the same check-state
...
```
// the current Node in AfterSelect
private TreeNode currentNode;
// flag to prevent recursion
private bool dontRecurse;
// boolean used in testing if all child nodes are checked
private bool isChecked;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
// prevent recursion here
if (dontRecurse) return;
// set the currentNode
currentNode = e.Node;
// for debugging
//Console.WriteLine("after check node = " + currentNode.Text);
// select or unselect the current node depending on checkstate
if (currentNode.Checked)
{
treeView1.SelectedNode = currentNode;
}
else
{
treeView1.SelectedNode = null;
}
if(currentNode.Nodes.Count > 0)
{
// node with children : make the child nodes
// checked state match the parents
foreach (TreeNode theNode in currentNode.Nodes)
{
theNode.Checked = currentNode.Checked;
}
}
else
{
// assume a child node is selected here
// i.e., we assume no root level nodes without children
if (!currentNode.Checked)
{
// the child node is unchecked : uncheck the parent node
dontRecurse = true;
currentNode.Parent.Checked = false;
dontRecurse = false;
}
else
{
// the child node is checked : check the parent node
// if all other siblings are checked
// check the parent node
dontRecurse = true;
isChecked = true;
foreach(TreeNode theNode in currentNode.Parent.Nodes)
{
if(theNode != currentNode)
{
if (!theNode.Checked) isChecked = false;
}
}
if (isChecked) currentNode.Parent.Checked = true;
dontRecurse = false;
}
}
}
``` |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Presently, it is not working. However, there is some funding (I heard Microsoft, but I have no confirmation) to get it working on the CLR, so there's an on-going effort, which seems to be aiming at basic functionality available by the time Scala 2.8 is out.
By "basic" I mean it should run and produce code, but there's not going to be much CLR-specific tests, and it shouldn't take any advantage of CLR-specific features or libraries.
At any rate, at the moment, *it is not abandoned*.
**EDIT:** Here is a specific reference to the fact it's not abandoned. This is a snippet from one of the regular progress reports the Scala team sends to the Scala Internals mailing list. I picked this one simply because it's the most recent one mentioning it (12 days ago at the time I'm writing this), but anyone looking at them will see this has been referred to regularly on the reports of the first semester of 2010.
>
> Scala Meeting 2010-05-04
>
>
> People attending the meeting: Ingo,
> Miguel, Donna, Adriaan, Iulian, Phil,
> Lukas, Philipp, Toni, Gilles, Martin,
> Hubert, Tiark.
>
>
> * Current work
> + cleanups in remote actors and concurrent.opts, documentation for
> actors
> + fixes with named arguments
> + general bug fixing
> + work on scaladoc
> + work on .NET
>
>
> | Given that Scala on the JVM is at version 2.7 (and 2.8 is imminent), I don't believe this is being maintained.
See also [this StackOverflow question](https://stackoverflow.com/questions/743172/is-scala-net-production-ready) (from April 2009), which has more details. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Given that Scala on the JVM is at version 2.7 (and 2.8 is imminent), I don't believe this is being maintained.
See also [this StackOverflow question](https://stackoverflow.com/questions/743172/is-scala-net-production-ready) (from April 2009), which has more details. | It's also probably worth noting that the advent of [F#](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/) has limited Microsoft's interest in Scala, in that they now have a "blessed" functional language of their own. NIH. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Presently, it is not working. However, there is some funding (I heard Microsoft, but I have no confirmation) to get it working on the CLR, so there's an on-going effort, which seems to be aiming at basic functionality available by the time Scala 2.8 is out.
By "basic" I mean it should run and produce code, but there's not going to be much CLR-specific tests, and it shouldn't take any advantage of CLR-specific features or libraries.
At any rate, at the moment, *it is not abandoned*.
**EDIT:** Here is a specific reference to the fact it's not abandoned. This is a snippet from one of the regular progress reports the Scala team sends to the Scala Internals mailing list. I picked this one simply because it's the most recent one mentioning it (12 days ago at the time I'm writing this), but anyone looking at them will see this has been referred to regularly on the reports of the first semester of 2010.
>
> Scala Meeting 2010-05-04
>
>
> People attending the meeting: Ingo,
> Miguel, Donna, Adriaan, Iulian, Phil,
> Lukas, Philipp, Toni, Gilles, Martin,
> Hubert, Tiark.
>
>
> * Current work
> + cleanups in remote actors and concurrent.opts, documentation for
> actors
> + fixes with named arguments
> + general bug fixing
> + work on scaladoc
> + work on .NET
>
>
> | The status of Scala on the CLR is... shabby. Unless they've worked heavily on it since 2.7.3 (and there's no evidence of this in the changelogs, though I haven't actually tested it), it:
* only runs against .NET 1.1 (!)
* outputs IL assembler which you then
have to ilasm by hand (!)
* is missing
several language and library features
(like structural types and parser
combinators)
It's being maintained to the extent that they're continuing to merge revisions from the Java compiler into the MSIL compiler, but other than that I'd say it's moribund. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | The status of Scala on the CLR is... shabby. Unless they've worked heavily on it since 2.7.3 (and there's no evidence of this in the changelogs, though I haven't actually tested it), it:
* only runs against .NET 1.1 (!)
* outputs IL assembler which you then
have to ilasm by hand (!)
* is missing
several language and library features
(like structural types and parser
combinators)
It's being maintained to the extent that they're continuing to merge revisions from the Java compiler into the MSIL compiler, but other than that I'd say it's moribund. | It's also probably worth noting that the advent of [F#](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/) has limited Microsoft's interest in Scala, in that they now have a "blessed" functional language of their own. NIH. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Presently, it is not working. However, there is some funding (I heard Microsoft, but I have no confirmation) to get it working on the CLR, so there's an on-going effort, which seems to be aiming at basic functionality available by the time Scala 2.8 is out.
By "basic" I mean it should run and produce code, but there's not going to be much CLR-specific tests, and it shouldn't take any advantage of CLR-specific features or libraries.
At any rate, at the moment, *it is not abandoned*.
**EDIT:** Here is a specific reference to the fact it's not abandoned. This is a snippet from one of the regular progress reports the Scala team sends to the Scala Internals mailing list. I picked this one simply because it's the most recent one mentioning it (12 days ago at the time I'm writing this), but anyone looking at them will see this has been referred to regularly on the reports of the first semester of 2010.
>
> Scala Meeting 2010-05-04
>
>
> People attending the meeting: Ingo,
> Miguel, Donna, Adriaan, Iulian, Phil,
> Lukas, Philipp, Toni, Gilles, Martin,
> Hubert, Tiark.
>
>
> * Current work
> + cleanups in remote actors and concurrent.opts, documentation for
> actors
> + fixes with named arguments
> + general bug fixing
> + work on scaladoc
> + work on .NET
>
>
> | It's also probably worth noting that the advent of [F#](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/) has limited Microsoft's interest in Scala, in that they now have a "blessed" functional language of their own. NIH. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Presently, it is not working. However, there is some funding (I heard Microsoft, but I have no confirmation) to get it working on the CLR, so there's an on-going effort, which seems to be aiming at basic functionality available by the time Scala 2.8 is out.
By "basic" I mean it should run and produce code, but there's not going to be much CLR-specific tests, and it shouldn't take any advantage of CLR-specific features or libraries.
At any rate, at the moment, *it is not abandoned*.
**EDIT:** Here is a specific reference to the fact it's not abandoned. This is a snippet from one of the regular progress reports the Scala team sends to the Scala Internals mailing list. I picked this one simply because it's the most recent one mentioning it (12 days ago at the time I'm writing this), but anyone looking at them will see this has been referred to regularly on the reports of the first semester of 2010.
>
> Scala Meeting 2010-05-04
>
>
> People attending the meeting: Ingo,
> Miguel, Donna, Adriaan, Iulian, Phil,
> Lukas, Philipp, Toni, Gilles, Martin,
> Hubert, Tiark.
>
>
> * Current work
> + cleanups in remote actors and concurrent.opts, documentation for
> actors
> + fixes with named arguments
> + general bug fixing
> + work on scaladoc
> + work on .NET
>
>
> | Martin Odersky says in this [SE Radio interview](http://www.se-radio.net/2011/02/episode-171-scala-update-with-martin-odersky/) (January 2011):
>
> I don't want to give you an estimated time of arrival but it should be certainly this year including visual studio support.
>
>
>
He starts talking about .NET at the 15 minute mark. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Presently, it is not working. However, there is some funding (I heard Microsoft, but I have no confirmation) to get it working on the CLR, so there's an on-going effort, which seems to be aiming at basic functionality available by the time Scala 2.8 is out.
By "basic" I mean it should run and produce code, but there's not going to be much CLR-specific tests, and it shouldn't take any advantage of CLR-specific features or libraries.
At any rate, at the moment, *it is not abandoned*.
**EDIT:** Here is a specific reference to the fact it's not abandoned. This is a snippet from one of the regular progress reports the Scala team sends to the Scala Internals mailing list. I picked this one simply because it's the most recent one mentioning it (12 days ago at the time I'm writing this), but anyone looking at them will see this has been referred to regularly on the reports of the first semester of 2010.
>
> Scala Meeting 2010-05-04
>
>
> People attending the meeting: Ingo,
> Miguel, Donna, Adriaan, Iulian, Phil,
> Lukas, Philipp, Toni, Gilles, Martin,
> Hubert, Tiark.
>
>
> * Current work
> + cleanups in remote actors and concurrent.opts, documentation for
> actors
> + fixes with named arguments
> + general bug fixing
> + work on scaladoc
> + work on .NET
>
>
> | In an interview on scala-lang.org on 18th July 2011:
>
> Can I run Scala programs on .Net now?
>
> **Miguel**:
>
> The simple answer is yes, with a few limitations that will be remove by the fall.
>
>
>
Link: [The inteview](http://www.scala-lang.org/node/10299)
Link: [Binaries](http://lampsvn.epfl.ch/svn-repos/scala/scala-experimental/trunk/bootstrap/) |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | Martin Odersky says in this [SE Radio interview](http://www.se-radio.net/2011/02/episode-171-scala-update-with-martin-odersky/) (January 2011):
>
> I don't want to give you an estimated time of arrival but it should be certainly this year including visual studio support.
>
>
>
He starts talking about .NET at the 15 minute mark. | It's also probably worth noting that the advent of [F#](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/) has limited Microsoft's interest in Scala, in that they now have a "blessed" functional language of their own. NIH. |
1,897,815 | The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono... | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81896/"
] | In an interview on scala-lang.org on 18th July 2011:
>
> Can I run Scala programs on .Net now?
>
> **Miguel**:
>
> The simple answer is yes, with a few limitations that will be remove by the fall.
>
>
>
Link: [The inteview](http://www.scala-lang.org/node/10299)
Link: [Binaries](http://lampsvn.epfl.ch/svn-repos/scala/scala-experimental/trunk/bootstrap/) | It's also probably worth noting that the advent of [F#](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/) has limited Microsoft's interest in Scala, in that they now have a "blessed" functional language of their own. NIH. |
1,416,839 | Pls check code .html form gets submitted even if javascript returns false.
```
<form id="form1" name="form1" method="post" action="sub.jsp" onsubmit="return getValue()">
<input type="text" id="userName" name="userName" onkeyup="return getValue()" />
<input type="submit" name="Submit" value="Submit" />
</form>
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
form.userName.focus();
return false;
}
return true;
}
``` | 2009/09/13 | [
"https://Stackoverflow.com/questions/1416839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/153027/"
] | 1) try changing line **`form.userName.focus();`** to **`document.form1.userName.focus();`**
OR
2) try submitting from function itself:
```
<input type="button" name="Submit" value="Submit" onclick="getValue()" />
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
document.form1.userName.focus();//I think this is the problem
return false;
}
document.form1.submit();
}
</script>
``` | I think there are errors in your JavaScript code that happen prior to your return statements. Fix those errors and your code should work. |
1,416,839 | Pls check code .html form gets submitted even if javascript returns false.
```
<form id="form1" name="form1" method="post" action="sub.jsp" onsubmit="return getValue()">
<input type="text" id="userName" name="userName" onkeyup="return getValue()" />
<input type="submit" name="Submit" value="Submit" />
</form>
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
form.userName.focus();
return false;
}
return true;
}
``` | 2009/09/13 | [
"https://Stackoverflow.com/questions/1416839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/153027/"
] | I think there are errors in your JavaScript code that happen prior to your return statements. Fix those errors and your code should work. | alternatively, you make the click handler on the submit button to return false. |
1,416,839 | Pls check code .html form gets submitted even if javascript returns false.
```
<form id="form1" name="form1" method="post" action="sub.jsp" onsubmit="return getValue()">
<input type="text" id="userName" name="userName" onkeyup="return getValue()" />
<input type="submit" name="Submit" value="Submit" />
</form>
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
form.userName.focus();
return false;
}
return true;
}
``` | 2009/09/13 | [
"https://Stackoverflow.com/questions/1416839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/153027/"
] | 1) try changing line **`form.userName.focus();`** to **`document.form1.userName.focus();`**
OR
2) try submitting from function itself:
```
<input type="button" name="Submit" value="Submit" onclick="getValue()" />
<script type="text/javascript" >
function getValue()
{
var userName=document.getElementById("userName");
document.getElementById("userNamemsg").innerHTML="";
if(userName.value=="")
{
var mdiv=document.getElementById("userNamemsg");
mdiv.innerHTML="Error:Required Fields cannot be blank!";
document.form1.userName.focus();//I think this is the problem
return false;
}
document.form1.submit();
}
</script>
``` | alternatively, you make the click handler on the submit button to return false. |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | Using [SymPy](http://sympy.org/), your example would go something like this:
```
>>> import sympy
>>> a,b,c,d,e = sympy.symbols('abcde')
>>> r = (b+c*d)/e
>>> l = a
>>> r = sympy.solve(l-r,d)
>>> l = d
>>> r
[(-b + a*e)/c]
>>>
```
It seems to work for trigonometric functions too:
```
>>> l = a
>>> r = b*sympy.sin(c)
>>> sympy.solve(l-r,c)
[asin(a/b)]
>>>
```
And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions:
```
>>> r = '(b+c*d)/e'
>>> sympy.sympify(r)
(b + c*d)/e
>>> sympy.sstr(_)
'(b + c*d)/e'
>>>
```
or you may prefer to display them as rendered [LaTeX or MathML](http://docs.sympy.org/latest/tutorial/printing.html). | Sage has support for symbolic math. You could just use some of the equation manipulating functions built-in:
<http://sagemath.org/> |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | If you want to do this out of the box, without relying on librairies, I think that the problems you will find are not Python related. If you want to find such equations, you have to describe the heuristics necessary to solve these equations.
First, you have to represent your equation. What about separating:
* operands:
+ symbolic operands (a,b)
+ numeric operands (1,2)
* operators:
+ unary operators (-, trig functions)
+ binary operators (+,-,\*,/)
Unary operators will obviously enclose one operand, binary ops will enclose two.
What about types?
I think that all of these components should derivate from a single common `expression` type.
And this class would have a `getsymbols` method to locate quickly symbols in your expressions.
And then distinguish between unary and binary operators, add a few basic complement/reorder primitives...
Something like:
```
class expression(object):
def symbols(self):
if not hasattr(self, '_symbols'):
self._symbols = self._getsymbols()
return self._symbols
def _getsymbols(self):
"""
return type: list of strings
"""
raise NotImplementedError
class operand(expression): pass
class symbolicoperand(operand):
def __init__(self, name):
self.name = name
def _getsymbols(self):
return [self.name]
def __str__(self):
return self.name
class numericoperand(operand):
def __init__(self, value):
self.value = value
def _getsymbols(self):
return []
def __str__(self):
return str(self.value)
class operator(expression): pass
class binaryoperator(operator):
def __init__(self, lop, rop):
"""
@type lop, rop: expression
"""
self.lop = lop
self.rop = rop
def _getsymbols(self):
return self.lop._getsymbols() + self.rop._getsymbols()
@staticmethod
def complementop():
"""
Return complement operator:
op.complementop()(op(a,b), b) = a
"""
raise NotImplementedError
def reorder():
"""
for op1(a,b) return op2(f(b),g(a)) such as op1(a,b) = op2(f(a),g(b))
"""
raise NotImplementedError
def _getstr(self):
"""
string representing the operator alone
"""
raise NotImplementedError
def __str__(self):
lop = str(self.lop)
if isinstance(self.lop, operator):
lop = '(%s)' % lop
rop = str(self.rop)
if isinstance(self.rop, operator):
rop = '(%s)' % rop
return '%s%s%s' % (lop, self._getstr(), rop)
class symetricoperator(binaryoperator):
def reorder(self):
return self.__class__(self.rop, self.lop)
class asymetricoperator(binaryoperator):
@staticmethod
def _invert(operand):
"""
div._invert(a) -> 1/a
sub._invert(a) -> -a
"""
raise NotImplementedError
def reorder(self):
return self.complementop()(self._invert(self.rop), self.lop)
class div(asymetricoperator):
@staticmethod
def _invert(operand):
if isinstance(operand, div):
return div(self.rop, self.lop)
else:
return div(numericoperand(1), operand)
@staticmethod
def complementop():
return mul
def _getstr(self):
return '/'
class mul(symetricoperator):
@staticmethod
def complementop():
return div
def _getstr(self):
return '*'
class add(symetricoperator):
@staticmethod
def complementop():
return sub
def _getstr(self):
return '+'
class sub(asymetricoperator):
@staticmethod
def _invert(operand):
if isinstance(operand, min):
return operand.op
else:
return min(operand)
@staticmethod
def complementop():
return add
def _getstr(self):
return '-'
class unaryoperator(operator):
def __init__(self, op):
"""
@type op: expression
"""
self.op = op
@staticmethod
def complement(expression):
raise NotImplementedError
def _getsymbols(self):
return self.op._getsymbols()
class min(unaryoperator):
@staticmethod
def complement(expression):
if isinstance(expression, min):
return expression.op
else:
return min(expression)
def __str__(self):
return '-' + str(self.op)
```
With this basic structure set up, you should be able to describe a simple heuristic to solve very simple equations. Just think of the simple rules you learned to solve equations, and write them down. That should work :)
And then a very naive solver:
```
def solve(left, right, symbol):
"""
@type left, right: expression
@type symbol: string
"""
if symbol not in left.symbols():
if symbol not in right.symbols():
raise ValueError('%s not in expressions' % symbol)
left, right = right, left
solved = False
while not solved:
if isinstance(left, operator):
if isinstance(left, unaryoperator):
complementor = left.complement
right = complementor(right)
left = complementor(left)
elif isinstance(left, binaryoperator):
if symbol in left.rop.symbols():
left = left.reorder()
else:
right = left.complementop()(right, left.rop)
left = left.lop
elif isinstance(left, operand):
assert isinstance(left, symbolicoperand)
assert symbol==left.name
solved = True
print symbol,'=',right
a,b,c,d,e = map(symbolicoperand, 'abcde')
solve(a, div(add(b,mul(c,d)),e), 'd') # d = ((a*e)-b)/c
solve(numericoperand(1), min(min(a)), 'a') # a = 1
``` | Sage has support for symbolic math. You could just use some of the equation manipulating functions built-in:
<http://sagemath.org/> |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | Things have sure changed since 2009. I don't know how your GUI application is going, but this is now possible directly in IPython qtconsole (which one could embed inside a custom PyQt/PySide application, and keep track of all the defined symbols, to allow GUI interaction in a separate listbox, etc.)
![enter image description here](https://i.stack.imgur.com/ax15B.png)
*(Uses the `sympyprt` extension for IPython*) | Sage has support for symbolic math. You could just use some of the equation manipulating functions built-in:
<http://sagemath.org/> |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | Using [SymPy](http://sympy.org/), your example would go something like this:
```
>>> import sympy
>>> a,b,c,d,e = sympy.symbols('abcde')
>>> r = (b+c*d)/e
>>> l = a
>>> r = sympy.solve(l-r,d)
>>> l = d
>>> r
[(-b + a*e)/c]
>>>
```
It seems to work for trigonometric functions too:
```
>>> l = a
>>> r = b*sympy.sin(c)
>>> sympy.solve(l-r,c)
[asin(a/b)]
>>>
```
And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions:
```
>>> r = '(b+c*d)/e'
>>> sympy.sympify(r)
(b + c*d)/e
>>> sympy.sstr(_)
'(b + c*d)/e'
>>>
```
or you may prefer to display them as rendered [LaTeX or MathML](http://docs.sympy.org/latest/tutorial/printing.html). | What you want to do isn't easy. Some equations are quite straight forward to rearrange (like make `b` the subject of `a = b*c+d`, which is `b = (a-d)/c`), while others are not so obvious (like make `x` the subject of `y = x*x + 4*x + 4`), while others are not possible (especially when you trigonometric functions and other complications).
As other people have said, check out Sage. It [does](http://sagemath.org/doc/tutorial/tour_algebra.html) what you want:
```
You can solve equations for one variable in terms of others:
sage: x, b, c = var('x b c')
sage: solve([x^2 + b*x + c == 0],x)
[x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)]
``` |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | If you want to do this out of the box, without relying on librairies, I think that the problems you will find are not Python related. If you want to find such equations, you have to describe the heuristics necessary to solve these equations.
First, you have to represent your equation. What about separating:
* operands:
+ symbolic operands (a,b)
+ numeric operands (1,2)
* operators:
+ unary operators (-, trig functions)
+ binary operators (+,-,\*,/)
Unary operators will obviously enclose one operand, binary ops will enclose two.
What about types?
I think that all of these components should derivate from a single common `expression` type.
And this class would have a `getsymbols` method to locate quickly symbols in your expressions.
And then distinguish between unary and binary operators, add a few basic complement/reorder primitives...
Something like:
```
class expression(object):
def symbols(self):
if not hasattr(self, '_symbols'):
self._symbols = self._getsymbols()
return self._symbols
def _getsymbols(self):
"""
return type: list of strings
"""
raise NotImplementedError
class operand(expression): pass
class symbolicoperand(operand):
def __init__(self, name):
self.name = name
def _getsymbols(self):
return [self.name]
def __str__(self):
return self.name
class numericoperand(operand):
def __init__(self, value):
self.value = value
def _getsymbols(self):
return []
def __str__(self):
return str(self.value)
class operator(expression): pass
class binaryoperator(operator):
def __init__(self, lop, rop):
"""
@type lop, rop: expression
"""
self.lop = lop
self.rop = rop
def _getsymbols(self):
return self.lop._getsymbols() + self.rop._getsymbols()
@staticmethod
def complementop():
"""
Return complement operator:
op.complementop()(op(a,b), b) = a
"""
raise NotImplementedError
def reorder():
"""
for op1(a,b) return op2(f(b),g(a)) such as op1(a,b) = op2(f(a),g(b))
"""
raise NotImplementedError
def _getstr(self):
"""
string representing the operator alone
"""
raise NotImplementedError
def __str__(self):
lop = str(self.lop)
if isinstance(self.lop, operator):
lop = '(%s)' % lop
rop = str(self.rop)
if isinstance(self.rop, operator):
rop = '(%s)' % rop
return '%s%s%s' % (lop, self._getstr(), rop)
class symetricoperator(binaryoperator):
def reorder(self):
return self.__class__(self.rop, self.lop)
class asymetricoperator(binaryoperator):
@staticmethod
def _invert(operand):
"""
div._invert(a) -> 1/a
sub._invert(a) -> -a
"""
raise NotImplementedError
def reorder(self):
return self.complementop()(self._invert(self.rop), self.lop)
class div(asymetricoperator):
@staticmethod
def _invert(operand):
if isinstance(operand, div):
return div(self.rop, self.lop)
else:
return div(numericoperand(1), operand)
@staticmethod
def complementop():
return mul
def _getstr(self):
return '/'
class mul(symetricoperator):
@staticmethod
def complementop():
return div
def _getstr(self):
return '*'
class add(symetricoperator):
@staticmethod
def complementop():
return sub
def _getstr(self):
return '+'
class sub(asymetricoperator):
@staticmethod
def _invert(operand):
if isinstance(operand, min):
return operand.op
else:
return min(operand)
@staticmethod
def complementop():
return add
def _getstr(self):
return '-'
class unaryoperator(operator):
def __init__(self, op):
"""
@type op: expression
"""
self.op = op
@staticmethod
def complement(expression):
raise NotImplementedError
def _getsymbols(self):
return self.op._getsymbols()
class min(unaryoperator):
@staticmethod
def complement(expression):
if isinstance(expression, min):
return expression.op
else:
return min(expression)
def __str__(self):
return '-' + str(self.op)
```
With this basic structure set up, you should be able to describe a simple heuristic to solve very simple equations. Just think of the simple rules you learned to solve equations, and write them down. That should work :)
And then a very naive solver:
```
def solve(left, right, symbol):
"""
@type left, right: expression
@type symbol: string
"""
if symbol not in left.symbols():
if symbol not in right.symbols():
raise ValueError('%s not in expressions' % symbol)
left, right = right, left
solved = False
while not solved:
if isinstance(left, operator):
if isinstance(left, unaryoperator):
complementor = left.complement
right = complementor(right)
left = complementor(left)
elif isinstance(left, binaryoperator):
if symbol in left.rop.symbols():
left = left.reorder()
else:
right = left.complementop()(right, left.rop)
left = left.lop
elif isinstance(left, operand):
assert isinstance(left, symbolicoperand)
assert symbol==left.name
solved = True
print symbol,'=',right
a,b,c,d,e = map(symbolicoperand, 'abcde')
solve(a, div(add(b,mul(c,d)),e), 'd') # d = ((a*e)-b)/c
solve(numericoperand(1), min(min(a)), 'a') # a = 1
``` | What you want to do isn't easy. Some equations are quite straight forward to rearrange (like make `b` the subject of `a = b*c+d`, which is `b = (a-d)/c`), while others are not so obvious (like make `x` the subject of `y = x*x + 4*x + 4`), while others are not possible (especially when you trigonometric functions and other complications).
As other people have said, check out Sage. It [does](http://sagemath.org/doc/tutorial/tour_algebra.html) what you want:
```
You can solve equations for one variable in terms of others:
sage: x, b, c = var('x b c')
sage: solve([x^2 + b*x + c == 0],x)
[x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)]
``` |
1,010,583 | I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.
For example:
---
```
a = (b+c*d)/e
```
*Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:*
```
d = (a*e - b)/c
```
---
As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.
Is that the only way to go or is there any simpler suggestion?
Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.
But that is just my opinion, so please point out if I am wrong.
Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem. | 2009/06/18 | [
"https://Stackoverflow.com/questions/1010583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83088/"
] | Things have sure changed since 2009. I don't know how your GUI application is going, but this is now possible directly in IPython qtconsole (which one could embed inside a custom PyQt/PySide application, and keep track of all the defined symbols, to allow GUI interaction in a separate listbox, etc.)
![enter image description here](https://i.stack.imgur.com/ax15B.png)
*(Uses the `sympyprt` extension for IPython*) | What you want to do isn't easy. Some equations are quite straight forward to rearrange (like make `b` the subject of `a = b*c+d`, which is `b = (a-d)/c`), while others are not so obvious (like make `x` the subject of `y = x*x + 4*x + 4`), while others are not possible (especially when you trigonometric functions and other complications).
As other people have said, check out Sage. It [does](http://sagemath.org/doc/tutorial/tour_algebra.html) what you want:
```
You can solve equations for one variable in terms of others:
sage: x, b, c = var('x b c')
sage: solve([x^2 + b*x + c == 0],x)
[x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)]
``` |