Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
how can i search an html page for a word fast?
and how can i get the html tag that the word is in? (so i can work with the entire tag) | To find the element that word exists in, you'd have to traverse the entire tree looking in just the text nodes, applying the same test as above. Once you find the word in a text node, return the parent of that node.
```
var word = "foo",
queue = [document.body],
curr
;
while (curr = queue.pop()) {
if (!curr.textContent.match(word)) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE : // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!");
console.log(curr);
// you might want to end your search here.
}
break;
case Node.ELEMENT_NODE : // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
```
this works in Firefox, no promises for IE.
What it does is start with the body element and check to see if the word exists inside that element. If it doesn't, then that's it, and the search stops there. If it is in the body element, then it loops through all the immediate children of the body. If it finds a text node, then see if the word is in that text node. If it finds an element, then push that into the queue. Keep on going until you've either found the word or there's no more elements to search. | You can iterate through DOM elements, looking for a substring within them. Neither fast nor elegant, but for small HTML might work well enough.
I'd try something recursive, like: *(code not tested)*
```
findText(node, text) {
if(node.childNodes.length==0) {//leaf node
if(node.textContent.indexOf(text)== -1) return [];
return [node];
}
var matchingNodes = new Array();
for(child in node.childNodes) {
matchingNodes.concat(findText(child, text));
}
return matchingNodes;
}
``` | find words in html page with javascript | [
"",
"javascript",
"html",
""
] |
I'm trying to modify a C# WinForms application that uses multiple forms. At startup, a login window will be shown. If the user logs in with a correct user name and password combo a form with three different tabs will be shown as a sort of administrators view. If no password or user name is supplied, a much simplified GUI will be shown. It will basically consist of two buttons that in turn shows these two forms depending on which button is pressed:
Button 1: Give the user access to a form consisting of a number of textboxes where the user can input information that will be saved to a database. Once the DB-operation has been executed successfully, the first form with the two buttons will be displayed again.
Button 2: A form is shown where the user can input a code that will be written to DB. Once the DB operation is concluded, the user will automatically be taken back to the original form with the two buttons.
Both forms will also have a back button to take the user back to the first form. I have a lot of logic in place, but I am unsure of how to best handle all the forms involved. Where should I instantiate the first (login) form? Once the login validation is done there are two possible ways to go. Either show the tabbed admin form (if user name and password is correct) or the simplified user form with two large buttons. It should also be possible to logout from the admin form so that the simplified GUI is shown instead.
I hope I am making sense here. I just need a good way to handle all the forms and navigation between them. Currently, there aren't really any need for transporting data between them, but it might be an issue in the future so a solution that takes this into account would be excellent.
I'm thinking that what is needed is really a class that handles the displaying and disposing of the forms right from the start, but I'm not quite sure where I should put the instantiation of this handling class. | Form management can be a tricky issue. There are some different ways to go:
* Just have the forms float around on the screen. Let some static class hold references to the different forms and expose methods to activate them.
* Implement the forms as UserControls instead, put them onto the same form, and show and hide the controls as appropriate (this can also be achieved by loading the forms, stripping form borders and such and setting their parent to a panel or something similar; this will almost make them behave like user controls, but only almost)
* There are many other methods, of course ;o)
When it comes to managing the login form, I would do that in the Main method; show the login form, check the credentials and then instantiate the UI you want to show and pass that to the Application.Run method. | I just did something similar. I had a set of forms to manage as "pages" as the spec called them. I also had strict page flow that was a bit more complicated than yours. I'll talk you through that.
I designed each "page" of interaction as a UserControl and created an "OuterForm" and a "Controller". The controller had a Navigate(string pageName) method and the outer form contained a panel and had a Display(Control page) method which cleared the children on a panel and added the replacement.
I used Spring.NET to configure the controller and the form and used setter injection to create a two way link between the two. That meant my main method could ask Spring for the form and just display it using Application.Run(form);
I created a convenience method to access the controller from event handlers and would do e.g. Controller.Instance.Navigate(chosenPage); The controller also used Spring.NET to load the correct UserControl for chosenPage and then called on the main form to Display() the instance it loaded. There as no Spring.NET code in any user control, and no new keywords either ;-)
The advantage for me in using Spring.NET is that I had one form class that just monitored some business logic and displayed a progress indication. I was able to implement that once and configure many instances of that form injected with different business logic that it would monitor. Also, I needed to stub out interfaces to domain specific pieces of hardware and web services. Eventually I moved page flow into the configuration as well. | Handling multiple forms in C# app | [
"",
"c#",
".net",
"winforms",
"architecture",
""
] |
Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so -
```
int Result = Func();
assert( Result == 1 );
```
When compiling code in a Release build, assert()s are usually disabled, so this code may produce a warning about Result being set but never read.
A possible workaround is -
```
int Result = Func();
if ( Result == 1 )
{
assert( 0 );
}
```
But it requires too much typing, isn't easy on the eyes and causes the condition to be always checked (yes, the compiler may optimize the check away, but still).
I'm looking for an alternative way to express this assert() in a way that wouldn't cause the warning, but still be simple to use and avoid changing the semantics of assert().
(disabling the warning using a #pragma in this region of code isn't an option, and lowering warning levels to make it go away isn't an option either...). | We use a macro to specifically indicate when something is unused:
```
#define _unused(x) ((void)(x))
```
Then in your example, you'd have:
```
int Result = Func();
assert( Result == 1 );
_unused( Result ); // make production build happy
```
That way (a) the production build succeeds, and (b) it is obvious in the code that the variable is unused *by design*, not that it's just been forgotten about. This is especially helpful when parameters to a function are not used. | I wouldn't be able to give a better answer than this, that addresses that problem, and many more:
[Stupid C++ Tricks: Adventures in assert](http://web.archive.org/web/20201129200055/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/)
```
#ifdef NDEBUG
#define ASSERT(x) do { (void)sizeof(x);} while (0)
#else
#include <assert.h>
#define ASSERT(x) assert(x)
#endif
``` | Avoiding unused variables warnings when using assert() in a Release build | [
"",
"c++",
"warnings",
"assertions",
""
] |
C# 3.5 Winforms...
So I’ve recently discovered the IExtenderProvider and how it can be used to extend controls with additional properties.
In a prototype project that I setup i put a break point on the ‘set’ method for my extendee property and as the form loads I could see the ‘set’ method executing for every control on the form; which is exactly what I wanted. Following the successful prototype I implemented the extender component into my main project. All the forms in my project inherit from a base form which I’ve added my extender component to. On the base form I set the modifier of the extender component to public so that its accessible by the form inheriting this base form.
Doing the same thing before i added a break point on the ‘set’ method for my extendee property but the method doesn’t execute for the controls in the form (but only for the controls in the base form). HELP!
I should probably add at this point that i’ve source controlled my forms and so most of them are checked-in (ie lock from modification). For the forms that I’ve checked out and modified the provider property; I’ve noticed in the designer file that all controls have an additional statement which calls the ‘set’ method of the provider property.
this.MyProvider1.SetMyProperty(this.txtTextBox1, false);
Am I right in thinking that for the extender component to work it has to physically modify the designer file or should it be able to cope with locked files and therefore call the set method dynamically? I guess if it does have to modify the designer file then this isn’t a problem for new forms or forms that get modified after the extender component was added to the project – but it would be problem when you have 101 forms all locked by source-safe...
I’d appreciate any thoughts... | > > At what point does the extender provider (IExtenderProvider) extend the 'type' (in my case a winforms control) that the extender was intended for; at design time or at run time?
The **designer** is responsible for showing you the properties of the extender in the property editor
Method `bool CanExtend(object)` from the IExtenderProvider interface
> > Am I right in thinking that for the extender component to work it has to physically modify the designer file or should it be able to cope with locked files and therefore call the set method dynamically?
It has to physically modify the designer file, and write the extended properties there
> > I guess if it does have to modify the designer file then this isn’t a problem for new forms or forms that get modified after the extender component was added to the project – but it would be problem when you have 101 forms all locked by source-safe...
This is is not a problem for new forms, and **not for old forms**.
If you want to set some extended properties, open the old form and set the extended properties (a check out of the file is necessary) | This really does confirm my suspicions, many thanks. But this does leave a problem in that the components are only extended if some physical change is made to the old form.
I was trying to hijack the Set property method to also add and remove an event handler to the component (if the component was a control). Image the property is a Boolean and when set to false it adds the event handle and therefore the default behaviour (setting to true doesn’t add and event handler)
To cut a long story short the controls which were part of newly added forms automatically have an event handler added even without me explicitly setting the property to false but the designer file of the old forms never modifier so the event handler wasn’t added.
As some background, I was trying to add a global event handler for all controls
[Global event handler for all controls for User Help](https://stackoverflow.com/questions/772079/global-event-handler-for-all-controls-for-user-help)
The theme here is to add context help to my forms here’s example of the extender ( the event handler is added as part of the end initialiser)
public partial class HelpProvider : Component, IExtenderProvider, ISupportInitialize
... other code of the extender omitted ...
```
#region ISupportInitialize Members
public void BeginInit()
{
// do nothing
}
public void EndInit()
{
if (DesignMode)
return;
foreach (Component item in _disableOnlineHelp)
{
if (item == null)
continue;
if (GetDisableOnlineHelp(item)) // developer has decide to set property to TRUE
continue;
Control control = item as Control;
if (control != null)
continue;
control.HelpRequested += new HelpEventHandler(HelpProvider_HelpRequested);
_toolTip.SetToolTip(control, GetHelpText(control));
}
}
#endregion
#region DisableOnlineHelp Provider Property
public virtual bool GetDisableOnlineHelp(Component component)
{
object flag = _disableOnlineHelp[component];
if (flag == null)
return false;
return (bool)flag;
}
public virtual void SetDisableOnlineHelp(Component component, bool value)
{
_disableOnlineHelp[component] = value;
}
#endregion
``` | IExtenderProvider and WinForms designer file | [
"",
"c#",
".net",
"winforms",
""
] |
Are there reasons for not storing boolean values in SQL as bit data types without NULL? I see them often stored as integers without constraints to limit values to 0 and 1, and as strings with things like T/F, True/False, yes/no, etc., again without constraints. Isn't it better to store them as bits and not have to worry about additional constraints? What am I missing here? | I'd always stick with the smallest data type I can to store this.
* SQLServer: BIT
* Oracle: NUMBER(1) (or BOOLEAN in PL/SQL)
* MySQL: TINYINT (iirc BOOLEAN maps to this automatically)
Edit: Oracle's BOOLEAN is PL/SQL only, not table definition. Updated answer to reflect this. | what typically happens down the road is that someone wants to add also a maybe to yes and no, if you have a bit then now you have to change all your code to tinyint
if you had tinyint to begin with then you don't.....believe me this happens more than you think | Are there reasons for not storing boolean values in SQL as bit data types? | [
"",
"sql",
"t-sql",
""
] |
after doing some test-code for this link :
[Is it safe to call temporary object's methods?](https://stackoverflow.com/questions/701313/is-it-safe-to-call-temporary-objects-methods)
I found a rather strange feature of the c++ language, which I'm not sure how it works :
```
struct Test{
int i;
Test(int ii):i(ii){}
Test& operator=(int ii){
i = ii;
return *this;
}
Test operator+(const Test& rhs){
return Test(i + rhs.i);
}
void non_const_function(){
i *= i;
}
};
int main(){
//code below gives errors, builtin types don't allow evil code
//int i = 5+5 = 8;
//int& iRef = 5+5;
//int* iPtr = &(5+5);
//5 = 10;
Test x = Test(5) + Test(5) = 8;//assign to a temporary
Test& xRef = Test(5) + Test(5);//reference to a temporary
Test* xPtr = &(Test(5) + Test(5));//address of a temporary
Test(5) = Test(10);//assign to a temporary
Test(8).non_const_function();//call a non-const function
return 0;
}
```
xRef and xPtr are both working pointers, with the expected values.
Of course I wouldn't write such code in a real project, but I'm still interested how / why this works.
The only info I found on google about this was that "if you create a reference to a temporary, the temporaries lifetime is linked to the lifetime of the reference"
Note :
-not all compilers are that forgiving, e.g. Metrowerks ARM (does it use GCC ?) only allows const reference to temporaries.
EDIT :
-increasing the warning to W4 in VC++ 2008 showed lots of errors - good to know.
EDIT 2:
Thank you all for the help. I'm back to work, fixing 100's of warnings.
CONCLUSION : use highest warning from start (I even found a REAL bug thanks to /G4) | Let's go line by line:
```
Test x = Test(5) + Test(5) = 8;//assign to a temporary
```
There's no big deal here. Temporaries are still just normal objects, and thus the assignment operator works on them just as it would on anything else.
```
Test& xRef = Test(5) + Test(5);//reference to a temporary
```
Like Metroworks, my GCC doesn't allow a non-const reference to a temporary.
```
Test* xPtr = &(Test(5) + Test(5));//address of a temporary
```
In addition, GCC warns about taking the address of a temporary, for obvious reasons.
```
Test(5) = Test(10);//assign to a temporary
```
Again, this is just assignment, which, as I explained above, is no big deal.
```
Test(8).non_const_function();//call a non-const function
```
Temporary objects aren't constant. There's nothing stopping them from calling non-const functions. | This kind of thing is ubiquitous in many object-oriented programming languages, especially those with object overloading.
If the first statement were written
```
Text x = Test(5).add(Test(5)).set(8);
```
where .add and .set return the lefthand Test instances with the expected values, would you still be confused?
To break this example down, you're creating a Test object with value 5, then adding another Test object with value 5 to it, and returning the first Test object, now with value 10. Then you're setting its value to 8, and assigning that object to x (well actually it's not assignment, again you're creating a Test object named x, then setting its value to the temporary's value). | Assigning to temporary (like 5 = 10 but for user-defined types) | [
"",
"c++",
""
] |
How do you convert HTML entities to Unicode and vice versa in Python? | You need to have [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
```
from BeautifulSoup import BeautifulStoneSoup
import cgi
def HTMLEntitiesToUnicode(text):
"""Converts HTML entities to unicode. For example '&' becomes '&'."""
text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
return text
def unicodeToHTMLEntities(text):
"""Converts unicode to HTML entities. For example '&' becomes '&'."""
text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
return text
text = "&, ®, <, >, ¢, £, ¥, €, §, ©"
uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)
print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &, ®, <, >, ¢, £, ¥, €, §, ©
``` | As to the "vice versa" (which I needed myself, leading me to find this question, which didn't help, and subsequently [another site which had the answer](http://www.megasolutions.net/python/Unicode-to-HTML-entities-78703.aspx)):
```
u'some string'.encode('ascii', 'xmlcharrefreplace')
```
will return a plain string with any non-ascii characters turned into XML (HTML) entities. | Convert HTML entities to Unicode and vice versa | [
"",
"python",
"html",
"html-entities",
""
] |
I'm creating a C# library and am going to be prefix most of the public classes with the protocol they use (TCP, UDP, etc) and I came to a little dilemma: should it be `TCPXxxx` or `TcpXxxx`?
There doesn't seem to be a standard in the .NET framework (`IPAddress` versus `TcpClient`).
Which you would prefer when working with a library: `TCPXxxx` or `TcpXxxx`? | It should be TcpXxxx, by the design guidelines.
In the design guidelines, 2 letter acronyms are capitalized, all others are pascal cased.
From *Framework Design Guidelines* by Cwalina and Abrams:
> * Do capitalize both charaters of two-character acronyms, exception the first word of a camel-cased identifier.
> ```
> System.IO
> public void StartIO(Stream ioStream)
> ```
> * Do capitalize only the first character of acronyms with three or more characters, except the first word of a camel cased identifier.
[MSDN](http://msdn.microsoft.com/en-us/library/ms229043.aspx) has an abbrieviated, shorter version of this. | I always like to imagine a theoretical process that converts WordsLikeThis to words-like-this, and imagine how the name in question would convert. Some examples:
TCPSocket -> t-c-p-socket
TcpSocket -> tcp-socket
Clearly the latter makes more sense. | Representing abbreviations in camel-cased class names | [
"",
"c#",
".net",
"naming-conventions",
""
] |
I am trying to use JavaScript to get the value from an HTML text box but value is not coming after white space
For example:
```
<input type="text" name="txtJob" value="software engineer">
```
I only get: "software" from the above. I am using a script like this:
```
var jobValue = document.getElementById('txtJob').value
```
How do I get the full value: "software engineer"? | +1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.
> i am getting only "software".
id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:
```
<input type="text" name="txtJob" value=software engineer>
``` | Your element does not have an ID but just a name. So you could either use `getElementsByName()` method to get a list of all elements with this name:
```
var jobValue = document.getElementsByName('txtJob')[0].value // first element in DOM (index 0) with name="txtJob"
```
Or you assign an ID to the element:
```
<input type="text" name="txtJob" id="txtJob" value="software engineer">
``` | How to get text box value in JavaScript | [
"",
"javascript",
"html",
""
] |
This simple sample code demonstrates the problem. I create an `ArrayBlockingQueue`, and a thread that waits for data on this queue using `take()`. After the loop is over, in theory both the queue and the thread can be garbage collected, but in practice I soon get an `OutOfMemoryError`. What is preventing this to be GC'd, and how can this be fixed?
```
/**
* Produces out of memory exception because the thread cannot be garbage
* collected.
*/
@Test
public void checkLeak() {
int count = 0;
while (true) {
// just a simple demo, not useful code.
final ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(2);
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
abq.take();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
// perform a GC once in a while
if (++count % 1000 == 0) {
System.out.println("gc");
// this should remove all the previously created queues and threads
// but it does not
System.gc();
}
}
}
```
I am using Java 1.6.0.
UPDATE: perform GC after a few iterations, but this does not help. | Threads are top level objects. They are 'special' so they do not follow the same rules as other objects. The do not rely on references to keep them 'alive' (i.e. safe from GC). A thread will not get garbage collected until it has ended. Which doesn't happen in your sample code, since the thread is blocked. Of course, now that the thread object is not garbage collected, then any other object referenced by it (the queue in your case) also cannot be garbage collected. | You are creating threads indefinitely because they all block until `ArrayBlockingQueue<Integer> abq` has some entry. So eventually you'll get a `OutOfMemoryError`.
**(edit)**
Each thread you create will never end because it blocks until the `abq` queue as one entry.
If the thread is running, the GC isn't going to collect any object that the thread is referencing including the queue `abq` and the thread itself. | OutOfMemoryError - why can a waiting Thread not be garbage collected? | [
"",
"java",
"multithreading",
"garbage-collection",
"out-of-memory",
""
] |
I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.
I want to know how to check if the gridview is empty, and the do something.
I have already tried:
```
if(GridView.Rows.Count == 0)
{
// Do Something
}
```
but it doesn't work...
Any ideas?
Thank you. | Your code *should* work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.
```
DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
ShowEmptyData();
}
else
{
Grid.DataSource = dt;
Grid.DataBind();
}
``` | This doesn't work since the `GridView` is data bound and is going to fetch the actual data at a later time while rendering the page. You should check this by directly querying the data binding source of the gridview (see if the actual list that's grid view bound to is empty or not).
If you just want to display something when it's empty, you should use `<EmptyDataTemplate>` in your markup:
```
<asp:GridView runat="server">
<EmptyDataTemplate>The grid is empty</EmptyDataTemplate>
</asp:GridView>
``` | How to check for an Empty Gridview | [
"",
"c#",
"asp.net",
"gridview",
"null",
""
] |
I saw this C++ code on a forum which minimizes all open windows
```
#define MIN_ALL 419
#define MIN_ALL_UNDO 416
int main(int argc, char* argv[])
{
HWND lHwnd = FindWindow("Shell_TrayWnd",NULL);
SendMessage(lHwnd,WM_COMMAND,MIN_ALL,0);
Sleep(2000);
SendMessage(lHwnd,WM_COMMAND,MIN_ALL_UNDO,0);
return 0;
}
```
How can I access the FindWindow and SendMessage API function and the HWND type in C#.net? | PInvoke.net is your friend :-)
```
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1 {
class Program {
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]
static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);
const int WM_COMMAND = 0x111;
const int MIN_ALL = 419;
const int MIN_ALL_UNDO = 416;
static void Main(string[] args) {
IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero);
System.Threading.Thread.Sleep(2000);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero);
}
}
}
``` | The site www.pinvoke.net has a lot of the information you require. For instance, this article on SendMessage and FindWindow:
<http://www.pinvoke.net/default.aspx/user32.SendMessage>
<http://www.pinvoke.net/default.aspx/user32.FindWindow>
It's rather technical - of course - but basically you use p/invoke to call on the FindWindow and SendMessage API functions to accomplish what you want. =) | Minimizing all open windows in C# | [
"",
"c#",
".net",
"window",
"minimize",
""
] |
I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to
```
''.join(random.choice(string.letters) for i in xrange(len))
```
It sucks if you want to generate long string.
I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.
It generates a 50mil random string on my notebook in just about 3 seconds.
```
def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
```
---
**edit**
heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.
Still curious if there's a better way of doing this that's just as fast. | ```
import os
random_string = os.urandom(string_length)
```
and if you need url safe string :
```
import os
random_string = os.urandom(string_length).hex()
```
(note random\_string length is greatest than string\_length in that case) | Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them
```
from uuid import uuid4
random_string = str(uuid4())
```
If you want it a specific length without dashes
```
random_string_length = 16
str(uuid4()).replace('-', '')[:random_string_length]
``` | Random strings in Python 2.6 (Is this OK?) | [
"",
"python",
"random",
"python-2.6",
""
] |
I'm developing a master-slave command model by which some application "Master" sends commands to homogenous processes called "Slave" to do some task and then respond back with status complete or process failure. they should also expose some data to the master available on request.
What would this model look like in WCF?
would Master and each instance of Slave host thier own services? would only Master host? only Slave? Should I be using Callback Contracts? Data Contracts? or just Service Contracts.
As a side note, this is a low bandwidth, low intensity, internal only distribution project used for product testing and should not be considered as a "large high demand" project. | You will definitely have service contracts - a must - in some shape or form. This just defines your service and the operations (methods) on it (OperationContract).
If it's an internal "behind-the-firewall" system, you could look at a duplex binding, e.g. have the Master call the Slave, and the Slave report back on a duplex channel when it's done. Out of the box, there's only the WsDualHttpBinding to support duplex, but since you're internal, behind-the-firewall, you might want to look at creating your own TCP-based duplex binding (it's not as hard as it might sound at first!).
In this scenario, both involved apps really are server and client at the same time.
You will have DataContracts in some way, shape or form to define the DATA that is being moved around between Master and Slave - so again, yes, you will have to have Data Contracts.
EDIT:
Of course, another approach might be to use two MSMQ message queues; the Master drops his "job" request into a queue, which the Slave listens on and picks up the job request. When the Slave is done, it in turn drops a response into the response queue to which the Master is a listener, and gets notified of the job being done that way.
Marc | I agree with Jeremy here.. What you're describing doesn't need the complexity of callback contracts. The worker nodes could simply expose a WCF service (or even a WSDL or REST web service for that matter...) and then the controller would simply need to know the URLs of each of the child nodes and send messages to the worker nodes.
If you want the controller to be able to broadcast a single message and have all of the worker (I really dislike the master/slave analogy... I long ago switched to calling it controller/worker) nodes do something in response and post their progress back to the group, then you might want to use the often underrated P2P channel available within WCF. This allows a group of services written in WCF to talk to each other all at once as peers with URLs being used almost like topic/conversation separators.
So, for example, you might issue commands on the **net.p2p://labs/commands** channel. Only the controller sends commands on that channel but all of the worker nodes listen. When they're done doing their thing asynchronously, they can report progress back on the **net.p2p://labs/status** channel. An added benefit of this approach is that (if you need this feature), the individual workers would gain the ability to know what all the other workers are doing.
Keep in mind, however that if you use P2P then you'll have to deal with contention - you may end up with 2 nodes accepting the same command. If this is fine, then P2P is your tool. If you need commands to be issued and only picked up serially by individual nodes as they become free (a more likely scenario when telling remote nodes to run individual test scripts, etc) then you can use a MSMQ binding instead of P2P. Then all of the workers become clients which receive messages from the queue and you can more easily counteract the situation of multiple workers accepting the same request.
For additional reference:
[A blog post I wrote a while back on the Peer Channel](http://dotnetaddict.dotnetdevelopersjournal.com/peerseries_wcfpeerchannel.htm).
[Peer Channel Scenarios on MSDN](http://msdn.microsoft.com/en-us/library/ms734699.aspx) - This is good because you can go from here to Peer Channel concepts to the reference guide.
[Peer Channel Team Blog](http://blogs.msdn.com/peerchan/) | using WCF as a master-slave command model | [
"",
"c#",
".net",
"wcf",
"master-slave",
""
] |
When a `Control` is docked in a container (like a `Panel`) and is too wide to be shown (so a scroll bar appears), `Control.Width` seems to return the visible width of the Control (the top arrow in the picture).
How do you get the width that the Control "wants" to be? i.e. its full width that you'd see if you didn't have to scroll (the bottom arrow in the picture).
[alt text http://img19.imageshack.us/img19/372/size.png](http://img19.imageshack.us/img19/372/size.png) | There are two different properties of controls that you might find useful for this purpose. There is the DefaultSize which is the Size of the control when it is initially created, and then there is the PreferredSize which is the size the control can fit into so to speak. All controls have these properties and PreferredSize should be the one you're looking for. | `Bounds` is the actual size its drawn at
`ClientSize` is the size minus any scroll bars
`Control.PreferredSize` is what you want | WinForms - How do you get the size a Control "wants" to be? | [
"",
"c#",
".net",
"winforms",
""
] |
I'm having trouble with the MySQLdb module.
```
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
```
(I'm using a custom port)
the error I get is:
```
Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
```
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
```
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
```
I tried directly from the python prompt:
```
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
```
I'm confused... :( | Make sure that the mysql server is listening for tcp connections, which you can do with netstat -nlp (in \*nix). This is the type of connection you are attempting to make, and db's normally don't listen on the network by default for security reasons. Also, try specifying --host=localhost when using the mysql command, this also try to connect via unix sockets unless you specify otherwise. If mysql is **not** configured to listen for tcp connections, the command will also fail.
Here's a relevant section from the [mysql 5.1 manual](http://dev.mysql.com/doc/refman/5.1/en/can-not-connect-to-server.html) on unix sockets and troubleshooting connections. Note that the error described (2002) is the same one that you are getting.
Alternatively, check to see if the module you are using has an option to connect via unix sockets (as David Suggests). | Changing `localhost` to `127.0.0.1` solved my problem using `MySQLdb`:
```
db = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
```
Using `127.0.0.1` forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If `host` is specified as `localhost`, a Unix socket or pipe will be used. | MySQLdb connection problems | [
"",
"python",
"mysql",
"connection",
""
] |
I'd like to use `os.system("md5sum myFile")` and have the result returned from os.system instead of just runned in a subshell where it's echoed.
In short I'd like to do this:
```
resultMD5 = os.system("md5sum myFile")
```
And only have the md5sum in resultMD5 and not echoed. | [`subprocess`](http://docs.python.org/library/subprocess.html) is better than using `os.system` or `os.popen`
```
import subprocess
resultMD5 = subprocess.Popen(["md5sum","myFile"],stdout=subprocess.PIPE).communicate()[0]
```
Or just calculate the md5sum yourself with the [`hashlib`](http://docs.python.org/library/hashlib.html) module.
```
import hashlib
resultMD5 = hashlib.md5(open("myFile").read()).hexdigest()
``` | You should probably use the subprocess module as a replacement for os.system. | Getting Python System Calls as string results | [
"",
"python",
""
] |
We have constants declared in an interface in our application like this.
```
public interface IConstants
{
public static final String FEVER="6";
public static final String HEADACHE="8";
}
```
We now want to populate these constants values (6 and 8) from the database (or application servlet context).
The database values stored in a look up table are already available in the application session (in servlet context attribute) and hence I don't have to make a database call every time.
How do we accomplish this? | Given that you don't want to change the existing code too much, the simplest way would be:
```
public interface IConstants {
public static final String FEVER = getConstFromDatabase("FEVER");
public static final String HEADACHE = getConstFromDatabase("HEADACHE");
}
``` | Since the constant values are persisted in a database, the best approach would be to create an enum type and make them available through it. | How can I best initialize constants from a database or servlet context? | [
"",
"java",
"database",
"servlets",
"initialization",
"constants",
""
] |
Sorry to have to do this, but I'm getting no love from the people who run this particular webservice. I've never used SOAP before.
[Here's the method I'm trying to call](https://cwi.rezexchange.com:9991/Service.asmx?op=CwiRateDetails)
And here's the code I'm thinking should work
```
public function soapTest(){
echo "start <br />";
use_soap_error_handler(true);
$client = new SoapClient("https://cwi.rezexchange.com:9991/?wsdl");
// here's the problem. What goes in the parenthesis?
$result = $client->CwiRateDetails(????);
echo($result);
echo "<br /> end";
}
```
Now I'm guessing this tells me what the parenthesis should contain.
```
POST /Service.asmx HTTP/1.1
Host: cwi.rezexchange.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://hotelconcepts.com/CwiRateDetails"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<CwiRateDetails xmlns="http://hotelconcepts.com/">
<PropertyCode>string</PropertyCode>
<DateFrom>dateTime</DateFrom>
<DateTo>dateTime</DateTo>
<RatePlan>string</RatePlan>
<RoomType>string</RoomType>
<PromotionalRates>boolean</PromotionalRates>
</CwiRateDetails>
</soap:Body>
</soap:Envelope>
```
My guess is that something like
```
$result = $client->CwiRateDetails($PCode, $DateFrom, $DateTo, $RatePlan, $RoomType, false);
```
Should work. But I don't know what the date format is, or what room types are or how to reference a rate plan.
Now. Before I go ape shit bannana bonkers over email with them, am I wrong in thinking there's a load more information they need to give me? Or is there some sort of SOAP trickery I can use to get that information from somewhere? | Try
```
$result = $client->CwiRateDetails(array(
'PropertyCode' => ...,
'DateFrom' => ...,
'DateTo' => ...,
'RatePlan' => ...,
'RoomType' => ...,
'PromotionalRates' => ...,
));
```
You'll have to serialize your date-time-values in `DateFrom` and `DateTo` and the boolean value in `PromotionalRates` according to the XML Schema specifications:
* [boolean](http://www.w3.org/TR/xmlschema-2/#boolean): `true` = `'true'` or `1` and `false` = `'false'` or `0`
* [dateTime](http://www.w3.org/TR/xmlschema-2/#dateTime): `YYYY-MM-DD`T`hh:mm:ss`Z for UTC or `YYYY-MM-DD`T`hh:mm:ss(+/-)hh:mm` for local-time including timezone information; timezone information is optional | the date format is actually dateTime (which is a SOAP format type). I'm sure there is an example on the internet that converts a time() (or whatever) to a SOAP::dateTime field.
the information you need to connect is all there.. maybe you should read up on webservices first? | Calling a SOAP method with PHP for a specific service | [
"",
"php",
"soap",
""
] |
The hashCode value of a Java String is computed as ([String.hashCode()](http://java.sun.com/javase/6/docs/api/java/lang/String.html#hashCode())):
```
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
```
Are there any circumstances (say JVM version, vendor, etc.) under which the following expression will evaluate to false?
```
boolean expression = "This is a Java string".hashCode() == 586653468
```
**Update #1:** If you claim that the answer is "yes, there are such circumstances" - then please give a concrete example of when "This is a Java string".hashCode() != 586653468. Try to be as specific/concrete as possible.
**Update #2:** We all know that relying on the implementation details of hashCode() is bad in general. However, I'm talking specifically about String.hashCode() - so please keep the answer focused to String.hashCode(). Object.hashCode() is totally irrelevant in the context of this question. | I can see that documentation as far back as Java 1.2.
While it's true that *in general* you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for `java.lang.String`, so changing it would count as breaking existing contracts.
Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind `java.lang.String` is a special case simply because the algorithm *has* been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course. | I found something about JDK 1.0 and 1.1 and >= 1.2:
> In JDK 1.0.x and 1.1.x the hashCode
> function for long Strings worked by
> sampling every nth character. This
> pretty well guaranteed you would have
> many Strings hashing to the same
> value, thus slowing down Hashtable
> lookup. In JDK 1.2 the function has
> been improved to multiply the result
> so far by 31 then add the next
> character in sequence. This is a
> little slower, but is much better at
> avoiding collisions.
> Source: <http://mindprod.com/jgloss/hashcode.html>
Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all... | Consistency of hashCode() on a Java string | [
"",
"java",
"string",
"hashcode",
""
] |
Do you think that this is a good way for testing exceptions? Any suggestions?
```
Exception exception = null;
try{
//I m sure that an exeption will happen here
}
catch (Exception ex){
exception = ex;
}
Assert.IsNotNull(exception);
```
I'm using MS Test. | I have a couple of different patterns that I use. I use the `ExpectedException` attribute most of the time when an exception is expected. This suffices for most cases, however, there are some cases when this is not sufficient. The exception may not be catchable - since it's thrown by a method that is invoked by reflection - or perhaps I just want to check that other conditions hold, say a transaction is rolled back or some value has still been set. In these cases I wrap it in a `try/catch` block that expects the exact exception, does an `Assert.Fail` if the code succeeds and also catches generic exceptions to make sure that a different exception is not thrown.
First case:
```
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void MethodTest()
{
var obj = new ClassRequiringNonNullParameter( null );
}
```
Second case:
```
[TestMethod]
public void MethodTest()
{
try
{
var obj = new ClassRequiringNonNullParameter( null );
Assert.Fail("An exception should have been thrown");
}
catch (ArgumentNullException ae)
{
Assert.AreEqual( "Parameter cannot be null or empty.", ae.Message );
}
catch (Exception e)
{
Assert.Fail(
string.Format( "Unexpected exception of type {0} caught: {1}",
e.GetType(), e.Message )
);
}
}
``` | Now, 2017, you can do it easier with the new [MSTest V2 Framework](https://github.com/microsoft/testfx):
```
Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());
//async version
await Assert.ThrowsExceptionAsync<SomeException>(
() => myObject.SomeMethodAsync()
);
``` | Best way to test exceptions with Assert to ensure they will be thrown | [
"",
"c#",
".net",
"unit-testing",
""
] |
I'd like to implement a [Bézier curve](http://en.wikipedia.org/wiki/B%C3%A9zier_curve). How should I go about creating a quadratic curve?
```
void printQuadCurve(float delta, Vector2f p0, Vector2f p1, Vector2f p2);
```
Clearly we'd need to use linear interpolation, but does this exist in the standard math library? If not, where can I find it?
I'm using Linux. | Recently I ran across the same question and wanted to implemented it on my own.
This image from Wikipedia helped me:

The following code shows how to compute a quadratic bezier.
```
int interpolate( int from , int to , float percent )
{
int difference = to - from;
return from + ( difference * percent );
}
for( float i = 0 ; i < 1 ; i += 0.01 )
{
// The Green Line
xa = interpolate( x1 , x2 , i );
ya = interpolate( y1 , y2 , i );
xb = interpolate( x2 , x3 , i );
yb = interpolate( y2 , y3 , i );
// The Black Dot
x = interpolate( xa , xb , i );
y = interpolate( ya , yb , i );
drawPixel( x , y , COLOR_RED );
}
```
With (x1|y1), (x2|y2) and (x3|y3) being P0, P1 and P2 in the image. Just for showing the basic idea...
For the ones who ask for the cubic bezier, it just works analogue (also from Wikipedia):

[This](https://stackoverflow.com/questions/37642168/how-to-convert-quadratic-bezier-curve-code-into-cubic-bezier-curve/37642695#37642695) answer provides Code for it. | Here is a general implementation for a curve with any number of points.
```
vec2 getBezierPoint( vec2* points, int numPoints, float t ) {
vec2* tmp = new vec2[numPoints];
memcpy(tmp, points, numPoints * sizeof(vec2));
int i = numPoints - 1;
while (i > 0) {
for (int k = 0; k < i; k++)
tmp[k] = tmp[k] + t * ( tmp[k+1] - tmp[k] );
i--;
}
vec2 answer = tmp[0];
delete[] tmp;
return answer;
}
```
Note that it uses heap memory for a temporary array which is not all that efficient. If you only need to deal with a fixed number of points you could hard-code the numPoints value and use stack memory instead.
Of course, the above assumes you have a vec2 structure and operators for it like this:
```
struct vec2 {
float x, y;
vec2(float x, float y) : x(x), y(y) {}
};
vec2 operator + (vec2 a, vec2 b) {
return vec2(a.x + b.x, a.y + b.y);
}
vec2 operator - (vec2 a, vec2 b) {
return vec2(a.x - b.x, a.y - b.y);
}
vec2 operator * (float s, vec2 a) {
return vec2(s * a.x, s * a.y);
}
``` | How do I implement a Bézier curve in C++? | [
"",
"c++",
"math",
"interpolation",
"spline",
""
] |
How does the compiler fill values in `char array[100] = {0};`? What's the magic behind it?
I wanted to know how internally compiler initializes. | It's not magic.
The behavior of this code in C is described in section 6.7.8.21 of the C specification ([online draft of C spec](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf)): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification ([online draft of C++ spec](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf#subsection.8.5.1)): the compiler aggregate-initializes the elements that don't have a specified value.
Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:
```
char array[100] = {};
```
As for what sort of code the compiler might generate when you do this, take a look at this question: [Strange assembly from array 0-initialization](https://stackoverflow.com/questions/531477/strange-assembly-from-array-0-initialization/531490) | Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements. | how does array[100] = {0} set the entire array to 0? | [
"",
"c++",
"c",
"compiler-construction",
""
] |
I was asking my team to port our vc6 application to vc2005, they are ready to allot sometime to do the same.Now they need to know what is the advantage of porting.
I don't thing they really understand what does it mean to adhere to standard compliance.
Help me list out the advantage to do the porting.
Problem I am facing are
1)No debugging support for standard containers
2)Not able to use boost libraries
3)We use lot of query generation but use CString format function that is not type safe
4)Much time is spent on trouble shooting vc6 problems like having >>
```
vector<vector<int>>
```
with out space between >> | **Advantages:**
* **More standards compliant compiler.** This is a good thing because it will make it easier to port to another platform (if you ever want to do that). It also means you can look things up in the standard rather than in microsoft's documentation. In the end you will have to upgrade your compiler at some point in the feature. The sooner you do it, the less work it will be.
* **Not supported by MS.** The new SDK doesn't work. 64-bit doesn't work. And I don't think they're still fixing bugs either.
* **Nicer IDE.** Personally, I really prefer tabs to MDI. I also think that it's much easier to configure Visual Studio (create custom shortcuts, menu bars, etc.). Of course that's subjective. Check out an express edition and see if you agree.
* **Better plugin support.** Some plugins aren't available for VC6.
**Disadvantages:**
* **Time it takes to port.** This very much depends on what kind of code you have. If your code heavily uses non-standards compliant VC6 features, it might take some time. As Andrew said, if you're maintaining an old legacy project, it might not be worth it.
* **Worse Performance.** If you're developing on really old computers, Visual Studio may be too slow.
* **Cost** I just had a quick look and Visual Studio licenses seem to be a bit more expensive than VC6's. | Why VC2005? If you are going to invest the time (and testing!) to upgrade from VC6, why not target VC2008? | Advantage of porting vc6 to vc2005/vc2008? | [
"",
"c++",
"visual-studio-2008",
"visual-studio-2005",
"visual-c++-6",
"porting",
""
] |
From what I can tell, pdb does not recognize when the source code has changed between "runs". That is, if I'm debugging, notice a bug, fix that bug, and rerun the program in pdb (i.e. without exiting pdb), pdb will not recompile the code. I'll still be debugging the old version of the code, even if pdb lists the new source code.
So, does pdb not update the compiled code as the source changes? If not, is there a way to make it do so? I'd like to be able to stay in a single pdb session in order to keep my breakpoints and such.
FWIW, gdb will notice when the program it's debugging changes underneath it, though only on a restart of that program. This is the behavior I'm trying to replicate in pdb. | What do you mean by "rerun the program in pdb?" If you've imported a module, Python won't reread it unless you explicitly ask to do so, i.e. with `reload(module)`. However, `reload` is far from bulletproof (see [xreload](http://svn.python.org/projects/sandbox/trunk/xreload/xreload.py) for another strategy).
There are plenty of pitfalls in Python code reloading. To more robustly solve your problem, you could wrap pdb with a class that records your breakpoint info to a file on disk, for example, and plays them back on command.
(Sorry, ignore the first version of this answer; it's early and I didn't read your question carefully enough.) | The following mini-module may help. If you import it in your pdb session, then you can use:
```
pdb> pdbs.r()
```
at any time to force-reload all non-system modules except **main**. The code skips that because it throws an ImportError('Cannot re-init internal module **main**') exception.
```
# pdbs.py - PDB support
from __future__ import print_function
def r():
"""Reload all non-system modules, to reload stuff on pbd restart. """
import importlib
import sys
# This is likely to be OS-specific
SYS_PREFIX = '/usr/lib'
for k, v in list(sys.modules.items()):
if (
k == "__main__" or
k.startswith("pdb") or
not getattr(v, "__file__", None)
or v.__file__.startswith(SYS_PREFIX)
):
continue
print("reloading %s [%s]" % (k, v.__file__), file=sys.stderr)
importlib.reload(v)
``` | How to make pdb recognize that the source has changed between runs? | [
"",
"python",
"debugging",
"pdb",
""
] |
I want to do something like this:
```
foreach ($array as $key=>$value except when $key="id")
{
// whatever
}
```
... without having to put an "if" clause inside the body of the loop. It is not guaranteed that "id" will the be the first or last element in the array, and I don't really want to unset or slice the array, because that will be expensive, ugly, and not maintain the original data. I also definitely need to use both key and value inside the loop.
Any ideas? | I don't think that the if-clause is such a problem:
```
foreach ($array as $key => $value) {
if ($key == 'ignore_me') continue;
if ($key == 'ignore_me_2') continue;
```
If you want a fancy solution, you can use [`array_diff_key`](http://de.php.net/manual/en/function.array-diff.php):
```
$loop_array = array_diff_key($actual_array, array('ignore_me' => NULL, 'ignore_me_2' => NULL));
foreach ($loop_array as $key => $value) {
#...
``` | Go with the if-clause inside the loop.
There is nothing inelegant about it, it is the easiest to read and understand, and it is the most efficient.
If you have many keys to skip you could build a second hash to test against (in the if-clause):
```
foreach ($array as $key => $value) {
if (array_key_exists($key,$skip_keys)) continue;
...
}
``` | What is the most elegant way to do "foreach x except y" in PHP? | [
"",
"php",
"optimization",
"loops",
"foreach",
""
] |
I've got a seemingly unique issue on just one computer in the company (had to be my boss's). I've got a program from Borland C++ that uses a `TSQLConnection`. It connects to a local Firebird server 2.1.1.17910 running as an application. The other computers work fine.
It will *absolutely not* connect on this one lappy (local server) for *anything*. I remember he always had trouble with InterBase when it was installed as well. I think he installed up to 7.5 possibly. It's gone now and I went through and wiped out any old *GDS32.dll* files and updated them with the FireBird ones, and the connection is using *fbclient.dll* anyways...
I tried uninstalling and reinstalling FB and running it as a service. Didn't work.
I went into etc/services and added in this line:
```
gds_db 3050/tcp #Firebird
```
No dice.
Sticking "localhost:" in front of the database location gets this error
> Unable to complete network request to host "localhost".
> Failed to establish a connection.
I checked netstat, it's listening on 127.0.0.1 port 3050...
Tried sticking "127.0.0.1:" before the database location, I get:
> connection rejected by remote interface
Tried taking 127.0.0.1 or localhost out entirely and just using the database location, which is the right location, I get
> Unavailable Database.
The *exact same CD* works fine on other machines. I tried sticking "localhost", "127.0.0.1", and nothing at all in front of the database location and all connect fine on other machines.
I've made him turn his firewall off, still no dice... This problem has been going on for a long time and I'm at the end of my rope. I've tried everything I can possibly think of. It works fine on my computer, blank test computers, for the beta testers... everybody except my boss. Any help would be *vastly* appreciated. | I had "exactly" same problem now today 5/11-2011
and went to work quite methodically on the issue.
Searched internet for hints and tips.
I tried uninstalling my Firebird 2. I reinstalled it. Same error persisted when I tried using database via Delphi.
I renamed GDS32.DLL in system32 folder and copied it from another computer where everything was working fine.
Still same problem. Always refusing to connect to the database for some reason.
I checked the logfile of Firebird and.. yes. it always refuse, but when I use IB-Console, I can create a new database or work with existing ones.
I decided to do one final attempt and uninstalled Firebird again.
I then deleted the rest of the installation in programfiles\firebird.
I did a complete registry check with AML Free registry cleaner. (I think most good ones will do)
It found about 1500 entries that were invalid and I just decided to "Fix All"
When finished, I reinstalled firebird 2. Installed it as a server.
Voila.
I can now use IBqueries and SQL Databases with Firebird in my development of software again.
My best guess is that something was wrong with Windows Registry, although I can not pinpoint this.
Good luck and best regards.
Morten, Norway, a very late Saturday evening. | I authored the "InterBase Operations Guide" way back in 1998, when I worked for Borland. I tried to address troubleshooting for common connection-related errors.
* **Connection Refused** is when the client application cannot complete a network connection to the IB/FB server at all. If a firewall were blocking connections, this is the error you'd get.
* **Connection Rejected** is when the network connection reached the database server, but the database server decided to terminated the connection request. Reasons for this include:
+ You entered the wrong path to the database.
+ You specified an incorrect username or password (i.e. they don't match entries in `isc4.gdb`).
+ The database directory is on a networked filesystem. It must be on a filesystem that is physically local to the laptop.
+ The database server process doesn't have filesystem-level permission to read & write the database files (including `isc4.gdb`). Could there be anti-virus software or other filesystem security blocking I/O for unauthorized processes? | "Unable to complete network request" or "connection rejected" for Firebird, on just one machine | [
"",
"sql",
"odbc",
"firebird",
"c++builder",
""
] |
Given:
```
function foo(){
var bar = "quux";
console.log(/*mystery code here*/);
}
```
I'm looking for code that when inserted into the comment would yield the value of bar. By way of illustration, something like this works in a global scope:
```
var foo = "bar";
var bar = "quux";
console.log(window[foo]);
```
But, of course, variables defined globally are appended to the window object. Variables local to a function are not. Is there some similar way to programmatically get to local function variables? | Nope, afraid not.
### See: [javascript locals()?](https://stackoverflow.com/questions/39960/javascript-locals) | In the first place, why do you need to do that? Isn't it enough to do something like this?
```
console.log(bar);
```
Local variables are not available outside its scope in JS, but if you're trying to access them only inside your function then there's no need for an alternative way to access them.
Perhaps if you told us the real problem behind this (not just this example) we could provide you with a better alternative than looking for something like `window[foo]`. | Programmatically get values of variables local to function in javascript? | [
"",
"javascript",
"metaprogramming",
""
] |
I have created a custom list here is the List Template:
```
<ListTemplate Name="CustomDocumentLibrary"
DisplayName="Document Library"
Description=""
BaseType="1"
Type="10101"
OnQuickLaunch="TRUE"
SecurityBits="11"
Sequence="110"
Image="/_layouts/images/itdl.gif"
DocumentTemplate="101" />
```
I have added a custom Action:
```
<CustomAction
Id="1611D96C-ABBD-4021-9183-60D8440BEB95"
Location="EditControlBlock"
Title="Send to Document Management"
ImageUrl="/_layouts/images/cmCopy.gif"
RegistrationType="List"
RegistrationId="10101">
<UrlAction Url="~site/Lists/DocumentLibrary/Forms/SendToDM.aspx?ListId={ListId}&ListItemID={ItemId}&Action=Copy"/>
```
This context menu appears on both files and folders, is it possible for my context memu to appear on files only? | I never figured out how to do this in code or XML but I got it working in JavaScript.
I added the following code to the AllItems.aspx:
```
<script type="text/javascript">
function Custom_AddDocLibMenuItems(m, ctx) {
var otype = currentItemFSObjType = GetAttributeFromItemTable(itemTable, "OType", "FSObjType");
if (otype != 1) { // 1=folder
var itemId = GetAttributeFromItemTable(itemTable, "ItemId", "Id");
var listId = ctx.listName;
var action = 'Go_To_Page("' + ctx.HttpRoot + '/_layouts/MyPage.aspx?ListId=' + listId + '&ListItemID=' + itemId + '");';
var option = CAMOpt(m, 'Do Something', action, '/_layouts/IMAGES/10.gif', '', 1110);
option.id = "ID_Do_Something";
}
return false;
}
function Go_To_Page(page) {
window.location = page;
}
</script>
```
One unfortunate side effect is the item is always first in the context menu. | You can register the action on the content type instead. But that might not be suitable in your situation? | SharePoint custom context menu in custom list appears on folders and not just files | [
"",
"c#",
"visual-studio-2008",
"sharepoint",
"custom-action",
"sharepointdocumentlibrary",
""
] |
Greetings!
I've created an APSX web form that returns a remote image based on some supplied parameters. It can be used like this:
```
<img src="/ImageGetter.aspx?param1=abc¶m2=123" />
```
ImageGetter.aspx's markup and code look similar to this:
```
<%@ OutputCache Duration="100000" VaryByParam="*" Location="ServerAndClient" %>
<%@ Page Language="C#" AutoEventWireup="false" EnableSessionState="False" CodeBehind="ImageGetter.aspx.cs" Inherits="ACME.Helpers.ImageGetter" %>
```
This code is called in ImageGetter.aspx's Page\_Load method:
```
byte[] data = null;
Dictionary<string, string> file_locations = GetImageLocations(param1, param2);
try
{
data = new WebClient().DownloadData(file_locations["main"]);
}
catch (WebException wex)
{
try
{
data = new WebClient().DownloadData(file_locations["backup"]);
}
catch (Exception e)
{
throw;
}
}
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(data, 0, data.Length);
Response.End();
```
From my testing, it doesn't appear to be caching. Is this possible to do with Output Caching or should I resort to writing my own cache to store the byte arrays depending on query string paramters? | Try dropping the Response.End() as this will terminate the thread prematurely and prevent output caching from taking place.
See: <http://bytes.com/groups/net-asp/323363-cache-varybyparam-doesnt-work>
You *may* wish to consider using an ASHX handler and using your own caching method. | Use an ASHX generic handler and use the HttpRuntimeCache (Cache object) to do the job as Codebrain said. It will be faster and WAY more flexible. | ASPX That Returns An Image - Output Cache-able? | [
"",
"c#",
"asp.net",
"caching",
"outputcache",
""
] |
I have an Apache Ant build file with a `<javac>` command that requires four specific JARs to be on the build `classpath`. I've tried to do this:
```
<project basedir=".." default="build_to_jar" name="Transnet Spectrum Analyzer">
<property environment="env"/>
<property name="src" value="src"/>
<property name="libsrc" value="library_sources" />
<property name="build" value="build"/>
<property name="dist" value="dist"/>
<property name="target" value="1.5"/>
<property name="libraries" value="./libraries"/>
<fileset dir="." id="TSA.classpath">
<include name="${libraries}/rxtx/RXTXcomm.jar" />
<include name="${libraries}/commons-logging-1.1.1.jar" />
<include name="${libsrc}/JCommon/jcommon-1.0.15.jar" />
<include name="${libsrc}/JFreeChart/jfreechart-1.0.12.jar" />
</fileset>
<target name="compile" depends="clean,init" description="compile the source " >
<echo>Compile from ${src} to ${build}</echo>
<javac destdir="${build}" source="${target}" target="${target}">
<compilerarg value="-Xlint:unchecked"/>
<src path="${src}"/>
<classpath path="TSA.classpath" />
</javac>
</target>
<!-- blah blah blah -->
</project>
```
…but none of the files specified in `TSA.classpath` appear to show up. How do I include these files in my classpath? | Here's an example from a project I am currently working on. I suspect you can modify it to work for your situation.
```
<path id="master-classpath">
<fileset dir="${web.dir}/WEB-INF/lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${appserver.lib}">
<include name="servlet*.jar"/>
</fileset>
<pathelement path="${build.dir}"/>
</path>
...
<javac destdir="${build.dir}">
<src path="${src.dir}"/>
<classpath refid="master-classpath"/>
</javac>
``` | Try
```
<javac ... classpathref="TSA.classpath">
```
or
```
<javac ...>
...
<classpath refid="TSA.classpath" />
</javac>
``` | Getting Ant <javac> to recognise a classpath | [
"",
"java",
"ant",
"classpath",
""
] |
I have a database with a table, storing changes in account-balance across a couple of accounts, with three columns;
```
float balance, #The account balance after the change
Date date, #Date that balance change occurred
int aid #Account that the balance change occurred on
```
It contains a couple of entries for each day of the year, and I want to retrieve the balance of every five days. I also want it to separate between accounts (ie if two changes
occurred on the same day, but on separate accounts, return both).
**The problem is this**: Sometimes there will be several days (or weeks) where there is no data available. When that occurs, I want to make sure to return the latest entry *before* the "hole" in the dataset. This is a simplified version of the problem, the actual database is big (several gigabytes), the size is the reason why I want to return a subset of the data. It cannot use platform specific methods, because it needs to work on both oracle and mySQL.
**My question is**: Is there any way to do this *fast*? I would be able to write a query that gets the job done, but I am hoping there is some devil magic way of doing it that does not require lots of nested queries and aggregate functions.. | I would use Andomar's Period table idea, but I would try a slightly different final query. This assumes that your Account\_Balances table has a PK on aid and date. If you ended up with two balances for the same account for the same exact date and time then you would get some duplicate rows.
```
SELECT
P.start_date,
P.end_date,
AB1.account_id,
AB1.balance
FROM
Periods P
LEFT OUTER JOIN Account_Balances AB1 ON
AB1.date <= P.end_date
LEFT OUTER JOIN Account_Balances AB2 ON
AB2.aid = AB1.aid AND
AB2.date > AB1.date AND
AB2.date <= P.end_date
WHERE
AB2.aid IS NULL
```
If the account has no rows before or during the given period you will not get a row back for it. | You can do this in a relatively straightforward way by creating a period table, which you can join with the accounts table to create one row per account per period.
Here's an example. Let's set up some temporary tables:
```
create table #balance (
id int identity,
balance float,
date datetime,
aid int
)
create table #period (
id int identity,
startdt datetime,
enddt datetime
)
```
Enter some test data:
```
insert into #yourtable (balance, date, aid) values (4,'2009-01-01',1)
insert into #yourtable (balance, date, aid) values (5,'2009-01-10',1)
insert into #yourtable (balance, date, aid) values (6,'2009-01-10',1)
insert into #yourtable (balance, date, aid) values (7,'2009-01-16',1)
insert into #yourtable (balance, date, aid) values (2,'2009-01-01',2)
insert into #yourtable (balance, date, aid) values (3,'2009-01-10',2)
insert into #yourtable (balance, date, aid) values (4,'2009-01-10',2)
insert into #yourtable (balance, date, aid) values (5,'2009-01-16',2)
insert into #period (startdt, enddt) values ('2009-01-01','2009-01-06')
insert into #period (startdt, enddt) values ('2009-01-06','2009-01-11')
insert into #period (startdt, enddt) values ('2009-01-11','2009-01-16')
insert into #period (startdt, enddt) values ('2009-01-16','2009-01-21')
```
Now let's query all periods:
```
from #period p
```
Add one row for each balance before the end of the period:
```
left join #balance b1 on
b1.date <= p.enddt
```
Search for balances in between the balance from the first join, and the end of the period:
```
left join #balance b2 on
b2.aid = b1.aid
and b1.id < b2.id
and b2.date <= p.enddt
```
Then filter out the rows that are not the last balance for their period.
```
where
b2.aid is null
```
The b2 join basically looks for the "in-between" value, and by saying it's id is null, you say no in-between row exists. The final query looks like this:
```
select
b1.aid
, p.startdt
, b1.balance
from #period p
left join #balance b1 on
b1.date <= p.enddt
left join #balance b2 on
b2.aid = b1.aid
and b1.id < b2.id
and b2.date <= p.enddt
where
b2.aid is null
order by b1.aid, p.startdt
```
Note: the queries assume a balance with a later date always has a larger id. If you never have to balances with exactly the same end date, you can replace "b1.id < b2.id" with "b1.date < b2.date". | Selecting date intervals, doing it fast, and always returning the latest entry with the result | [
"",
"sql",
"optimization",
"aggregate",
"intervals",
""
] |
Let's say I have a windows service called "MyService" and an executable called "MyEXE" located on several computers on my network.
Is it possible (from within "MyService") to start several instances of "MyEXE" on a different/same computer, have it do some task and return a true/false result to a callback method in "MyService"?
Something like this
```
class MyService : ServiceBase
{
delegate void UpdateCallBack(int id, bool updated)
void CheckForUpdates()
{
bool updatesExist = someService.GetCurrentVersion() != currentVersion;
if(updatesExist)
{
UpdatePC("C:\Program Files\MyApp.exe", 1, UpdateComplete);
UpdatePC("\\somepc\Program Files\MyApp.exe", 1, UpdateComplete);
UpdatePC("\\mypc\Program Files\MyApp.exe", 1, UpdateComplete);
}
}
void UpdatePC(string filePath, int id, UpdateCallBack callback)
{
//This is where I am kind of lost
SomeEXERunner runner = new SomeEXERunner();
runner.Run(filePath,"-u",id,callback);
}
void UpdateComplete(int id, bool updated)
{
//do something
if(!updated)
EmailService.NotifyAdmin("PC Not updated", id);
}
}
```
Maybe I'm getting the whole architecture wrong! | You could use PSexec as Ian stated, but I think WMI is a better way try this for an example <http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx> | One thing you can do is run the PsExec tool (<http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx>) from Sysinternals in a separate process, pipe the result to a file, then parse it to figure out success/failure. | How can you run a process on another computer in .net | [
"",
"c#",
"windows-services",
"parallel-processing",
"appdomain",
""
] |
Is there a way in C# to check if an object is suspend? I have a TreeView that I need to know if it is still suspend.
```
myTreeView.BeginUpdate();
myTreeView.SuspendLayout();
// Do Stuff.
myTreeView.EndUpdate();
myTreeView.ResumeLayout();
```
Because i have this code in a recursive function I want to know if the TreeView is already been suspended. | Following on from verminity's answer you do have one option:
Use the following class
```
public class SuspendAwareTreeView : TreeView
{
public readonly T RealControl;
private int suspendCount;
public bool IsSuspended
{
get { return suspendCount > 0; }
}
public Suspendable(T real) { this.RealControl = real; }
public void SuspendLayout()
{
this.suspendCount++;
this.RealControl.SuspendLayout();
}
public void ResumeLayout()
{
this.RealControl.ResumeLayout();
this.suspendCount--;
}
}
```
Then use this class for everything internally where you need to suspend it.
Obviously this won't work if you ever pass the class around to something that only expects a control or if something else outside your control sets it.
If this is the case you would be forced to go with a variety of less than pleasant solutions:
* Write a new User control which wraps the TreeView and defers all calls to it but maintains the suspended state.
+ the resulting instance is no longer "is-a TreeView" which will cause problems.
+ maintenance effort possibly high.
+ if for some reason the treeview ever decided to suspend itself this will break.
+ new version of the runtime unlikely to break anything, you simply won't gain new functionality without effort.
* Implement an entirely new TreeViewEx which exposes this state
+ the resulting instance is no longer "is-a TreeView" which will cause problems.
+ maintenance effort possibly high
+ can never break since you have total control, can diverge from original though
+ new version of the runtime unlikely to break anything, you simply won't gain new functionality without significant effort (possibly in violation of the law/EULA).
* Violate Encapsulation
+ No alteration fo the type system, everything else continues to work.
+ Maintenance effort potentially high on runtime change
+ apps will break if the runtime changes underneath them
For your needs **if and only if** you control the runtime versions this operates on entirely (i.e. a controlled corporate environment) the following **evil** but effective hack is appropriate. So long as you test any time you upgrade it may well keep working with little effort.
```
public class ControlInvader
{
private static readonly System.Reflection.FieldInfo layoutSuspendCount =
typeof(Control).GetField("layoutSuspendCount",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
private readonly Control control;
public bool IsSuspended
{
get
{
return 0 != (byte)layoutSuspendCount.GetValue(this.control);
}
}
public Suspendable(Control control) { this.control = control; }
}
```
Attach this to your TreeView and then you can inspect the value whenever you like.
To reiterate this is *fragile* and entirely inappropriate for an environment where the version of the underlying runtime is not strictly controlled and where you can handle possible significant efforts to fix this on a breaking change.
You would do well to include a static initializer which checks if the field actually existed and was the right type and aborted if not. | Well, it's kind of late answer, but internally, the control is tracking the count and will only resume in the out most resume statement. So why do you care about it in the first place, you just make sure that you call the suspend and resume it in finally block:
```
void Recursive(Control c)
{
c.SuspendLayout();
try
{
if (existCondition) return;
// do stuff
Recursive(c);
}
finally
{
c.ResumeLayout(true);
}
}
```
This works because below is how Control internally reacts to your call in below order:
```
c.SuspendLayout() // 1st call suspends layout
c.SuspendLayout() // 2nd and subsequent call only increase the count and does nothing.
....
c.ResumeLayout(true) // this decrease the count to 1 and does NOT actually resumes layout.
c.ResumeLayout(true) // this set the count to 0 and REALLY resumes layout.
```
HTH | Check SuspendLayout | [
"",
"c#",
".net",
"windows",
"winforms",
""
] |
Okay, I've got what is probably a very easy question for you Sql gurus out there...
Given a boolean of some kind, T, I want to populate a temp table with data set A, if T is true, or data set B, if T is false. I thought this would be how to do it:
```
DECLARE @foo INT
SET @foo = null
IF (@foo is null)
BEGIN
SELECT 'foo was null' INTO #TempTable
END
ELSE
BEGIN
SELECT 'foo not null' INTO #TempTable
END
```
But this doesn't work. I get an error that reads "There is already an object named '#TempTable' in the database."
Apparently Sql is trying to create the table in each case, before it evaluates the condition...? That seems odd to me, but okay... But what's the proper way to do something like this?
**Edit: I'm in Sql Server, but I suspect that this is a more universal issue...but if I'm wrong, please let me know.** | You'll need to create your temporary table first (it should be done once):
```
CREATE TABLE #TempTable TABLE (
message VARCHAR(50)
)
```
, then issue:
```
DECLARE @foo INT
SET @foo = null
IF (@foo is null)
BEGIN
INSERT
INTO #TempTable
SELECT 'foo was null'
END
ELSE
BEGIN
INSERT
INTO #TempTable
SELECT 'foo not null'
END
```
Probably you want not a `TEMPORARY TABLE`, but a `TABLE VARIABLE` (which lives only during the session and does not persist in the database schema):
```
DECLARE @foo INT
DECLARE @TempTable TABLE (
message VARCHAR(50)
)
SET @foo = null
IF (@foo is null)
BEGIN
INSERT
INTO @TempTable
SELECT 'foo was null'
END
ELSE
BEGIN
INSERT
INTO @TempTable
SELECT 'foo not null'
END
``` | Why not use a set-based, rather than procedural solution:
```
SELECT CASE WHEN @foo is null
THEN 'foo was null'
ELSE 'foo not null'
END AS result
INTO #TempTable
``` | How to choose how to fill #temptable in sql? | [
"",
"sql",
"sql-server",
""
] |
Why `double.Epsilon != std::numeric_limits<double>::min()`?
On my PC:
`double.Epsilon == 4.9406564584124654E-324` and is defined in .NET
`std::numeric_limits<double>::min() == 2.2250738585072014e-308`
Is there a way to get 2.2250738585072014e-308 from .NET? | They're different because [`double.Epsilon`](http://msdn.microsoft.com/en-us/library/system.double.epsilon.aspx) returns the smallest *representable* value. [`numeric_limits<double>::min()`](http://msdn.microsoft.com/en-us/library/69bwfeks.aspx) returns the smallest *normalized* value.
Basically `double.Epsilon` is the equivalent to `numeric_limits<double>::denorm_min()`.
The easiest way of getting the equivalent in .NET is probably to work out the bit pattern for the minimal normalized number and use [`BitConverter.Int64BitsToDouble`](http://msdn.microsoft.com/en-us/library/system.bitconverter.int64bitstodouble.aspx). | Well you could use C++/CLI to return the value:
```
double epsilon() { return std::numeric_limits<double>::min(); }
```
Why would you want to though? Why do they have to be the same? You should try to avoid skating on the edges of your floating point numbers. | double.Epsilon vs. std::numeric_limits<double>::min() | [
"",
".net",
"c++",
"floating-point",
""
] |
Is there a way of getting a unique identifier of an instance?
`GetHashCode()` is the same for the two references pointing to the same instance. However, two different instances can (quite easily) get the same hash code:
```
Hashtable hashCodesSeen = new Hashtable();
LinkedList<object> l = new LinkedList<object>();
int n = 0;
while (true)
{
object o = new object();
// Remember objects so that they don't get collected.
// This does not make any difference though :(
l.AddFirst(o);
int hashCode = o.GetHashCode();
n++;
if (hashCodesSeen.ContainsKey(hashCode))
{
// Same hashCode seen twice for DIFFERENT objects (n is as low as 5322).
Console.WriteLine("Hashcode seen twice: " + n + " (" + hashCode + ")");
break;
}
hashCodesSeen.Add(hashCode, null);
}
```
I'm writing a debugging addin, and I need to get some kind of ID for a reference which is unique during the run of the program.
I already managed to get internal ADDRESS of the instance, which is unique until the garbage collector (GC) compacts the heap (= moves the objects = changes the addresses).
Stack Overflow question *[Default implementation for Object.GetHashCode()](https://stackoverflow.com/questions/720177/default-implementation-for-object-gethashcode)* might be related.
The objects are not under my control as I am accessing objects in a program being debugged using the debugger API. If I was in control of the objects, adding my own unique identifiers would be trivial.
I wanted the unique ID for building a hashtable ID -> object, to be able to lookup already seen objects. For now I solved it like this:
```
Build a hashtable: 'hashCode' -> (list of objects with hash code == 'hashCode')
Find if object seen(o) {
candidates = hashtable[o.GetHashCode()] // Objects with the same hashCode.
If no candidates, the object is new
If some candidates, compare their addresses to o.Address
If no address is equal (the hash code was just a coincidence) -> o is new
If some address equal, o already seen
}
``` | The reference *is* the unique identifier for the object. I don't know of any way of converting this into anything like a string etc. The value of the reference will change during compaction (as you've seen), but every previous value A will be changed to value B, so as far as safe code is concerned it's still a unique ID.
If the objects involved are under your control, you could create a mapping using [weak references](http://msdn.microsoft.com/en-us/library/system.weakreference.aspx) (to avoid preventing garbage collection) from a reference to an ID of your choosing (GUID, integer, whatever). That would add a certain amount of overhead and complexity, however. | ## .NET 4 and later only
Good news, everyone!
The perfect tool for this job is built in .NET 4 and it's called [`ConditionalWeakTable<TKey, TValue>`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2). This class:
* can be used to associate arbitrary data with managed object instances much like a dictionary (although it *is* not a dictionary)
* does not depend on memory addresses, so is immune to the GC compacting the heap
* does not keep objects alive just because they have been entered as keys into the table, so it can be used without making every object in your process live forever
* uses reference equality to determine object identity; moveover, class authors cannot modify this behavior so it can be used *consistently* on objects of any type
* can be populated on the fly, so does not require that you inject code inside object constructors | .NET unique object identifier | [
"",
"c#",
"unique",
"hashcode",
"gethashcode",
""
] |
I've got a wpf listbox that is bound to a datatable. At some times, I want to programmaticly change the selection of the listbox. I know the text of the item I want to select. But it doesn't work to set the listbox1.SelectedItem to the text I want because the type of the SelectedItem is System.Data.DataRowView.
If I have the text I want to select and the DataRow that I want to select, what is the easiest way select the associated row in the list box? | Search through your `DataSet` and find the appropriate `DataRow`. Then set `SelectedItem` to that `DataRow`. | If you know the text, then it would be:
```
ListBox1.SelectedValue = ListBox1.Items.FindByText("Two").Value;
```
You can also use the SelectedIndex property to set the selected value by 0-based index. | Set selected item in a databound list box | [
"",
"c#",
"wpf",
""
] |
I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific methods they can readily be called.
This works fine, but I have read numerous posts about not inheriting from STL. Can someone provide a concrete advice of how I might write the code below in a better way?
```
class Item
{
int a;
int b;
int c;
int SpecialB()
{
return a * b + c;
}
};
class ItemList : public std::vector<Item>
{
int MaxA()
{
if( this->empty() )
throw;
int maxA = (*this)[0].a;
for( int idx = 1; idx < this->size(); idx++ )
{
if( (*this)[idx].a > maxA )
{
maxA = (*this)[idx].a;
}
}
return maxA;
}
int SpecialB()
{
if( this->empty() )
throw;
int specialB = (*this)[0].SpecialB();
for( int idx = 1; idx < this->size(); idx++ )
{
if( (*this)[idx].SpecialB() < specialB )
{
specialB -= (*this)[idx].c;
}
}
return specialB;
}
int AvgC()
{
if( this->empty() )
throw;
int cSum = 0;
for( int idx = 0; idx < this->size(); idx++ )
{
cSum += (*this)[idx].c;
}
return cSum / this->size(); // average
}
};
```
**EDIT**: Thanks for a bunch of thoughtful answers. I will create helper functions instead and from now on will never inherit from STL containers. | why you need extend vector in this way?
use standard `<algorithm>` with your functors.
e.g.
[`std::min_element`](http://en.cppreference.com/w/cpp/algorithm/min_element), [`std::max_element`](http://en.cppreference.com/w/cpp/algorithm/max_element)
```
int max_a = std::max_element
(
v.begin(),
v.end(),
boost::bind(
std::less< int >(),
bind( &Item::a, _1 ),
bind( &Item::a, _2 )
)
)->a;
```
[`std::accumulate`](http://en.cppreference.com/w/cpp/algorithm/accumulate) - for calculate avarage
```
const double avg_c = std::accumulate( v.begin(), v.end(), double( 0 ), boost::bind( Item::c, _1 ) ) / v.size(); // ofcourse check size before divide
```
your ItemList::SpecialB() could be rewrited as:
```
int accumulate_func( int start_from, int result, const Item& item )
{
if ( item.SpecialB() < start_from )
{
result -= item.SpecialB();
}
return result;
}
if ( v.empty() )
{
throw sometghing( "empty vector" );
}
const int result = std::accumulate( v.begin(), v.end(), v.front(), boost::bind( &accumulate_func, v.front(), _1, _2 ) );
```
BTW: if you don't need access to members, you don't need inheritance. | This is a **bad** idea.
There are a lot of reasons you shouldn't derive from STL classes, foremost of which is that they're not designed for it. Vector doesn't have a virtual destructor, so if you extend it, the superclass's destructor may not be called properly and you'll get memory leaks.
For more on this, see this answer on why *not* to derive from `std::string`. Many of the same points apply:
[Constructor doesn’t work for class inherited from std::string](https://stackoverflow.com/questions/555612/constructor-doesnt-work-for-class-inherited-from-stdstring/555633#555633)
* No virtual destructor
* No protected functions (so you gain nothing by inheriting)
* Polymorphism won't work, and you'll get object slicing. `std::vector` is assignable, but if you add your own fields they won't get copied on assignment if you assign from a vector pointer or vector reference. This is because `vector`'s `operator=` does not know about your fields.
For all of these reasons, you're better off making utility functions than extending when it comes to STL. | Advice on a better way to extend C++ STL container with user-defined methods | [
"",
"c++",
"stl",
""
] |
I have a site that gets just about 100 people everyday but I got this error message when log in as a user:
```
Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1203): User mexautos_Juan already has more than 'max_user_connections' active connections in /home/mexautos/public_html/kiubbo/data/model.php on line 26
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli in /home/mexautos/public_html/kiubbo/data/model.php on line 87
Query failed
```
I refresh the page a couple of time and now its ok, but since I dont have that many users I suspect the error its in my code, where should I look for it?
Thx
Edit: this is the model file:
```
<?php
/*
Model is the base class from which the other
model classes will be derived. It offers basic
functionality to access databases
*/
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
class Model {
private $created;
private $modified;
static function getConnection()
{
/*
Connect to the database and return a
connection or null on failure
*/
$db = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(!$db) {
echo mysql_error();
throw new Exception('Could not connect to database', EX_NO_DATABASE_CONNECTION);
}
return $db;
}
static function execSQL($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the resultset
*/
$db = null;
$results = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Model::closeConnection($db);
return $results;
}
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Model::closeConnection($db);
return $lastid;
}
function delete($table, $id, $conditions = '')
{
$query = "delete from $table where id = $id";
try
{
$db = Model::getConnection();
$results = Model::execSQL($query);
if(!$results){
throw new Exception('Could not delete this object', EX_DELETE_ERROR);
}
return $results->num_rows;
}
catch(Exception $e)
{
throw $e;
}
}
static function closeConnection($db)
{
$db->close();
}
function getCreated()
{
return $this->created;
}
function setCreated($value)
{
$this->created = $value;
}
function getModified()
{
return $this->modified;
}
function setModified($value)
{
$this->modified = $value;
}
}
?>
``` | this should fix your problem, but i didn't test it. the difference: if `getConnection()` is called the first time, a connection is made and stored. the rest of the time, the already established connection is used.
i removed the action in closeConnection, because that would make the first change useless. altough it would be nicer to remove the closeConnection call from execSQL.
normally (as far as i know), the database connection automatically closes when the script terminates (as long as mysqli doesn't support persistance). but it would be better to call (a working) closeConnection manually after all the database-stuff is finished.
```
<?php
class Model {
private $created;
private $modified;
private static $db = false;
static function getConnection()
{
/*
Connect to the database and return a
connection or null on failure
*/
if (self::$db === false) {
self::$db = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME);
}
if(!self::$db) {
echo mysql_error();
throw new Exception('Could not connect to database', EX_NO_DATABASE_CONNECTION);
}
return self::$db;
}
static function closeConnection()
{
// self::$db->close();
}
// moar functions (...)
}
?>
```
and ... i'd recommend using an existing database access abstraction layer to avoid such problems in the future. | Every hit on your website that opens a database connection is using the same database username and password. Your database settings have limited the number of connections on a per-user basis, and you are going over that maximum.
Check out this MySQL manual page: <http://dev.mysql.com/doc/refman/5.0/en/user-resources.html>
Your model class isn't that great, as it seems to be opening and closing a database connection on every individual query. This is a very bad use of resources, as opening and closing connections are expensive. I would write a destructor function on your model object that called $db->close(), and change getConnection() to open a connection once, and then return it every time after that. This means converting your model class to a non-static usage, but it would be much easier on the database to do so.
Anyhow, it's possible with all the connecting and deconnecting your class is doing that MySQL has connections backing up and they aren't clearing fast enough before you hit your max user limit. | Database Error: [mysqli.mysqli]: User already has more than 'max_user_connections' active connections | [
"",
"php",
"mysql",
"database",
"mysqli",
""
] |
I was looking for a simple function to get the week of the month (rather than the easy week of the year) in a mysql query.
The best I could come up with was:
```
WEEK(dateField) - WEEK(DATE_SUB(dateField, INTERVAL DAYOFMONTH(dateField)-1 DAY)) + 1
```
I'd love to know if I'm reinventing the wheel here, and if there is an easier and cleaner solution? | AFAIK, there is no standard on the first week of month.
First week of year is the week containing `Jan 4th`.
How do you define first week of month?
**UPDATE:**
You'll need to rewrite your query like this:
```
SELECT WEEK(dateField, 5) -
WEEK(DATE_SUB(dateField, INTERVAL DAYOFMONTH(dateField) - 1 DAY), 5) + 1
```
so that the year transitions are handled correctly, and the weeks start on `Monday`.
Otherwise, your query is fine. | There is an alternative that's sometimes used in reporting databases. It's to create a table, let's call it ALMANAC, that has one row per date (the key), and has every needed attribute of the date that might be useful for reporting purposes.
In addition to the week of the month column, there could be a column for whether or not the date is a company holiday, and things like that. If your company had a fiscal year that starts in July or some other month, you could include the fiscal year, fiscal month, fiscal week, etc. that each date belongs to.
Then you write one program to populate this table out of thin air, given a range of dates to populate. You include all the crazy calendar calculations just once in this program.
Then, when you need to know the attribute for a date in some other table, you just do a join, and use the column. Yes, it's one more join. And no, this table isn't normalized. But it's still good design for certain very specific needs. | Function for week of the month in mysql | [
"",
"sql",
"mysql",
"function",
""
] |
Say you have
```
char *= "name:454";
```
What is the best way to parse name and the number, thus
std:string id would equal to "name";
double d would equal to 454;
STL please, no boost. | ```
#include <iostream>
#include <sstream>
#include <string>
int main() {
/* output storage */
std::string id;
double d;
/* convert input to a STL string */
std::string s("name:454");
size_t off = std::string::npos;
/* smart replace: parsing is easier with a space */
if ((off = s.find(':')) != std::string::npos) { // error check: all or none
s = s.replace(off, 1, 1, ' ');
std::istringstream iss(s);
iss >> id >> d;
std::cout << "id = " << id << " ; d = " << d << '\n';
}
return 0;
}
```
Though, I'd just write my own parser or use the C scanner function for speed. | You want to look at the [`strtok`](http://www.cplusplus.com/reference/clibrary/cstring/strtok.html) function using `':'` as the token. Here is an example:
```
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "name:454";
char* c = strtok(str, ":");
while (c != NULL)
{
printf("%s\n", c);
c = strtok(NULL, ":");
}
return 0;
}
``` | fast way to parse a configuration | [
"",
"c++",
"stl",
""
] |
Does anyone know of a simple Web MVC framework and Web Server for Java that is open source?
This is intended as a simple web server and framework for students in a tutorial class.
It's important these both the web server and MVC framework are simple, OSS so students can easily peer under the hood and the tutors can easily support it, learn it and teach it.
**UPDATE** The suggestion I can avoid the single jar issue by unpacking several jars and joining them into one is a good suggestion. I'll definitely take it, and thus relax the single jar requirements | You could have a look at [Stripes](http://www.stripesframework.org/), which does not have any compile time dependencies (apart from itself, apparently) at all and only requires [COS](http://servlets.com/cos/) and [Commons Logging](http://commons.apache.org/logging/) during runtime.
It's also very lightweight and quite easy to pick up. | I'm very impressed with the [Play! Framework](http://www.playframework.org/) which I think would meet most of your requirements in terms of MVC. It's a lot like Rails etc, and supports annotations-based Hibernate persistence out of the box. The only three 'odd' things worth mentioning are that it:
1. I think it has its own built in implementation of properties (using reflection and byte code modifications)
2. It uses exceptions for flow control
3. Its templating may be a little basic for some requirements, but on the whole it's fine for simpler stuff.
None of these is a showstopper in terms of producing a good website quickly, but points 1 and 2 may put you off if you are trying to teach Java at the same time. | Simple Web Server and MVC framework for Java | [
"",
"java",
"model-view-controller",
""
] |
In a module of mine, I'd like to output the node teaser. The node has CCK fields, and I'd like them to be displayed accordingly to the visibility settings you can choose in the content types / field settings administration area.
But when I do:
```
$html = theme('node', $n);
```
the resulting teaser won't contain the CCK fields, only title and body.
What other theming function do I need to call?
The node contains fields such as an image and a node reference. I suppose I could write the HTML manually, but it seems to me better to use the provided theming functions... | <http://api.drupal.org/api/function/node_view/6>
```
$node = node_load($n);
$html = node_view($node,TRUE);
```
Then you can select the fields to display on **Content Type>Display Fields** after that, you can edit the theme of that teaser via [contemplate module](http://drupal.org/project/contemplate) or **node-content\_type.tpl.php** on the theme folder. | <http://drupal.org/node/362068#comment-1216250> you can achieve it using views 2 | Drupal CCK: how to output a node teaser with its fields? | [
"",
"php",
"drupal",
"drupal-6",
"cck",
""
] |
Has anyone ever actually used `stackalloc` while programming in C#? I am aware of what is does, but the only time it shows up in my code is by accident, because Intellisense suggests it when I start typing `static`, for example.
Although it is not related to the usage scenarios of `stackalloc`, I actually do a considerable amount of legacy interop in my apps, so every now and then I could resort to using `unsafe` code. But nevertheless I usually find ways to avoid `unsafe` completely.
And since stack size for a single thread in .Net is ~1Mb (correct me if I'm wrong), I am even more reserved from using `stackalloc`.
Are there some practical cases where one could say: "this is exactly the right amount of data and processing for me to go unsafe and use `stackalloc`"? | The sole reason to use `stackalloc` is performance (either for computations or interop). By using `stackalloc` instead of a heap allocated array, you create less GC pressure (the GC needs to run less), you don't need to pin the arrays down, it's faster to allocate than a heap array, an it is automatically freed on method exit (heap allocated arrays are only deallocated when GC runs). Also by using `stackalloc` instead of a native allocator (like malloc or the .Net equivalent) you also gain speed and automatic deallocation on scope exit.
Performance wise, if you use `stackalloc` you greatly increase the chance of cache hits on the CPU due to the locality of data. | I have used stackalloc to allocate buffers for [near] realtime DSP work. It was a very specific case where performance needed to be as consistent as possible. Note there is a difference between consistency and overall throughput - in this case I wasn't concerned with heap allocations being too slow, just with the non determinism of garbage collection at that point in the program. I wouldn't use it in 99% of cases. | Practical use of `stackalloc` keyword | [
"",
"c#",
"keyword",
"stackalloc",
""
] |
I want to implement a method like this:
```
public Iterator<File> getFiles(String root) {
// return an Iterator looping through all files in root and all files in sub-directories of roots (recursively)
}
```
In C#, this can easily be implemented with the `yield return` keyword. In Java, I suspect I have to end up writing a lot of complicated code to get it done. Is there any good solution to this problem?
**Edit:** I want the returned Iterator to be "lazy", i.e. only return a new File when `next()` is invoked. (That is the behavior C#'s `yield return` offers.) | This code might be your solution <http://snippets.dzone.com/posts/show/3532> | [Apache Commons FileUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html) offers [iterator](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#iterateFiles%28java.io.File,%20java.lang.String[],%20boolean%29) methods to iterate through directories and subdirectories. That does what you want and should save you a lot of work.
e.g.
`Iterator fi = iterateFiles(new File("."), String[] {".csv"}, true)`
to find all .csv files below the current directory. | How to implement a method to return Iterator of files recursively in Java | [
"",
"java",
"iterator",
""
] |
The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num\_to\_bytes()). | Came across the same issue. Starting from python 3.2, you can use [`int.to_bytes`](https://docs.python.org/3/library/stdtypes.html#int.to_bytes):
```
>>> (2**100).to_bytes(16, byteorder='big')
b'\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
``` | Do you mean *something* like this:
```
def num_to_bytes(num):
bytes = []
num = abs(num) # Because I am unsure about negatives...
while num > 0:
bytes.append(chr(num % 256))
num >>= 8
return ''.join(reversed(bytes))
def bytes_to_num(bytes):
num = 0
for byte in bytes:
num <<= 8
num += ord(byte)
return num
for n in (1, 16, 256, 257, 1234567890987654321):
print n,
print num_to_bytes(n).encode('hex'),
print bytes_to_num(num_to_bytes(n))
```
Which returns:
```
1 01 1
16 10 16
256 0100 256
257 0101 257
1234567890987654321 112210f4b16c1cb1 1234567890987654321
```
I'm just not sure what to do about negatives... I'm not that familiar with bit twidling.
**EDIT:** Another solution (which runs about 30% faster by my tests):
```
def num_to_bytes(num):
num = hex(num)[2:].rstrip('L')
if len(num) % 2:
return ('0%s' % num).decode('hex')
return num.decode('hex')
def bytes_to_num(bytes):
return int(bytes.encode('hex'), 16)
``` | Efficient arbitrary-sized integer packing in Python | [
"",
"python",
"byte",
""
] |
I really like the PHP function strtotime(), but the [user manual](http://ca.php.net/strtotime) doesn't give a complete description of the supported date formats. It only gives a few examples like "10 September 2000", "+1 week 2 days 4 hours 2 seconds", and "next Thursday".
Where can I find a complete description? | I can't find anything official, but I saw [a tutorial](http://www.programmers-corner.com/viewTutorial.php/80) that says strtotime()
uses GNU Date Input Formats. Those are described in detail [in the GNU manual](http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html).
One discrepancy I notice is that "next" doesn't match the
behaviour described in the GNU manual. Using strtotime(), "next Thursday" will give you the same result as "Thursday", unless today is a Thursday.
If today is a Thursday, then
* strtotime("Thursday") == strtotime("today")
* strtotime("next Thursday") == strtotime("today + 7 days")
If today is not a Thursday, then
* strtotime("Thursday") == strtotime("next Thursday")
I'm using PHP 5.2.6.
**Update:**
I guess the user manual has been updated since I posted this, or else I was blind. It now contains a link to the [Date and Time Formats chapter](http://php.net/manual/en/datetime.formats.php), that includes a section on [relative formats](http://php.net/manual/en/datetime.formats.relative.php). | You can start to trace what it is doing by looking at the following C code:
<http://cvs.php.net/viewvc.cgi/php-src/ext/date/php_date.c>
Search for PHP\_FUNCTION(strtotime)
Also this is the main regex parsing:
<http://cvs.php.net/viewvc.cgi/php-src/ext/date/lib/parse_date.re>
Good luck | What date formats does the PHP function strtotime() support? | [
"",
"php",
"datetime",
""
] |
We've got some fraction information stored in the database, e.g. ¾ ½
Short of doing a search and replace, are there any inbuilt PHP functions that will automatically convert these to proper html entities? | You can use the [htmlentities() function](https://www.php.net/htmlentities). This will replace all special characters with their HTML equivalent. It should do the job. | [htmlentities](http://de3.php.net/manual/en/function.htmlentities.php).
But you probably don't need to. Serve your page in an encoding that includes them (UTF-8, ISO-8859-1) and you can include those as literal, unescaped characters. | Converting fractions to html entities | [
"",
"php",
"html",
"string",
"html-entities",
"fractions",
""
] |
I have a Repeater that takes all my images in a folder and display it. But what code changes must I make to only allow lets say Image1.jpg and Image2.jpg to be displayed in my repeater. I don"t want the repeater to display ALL the images in my folder.
My Repeater
```
<asp:Repeater ID="repImages" runat="server" OnItemDataBound="repImages_ItemDataBound">
<HeaderTemplate><p></HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hlWhat" runat="server" rel="imagebox-bw">
<asp:Image ID="imgTheImage" runat="server" />
</asp:HyperLink>
</ItemTemplate>
<FooterTemplate></p></FooterTemplate>
</asp:Repeater>
```
My Code behind - PAGE LOAD
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
repImages.DataSource = oList;
repImages.DataBind();
}
}
```
My Code behind - Repeater's ItemDataBound event code
```
protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem ||
e.Item.ItemType == ListItemType.Item)
{
string sFile = e.Item.DataItem as string;
//Create the thumblink
HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
hlWhat.NavigateUrl = ResolveUrl("~/pics/" + sFile );
hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
hlWhat.Attributes["rel"] = "imagebox-bw";
Image oImg = e.Item.FindControl("imgTheImage") as Image;
oImg.ImageUrl = ResolveUrl("~/createthumb.ashx?gu=/pics/" + sFile + "&xmax=100&ymax=100" );
}
}
```
**ANSWER:**
My updated Page Load
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
string[] extensions = { "*.jpg", "*.png" };
List<string> files = new List<string>();
foreach (string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(sBasePath, filter));
oList.Add(System.IO.Path.GetFileName(filter));
}
repImages.DataSource = oList;
repImages.DataBind();
}
``` | What format are the image names that you want to display? If you know that you can construct a filter to use when listing the contents of the directory:
```
string[] files = Directory.GetFiles(folder, "*1.jpg");
```
Will list all the jpg files that end in "1"
EDIT:
Instead of having:
```
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
```
You'd have:
```
string[] files = System.IO.Directory.GetFiles(sBasePath, "*.jpg")
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
```
EDIT 2:
I've done a quick search and it looks like Get Files won't take multiple extensions, so you'll have to search for each type of extension separately:
```
string[] extensions = {"*.jpg" , "*.png" };
List<string> files = new List<string>();
foreach(string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(path, filter));
}
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
``` | Easiest way to is load them all into a List<> and then use Linq to filter out the ones you want.
**VS2005**
```
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(@"D:\downloads\_Installs").GetFiles();
ArrayList exefiles = new ArrayList();
foreach (FileInfo f in files)
{
if (f.Extension == ".exe") // or whatever matching you want to do.
{
exefiles.Add(f);
}
}
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
```
**VS2008**
```
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(@"D:\downloads\_Installs").GetFiles();
var exefiles = from FileInfo f in files
where f.Extension == ".exe"
select f;
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
``` | How to only display certain images in a folder into a Repeater in ASP.NET | [
"",
"c#",
"asp.net",
"image",
"repeater",
"itemdatabound",
""
] |
This is a simplified version of a query I have. Say for each customer that has made an order, I want to know what percentage of their total order value was for green items.
There can't be multiple items in an order, but it's possible for the order value to be zero so I want to avoid division errors. (And no, I am not able to change the database in any way.)
What's the best way to do this? EDIT: Omitting zero-totals is fine actually, hence accepted answer.
```
SELECT order.customer,
SUM
(
CASE items.color WHEN 'Green' THEN order.value
ELSE 0 END
) * 100 / sum(order.value) AS percentage,
SUM(order.value) AS total_value
FROM orders
INNER JOIN item
ON order.item_id = item.item_id
GROUP BY order.customer
``` | Add
```
having sum(order.value) <> 0
```
After your group by | See here: [SQL Server efficient handling of divide by zero](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-server-efficient-handling-of-divide) | Getting out of divide by zero in simple query | [
"",
"sql",
"database",
""
] |
im wanting to know the fastest way to access my globals... they will only change in the beta testing phase. before we go live. from then on they wont change ever.
im thinking that there is an overhead in getting stuff from web.config also its neater code wise to write App.HostUrl instead of ConfigurationManager.AppSettings["HostUrl"].ToString()
app.cs
```
public class App {
public const string HostUrl = "http://www.{domain}.co.uk";
public const string iHostUrl = "http://img.{domain}.co.uk";
}
```
or
web.config
```
<appSettings>
<add key="HostUrl" value="http://www.{domain}.co.uk" />
<add key="iHostUrl" value="http://img.{domain}.co.uk" />
<appSettings>
``` | A const will be faster but that limits our deployment options. As an alternative, why don't you create a static variables and put the appsetting in there in your Application\_Start (in global.asax).
```
public class App {
public static string HostUrl;
public static string iHostUrl;
}
```
In Global.asax.cs:
```
void Application_Start(object sender, EventArgs e)
{
App.HostUrl = ConfigurationManager.AppSettings["HostUrl"].ToString();
App.iHostUrl = ConfigurationManager.AppSettings["iHostUrl"].ToString();
}
``` | Web.config is parsed by your application anyway, so in practise there's no extra overhead associated with it. Whether it has appsettings or not, the file is still opened, read and parsed.
You should be worrying about real performance bottlenecks in your application rather than something it does *once* when it starts up. You're not going to achieve a noticeable boost in performance by not storing your settings in web.config. | Is using a const in a class in App_Code quicker/faster than using appSettings in config.web on a webforms asp.net app? | [
"",
"c#",
".net",
"asp.net",
"web-config",
""
] |
I have a script that is running slowly and I was wondering how I could time it and see which fixes improve the speed. Is there some sort of a PHP timer?
Update: Thought I should clarify... The script that is running slowly is my mailing list script that sends an email to everyone on the list. So I am looping through an array of subscribers and sending them an email one by one. It's so slow that I thought it would be interesting to see how long it took to iterate though the array. So I'm looking for a quick and easy way to test that. | I ended up using a timer class I found similar to this one: <http://forum.codecall.net/php-tutorials/4254-php-timer-class.html>
I just started a timer at the beginning of my loop and logged the duration at the end of each iteration. Found out, on average, it was taking between 3 and 4 seconds per email! Five minutes per email blast is a little too much. Time to refactor... | You can measure the loading time of your page and adjust where needed.
I like websites like <http://www.phpbench.com/> which tell you more about the basic needs in php.
Offcourse writing php using Zend Framework doesn't really say anything about your code actually. Do you follow the zend coding standards ?
<http://www.php.net/getrusage> might be usefull for your timing issue.
Good luck !
edit : extra link for the getrusage function ( reffered to on the php.net page as well ).
edit 2 : For your mailing list you could check phpbench.com for example with the count before the loop which saves some time.
How are you sending your mails ? That could be a bottleneck.
Good luck ! | How to go about speed testing my PHP script? | [
"",
"php",
"zend-framework",
"timer",
"performance",
""
] |
I have a class that is serialized to a XML file. There are several properties that are rarely used but always created. If I delete them within the XML the deserialization still works, because they have the default value.
These unnecessary (bool) attributes make the XML harder to read.
Can I somehow tell C# to omit elements or attributes that still have default value? | Specify the [DefaultValueAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx), and if the value matches, it won't be output. | Rowland has the answer for simple values. For more complex scenarios, you can add a method called `public bool ShouldSerializeFoo()` (for property `Foo`) - it it returns `false`, it won't get serialized. | How to tell C# to omit creation of attributes that are default during serialization? | [
"",
"c#",
"serialization",
""
] |
Passing two parameters to a new thread on the threadpool can sometimes be complicated, but it appears that with lambda expressions and anonymous methods, I can do this:
```
public class TestClass
{
public void DoWork(string s1, string s2)
{
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
try
{
TestClass test = new TestClass();
string s1 = "Hello";
string s2 = "World";
ThreadPool.QueueUserWorkItem(
o => test.DoWork(s1, s2)
);
}
catch (Exception ex)
{
//exception logic
}
```
Now, I've certainly simplified this example, but these points are key:
* The string objects being passed are immutable and therefore threadsafe
* The s1 and s2 variables are declared within the scope of the try block, which I exit immediately after queuing the work to the thread pool, so the s1 and s2 variables are never modified after that.
Is there something wrong with this?
The alternative is to create a new class that implements an immutable type with 3 members: test, s1, and s2. That just seems like extra work with no benefit at this point. | There is nothing wrong with this. The compiler is essentially doing automatically what you described as your alternative. It creates a class to hold the captured variables (test, s1 and s2) and passes a delegate instance to the lambda which is turned into a method on the anonymous class. In other words, if you went ahead with your alternative you would end up with soemthing very similar to what the compiler just generated for you. | For this particular example, no there is nothing wrong here. The state you've passed into the other thread is wholely contained and none of the types involve have any thread affinity issues. | ThreadPool.QueueUserWorkItem with a lambda expression and anonymous method | [
"",
"c#",
"multithreading",
"lambda",
"anonymous-methods",
"threadpool",
""
] |
I have a bunch of floating point numbers (Java doubles), most of which are very close to 1, and I need to multiply them together as part of a larger calculation. I need to do this *a lot*.
The problem is that while Java doubles have no problem with a number like:
```
0.0000000000000000000000000000000001 (1.0E-34)
```
they can't represent something like:
```
1.0000000000000000000000000000000001
```
Consequently of this I lose precision rapidly (the limit seems to be around 1.000000000000001 for Java's doubles).
I've considered just storing the numbers with 1 subtracted, so for example 1.0001 would be stored as 0.0001 - but the problem is that to multiply them together again I have to add 1 and at this point I lose precision.
To address this I could use BigDecimals to perform the calculation (convert to BigDecimal, add 1.0, then multiply), and then convert back to doubles afterwards, but I have serious concerns about the performance implications of this.
Can anyone see a way to do this that avoids using BigDecimal?
**Edit for clarity**: This is for a large-scale collaborative filter, which employs a gradient descent optimization algorithm. Accuracy is an issue because often the collaborative filter is dealing with very small numbers (such as the probability of a person clicking on an ad for a product, which may be 1 in 1000, or 1 in 10000).
Speed is an issue because the collaborative filter must be trained on tens of millions of data points, if not more. | Yep: because
```
(1 + x) * (1 + y) = 1 + x + y + x*y
```
In your case, `x` and `y` are very small, so `x*y` is going to be *far* smaller - way too small to influence the results of your computation. So as far as you're concerned,
```
(1 + x) * (1 + y) = 1 + x + y
```
This means you can store the numbers with 1 subtracted, and instead of multiplying, just add them up. As long as the results are always much less than 1, they'll be close enough to the mathematically precise results that you won't care about the difference.
*EDIT*: Just noticed: you say *most* of them are very close to 1. Obviously this technique won't work for numbers that are not close to 1 - that is, if `x` and `y` are large. But if one is large and one is small, it might still work; you only care about the magnitude of the product `x*y`. (And if both numbers are not close to 1, you can just use regular Java `double` multiplication...) | Perhaps you could use logarithms?
Logarithms conveniently reduce multiplication to addition.
Also, to take care of the initial precision loss, there is the function log1p (at least, it exists in C/C++), which returns log(1+x) without any precision loss. (e.g. log1p(1e-30) returns 1e-30 for me)
Then you can use expm1 to get the decimal part of the actual result. | How to handle multiplication of numbers close to 1 | [
"",
"java",
"math",
"floating-point",
"bigdecimal",
"rounding-error",
""
] |
Which methods and interfaces do you always implement in your classes?
Do you always override equals()? If you do, do you also do hashcode()? toString()? Do you make it a habit to implement the Comparable interface?
I've just written some code where I needed to implement compareTo() and override equals() to get my program to work in a sane manner; I now start seeing ways of using these everywhere...
What do y'all think? | I usually don't implement things in advance unless I need them.
If my class contains data members and I plan to store it somewhere, I will usually implement equals, hashCode, and comparable.
However, I found that most of my classes do not have this issue so there's no point to do it. For example, if your class revolves around functionality on other objects rather than data, why bother? If you have one instance or is organized hierarchically (e.g., a GUI widget or window), why bother?
Don't implement things you don't need, but always make sure to check whether they are needed or not because Java will generally not warn you.
Also, make sure to use your IDE or something like Apache commons to generate these functions. There is rarely a need to hand-code them.
As for toString, I rarely implement it until I find myself debugging and needing a better presentation in the Eclipse debugger (e.g., instead of object ID). I am afraid of implicit converts and never use toString when generating output. | (Almost) Always `toString()`.
It is usually helpful for debugging purposes. | What methods and interfaces do you (almost) always implement in classes? | [
"",
"java",
""
] |
I've recently been building a test framework for a bit of C# I've been working on. I have NUnit set up and a new project within my workspace to test the component. All works well if I load up my unit tests from Nunit (v2.4), but I've got to the point where it would be really useful to run in debug mode and set some break points.
I've tried the suggestions from several guides which all suggest changing the 'Debug' properties of the test project:
```
Start external program: C:\Program Files\NUnit 2.4.8\bin\nunit-console.exe
Command line arguments: /assembly: <full-path-to-solution>\TestDSP\bin\Debug\TestDSP.dll
```
I'm using the console version there, but have tried the calling the GUI as well. Both give me the same error when I try and start debugging:
```
Cannot start test project 'TestDSP' because the project does not contain any tests.
```
Is this because I normally load \DSP.nunit into the Nunit GUI and that's where the tests are held?
I'm beginning to think the problem may be that VS wants to run it's own test framework and that's why it's failing to find the NUnit tests?
**Edit**: To those asking about test fixtures, one of my .cs files in the TestDSP project looks roughly like this:
```
namespace Some.TestNamespace
{
// Testing framework includes
using NUnit.Framework;
[TestFixture]
public class FirFilterTest
{
[Test]
public void Test01_ConstructorTest()
{
...some tests...
}
}
}
```
...I'm pretty new to C# and the NUnit test framework so it's entirely possible I've missed some crucial bit of information ;-)
**Final Solution**: The big problem was the project I'd used. If you pick `Other Languages -> Visual C# -> Test -> Test Project` ...when you're choosing the project type, Visual Studio will try and use it's own testing framework as far as I can tell. You should pick a **normal** C# class library project instead and then the instructions in my selected answer will work. | I use the same technique as you are trying Jon, without the /assembly flag, i.e.
```
Start External Program: C:\Program Files\NUnit 2.4.8\bin\nunit.exe
Command line arguments: "<path>\bin\Debug\Quotes.Domain.Tests.dll"
```
Does TestDSP.dll contain all your TestFixtures?
As my test project is not the startup project in the solution, I run my tests by right-clicking on the test project and choosing Debug --> Start New Instance | When I need to debug my NUnit tests, I simply attach to the NUnit GUI application `nunit-agent.exe` using "Debug|Attach to Process" and run the tests from the GUI. Any breakpoints in my tests (or the code they're testing) are hit. Am I misunderstanding your question, or will that work for you? | How do I run NUnit in debug mode from Visual Studio? | [
"",
"c#",
"visual-studio-2008",
"unit-testing",
"testing",
"nunit",
""
] |
Which (commercial or free) installer tool would you recommend to replace [InstallAnywhere](https://www.flexerasoftware.com/producer/products/software-installation/installanywhere/) as the installer for a Java EE application? What do you specifically like about it, and what are its downsides?
Some requirements:
* Must support **running custom Java code** as part of installation procedure
* Must support Windows, including latest 64-bit versions like Windows Server 2008; support for other target operating systems is a plus
* Must be able to install a bundled application server (such as [Resin](http://caucho.com/) or [Tomcat](http://tomcat.apache.org/)) as a service on Windows
* Must support basic stuff like copying and moving files around, editing configuration files, extracting ZIPs, etc.
* (Must support bundling a specific version of JRE; at the very least by including a ZIP to be extracted)
Edit: a few more points:
* Preferably does not depend on a preinstalled JRE (or any other 3rd party runtime environment or library) on target machine; in other words, can produce an independent Windows .exe (or .msi)
* The tool should preferably be cross-platform so that installer development can be done on Linux, Windows, or Mac.
* Should preferably have a decent GUI for putting the installer together. Once that is done, however, it **must** be possible to skip the GUI and make installer building part of automated build process. | In this case, unfortunately, SO didn't tell us much that we didn't know already (and indeed the tool we ultimately chose was not mentioned in any answer). However, I'm posting our experiences here, as they might be helpful to others later on.
We (quickly) evaluated the following installer tools, mostly by looking at their websites and browsing for other information on the web: [Actual Installer](http://www.actualinstaller.com/), [Advanced Installer](http://www.advancedinstaller.com), [BitRock InstallBuilder](http://installbuilder.bitrock.com/), [Inno Setup](http://www.jrsoftware.org/isinfo.php), [Install Creator](http://www.clickteam.com/eng/installcreator.php), [Installer VISE for Windows](http://www.mindvision.com/winvise.asp), [InstallShield](http://www.flexerasoftware.com/products/software-installation/installshield-software-installer/), [install4j](http://www.ej-technologies.com/products/install4j/overview.html), [IzPack](http://izpack.org/), [NSIS](http://nsis.sourceforge.net/), [openInstaller](http://java.net/projects/openinstaller/), [Scriptlogic MSI Studio](http://www.scriptlogic.com/products/msi-studio/), [Smart Install Maker](http://www.sminstall.com/), [Symantec Wise Installation Studio](http://www.symantec.com/business/wise-installation-studio), and [WiX](http://wix.sourceforge.net/).
We screened out most of them early on, and ended up shortlisting two options for closer evaluation: **[BitRock InstallBuilder](http://installbuilder.bitrock.com/)** and **[install4j](http://www.ej-technologies.com/products/install4j/overview.html)**. For these tools, we downloaded evaluation versions and did some prototyping, to see if the things that are most important to us are really supported, and how easy or hard it is to get things working.
Both of the options were good in many things (and both seemed good alternatives to InstallAnywhere):
* They produce completely native and pretty Windows .exe installers that are
easy to customise with your own graphics etc.
* Both tools could easily be automated so that installer building is triggered from Ant. (With install4j it literally took me just five minutes to [learn it](http://resources.ej-technologies.com/install4j/help/doc/indexRedirect.html?http&&&resources.ej-technologies.com/install4j/help/doc/cli/ant.html) and then implement it.)
* Both companies seem to have good support (well, at least for prospects evaluating their products ;-) Especially from BitRock we got very quick replies.
In the following things install4j seemed better than BitRock for our needs (many of these are subjective, of course, so YMMV):
* install4j definitely has better support for running custom Java code - it can be done at any point during the installation, and regardless of whether there's any preinstalled JRE on the system.
* BitRock uses a more hard-coded sequence of installation steps while install4j is more flexible. In install4j, adding custom screens and forms (with or without custom Java code), asking user for input, etc., can be done at any point, before or after installing any files.
* Also some basic things like defining the filesets that are to be copied to the target system, and adding an installation step to replace certain strings in configuration files seemed somewhat easier in install4j.
* install4j has better support for JRE bundling
* When creating installers on Linux, the look & feel of install4j IDE was nicer (more "native") than that of BitRock
* (install4j's [licensing options](http://www.ej-technologies.com/buy/install4j/overview.html) were better for us - we strongly preferred a couple of floating licenses to named licenses for all developers or an expensive "site license")
So ultimately we went with **install4j**. Here are some more details on why it was impressive:
* Its IDE, where you put the installer together, is very simple and easy to use - I could figure out how to do most things I wanted quickly, even without looking at documentation. And when I did have to check something in the documentation (e.g. how to refer to [installer variables](http://resources.ej-technologies.com/install4j/help/doc/indexRedirect.html?http&&&resources.ej-technologies.com/install4j/help/doc/helptopics/concepts/variables.html); how to [get started writing custom Java code against the install4j API](http://resources.ej-technologies.com/install4j/help/doc/indexRedirect.html?http&&&resources.ej-technologies.com/install4j/help/doc/helptopics/extending/api.html)), it didn't take long to find what I needed.
* You can completely customise the screens and actions during the installation procedure, and also add custom screens and actions (coded against their [Java API](http://resources.ej-technologies.com/install4j/help/api/)) at any point. This was important to us because we need to reuse existing custom Java code from the old InstallAnywhere installer.
* In some small details, install4j seems ideal for *Java* developers. For example, if you want to add a validation script to check some user input, you can code that very quickly in the install4j IDE itself, *using plain old Java*, with coding assistance resembling that of IntelliJ IDEA.
* We deemed the cost of install4j floating licenses reasonable, considering how good the tool is (and downright bargain compared to the inflated pricing of InstallAnywhere...)
* In short, it seemed like the best installer tool available for deploying Java applications. | We created [BitRock InstallBuilder](http://installbuilder.bitrock.com), a crossplatform installation tool after some frustrating experiences with InstallAnywhere and specially its cousin (now defunct) InstallShield MP. More than half of our clients use our tool to package Java-based software but the tool is native, not Java-based. That means we have a number of advantages such as native look and feel (incl. Vista, GTK, Qt, etc.) and no need to do self-extraction previous to installation (faster startup, less space requirements) to mention a couple. To answer your specific questions:
* Supports calling Java code as part of the installation at multiple points in time (such as when a certain page is displayed, files being copied, at uninstall time, etc.). The code is not compiled in the installer, but it can be called externally and the result used in the installer. If you are more specific about which kind of code that you need I can provide specific sample code. We have a lot of built-in actions for functionality that needs to be manually added to other installers, so you may not need to write that code in the first place!
* We support all versions of Windows, including 64bit and Windows 2008 (multiple customers have certified on those platforms using our installers)
* We support bundled applications servers, including Tomcat, Resin, JBoss and others. Take a look at [BitNami](http://bitnami.org) for examples of such stacks that we have created.
* We support copying and moving files, substituting values in config files, unpacking files and most other common installation functionality. One of our principles is that the installer should provide built-in support for common installation actions and have an easy, clean interface for invoking external code that is specific to a client's product.
* We support bundling JREs, as you mention is often enough just to bundle the JRE directory and setting the appropriate value for JAVA\_HOME in the launching scripts
You can take a look at some of our [customers](http://installbuilder.bitrock.com/customers.html) such as MySQL, Samsung, Motorola, GitHub, etc. InstallBuilder is a commercial product, but we offer free licenses for open source projects and discounts for small business and microISVs. | What are good InstallAnywhere replacements for installing a Java EE application? | [
"",
"java",
"installation",
"jakarta-ee",
"windows-installer",
""
] |
I'm using a pre-commit hook to lint-check PHP source submitted by our staff, and everyone's really happy with the results. The staff have agreed it would be useful to have the code re-formatted to follow (customizable) style rules on commit. Are there any FOSS scripts which can do this from the command-line? | Was looking for the same thing, just came across the PHP Beautfier package in the PEAR repository:
<http://pear.php.net/package/PHP_Beautifier>
Hope this helps! | [PHP\_CodeSniffer](http://pear.php.net/package/PHP_CodeSniffer) is a nice PEAR package, but it only sniffs the PHP documents for detecting violations of coding standards - it doesn't fix the violations or re-formats the documents. However, it's a great package that every PHP-developer should at least know about - and maybe you can get your fellow staff members to sanitize their code on their own.
You can edit the sniffing-filter in PHP\_CS the way you want it to work. I on the other hand likes the default settings, which is at least a good start for writing better code. | Are there any free cmd-line scripts which can re-format PHP source-code? | [
"",
"php",
"svn",
"coding-style",
"code-formatting",
""
] |
I am trying to insert a new entity using LINQ-to-SQL, and entity is associated with a User entity. The insert of the new entity is successful, but my existing User entity gets inserted as if it were a new User. The code looks something like the following:
```
var someEntity = new Entity();
someEntity.User = this.User;
dataContextInstance.SomeEntities.InsertOnSubmit(someEntity);
dataContextInstance.SubmitChanges();
```
Does anyone know why the user is being inserted as a brand new entity into the Users table? It would seem that the User.UserId would become the foreign key value in the UserId column of the row mapped to the someEntity that is being inserted.
Thanks for any help/suggestions/comments | Since the User entity has been previously loaded by another DataContext (which should hopefully be disposed by now!), you have to attach it to the new (current) DataContext otherwise the DataContext will view it as a new Entity and not an existing one (which already exists in the DB). | Make sure you're using the same **instance** of DataContext for both tables. See my question [here](https://stackoverflow.com/questions/795196/linq-problem-with-inserting-new-rows-that-have-references-to-existing-records) for (I think) a clearer explanation of the problem. | Why is LINQ to SQL entity association creating a new (duplicate) row when inserting a new record? | [
"",
"c#",
".net",
"asp.net",
"linq",
"linq-to-sql",
""
] |
I am looking for a process by the name of "MyApp.exe" and I want to make sure I get the process that is owned by a particular user.
I use the following code to get a list of the processes:
```
Process[] processes = Process.GetProcessesByName("MyApp");
```
This gives me a list of processes, but there does not appear to be a way in the Process class to determine who owns that process? Any thoughts on how I can do this? | You can use WMI to get the user owning a certain process. To use WMI you need to add a reference to the `System.Management.dll` to your project.
**By process id:**
```
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
return argList[1] + "\\" + argList[0];
}
}
return "NO OWNER";
}
```
**By process name** (finds the first process only, adjust accordingly):
```
public string GetProcessOwner(string processName)
{
string query = "Select * from Win32_Process Where Name = \"" + processName + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
string owner = argList[1] + "\\" + argList[0];
return owner;
}
}
return "NO OWNER";
}
``` | Since WMI is not always a fast way of retrieving information, here is the native P/Invoke way of doing it:
The return value is `null` when unsuccessful. In order to get the names of processes running under the SYSTEM user, you need to execute this code as administrator.
```
private static string GetProcessUser(Process process)
{
IntPtr processHandle = IntPtr.Zero;
try
{
OpenProcessToken(process.Handle, 8, out processHandle);
WindowsIdentity wi = new WindowsIdentity(processHandle);
string user = wi.Name;
return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
}
catch
{
return null;
}
finally
{
if (processHandle != IntPtr.Zero)
{
CloseHandle(processHandle);
}
}
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
``` | How do I determine the owner of a process in C#? | [
"",
"c#",
".net",
"process",
""
] |
I am facing a strange problem while sorting a list of strings with integer values. However some values could be prefixed with some characters.
e.g.
```
// B1, 5, 50, A10, 7, 72, B3, A1, A2
```
There are basically page numbers and should be sorted like:
```
// A1, A2, A10, B1, B3, 5, 7, 50, 72
```
But if I use default string sorting then these will be sorted like
```
// A1, A10, A2, B1, B3, 5, 50, 7, 72
```
Any solution for this in C#? | You're looking for the **[Alphanum algorithm](http://www.davekoelle.com/alphanum.html)**. Fortunately for you, a number of implementations exist already. See **[here](http://www.davekoelle.com/alphanum.html)**. | This is how I solved it for our application, order will be like in a windows directory:
```
public class NaturalSortComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern int StrCmpLogicalW(string x, string y);
}
```
Usage:
```
NaturalSortComparer comparer = new NaturalSortComparer();
return comparer.Compare(string1, string2);
```
But it's probably not exactly what you want:
> // A1, A2, A10, B1, B3, 5, 7, 50, 72
This will give
> // 5, 7, 50, 72, A1, A2, A10, B1, B3 | How to Sort Integer Strings? | [
"",
"c#",
".net",
"sorting",
""
] |
What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter.
How does it change when the social graph keeps changing and updating constantly.
And then, is there any dump of twitter social graph data which I could use rather than making so many API calls to start over. | There was a company offering a dump of the social graph, but it was taken down and no longer available. As you already realized - it is kind of hard, as it is changing all the time.
I would recommend checking out their social\_graph api methods as they give the most info with the least API calls. | From the [Twitter API](http://apiwiki.twitter.com)
**[What's the Data Mining Feed and can I have access to it?](http://apiwiki.twitter.com/FAQ&sp=1#WhatstheDataMiningFeedandcanInbsphaveaccesstoit)**
[The Data Mining Feed](http://apiwiki.twitter.com/Streaming-API-Documentation&sp=2) is an expanded version of our /statuses/public\_timeline REST API method. It returns 600 recent public statuses, cached for a minute at a time. You can request it up to once per minute to get a representative sample of the public statuses on Twitter. We offer this for free (and with no quality of service guarantees) to researchers and hobbyists. All we ask is that you provide a brief description of your research or project and the IP address(es) you'll be requesting the feed from; just fill out this form. Note that the Data Mining Feed is not intended to provide a contiguous stream of all public updates on Twitter; please see above for more information on the forthcoming "firehose" solution.
and also see: [Streaming API Documentation](http://apiwiki.twitter.com/Streaming-API-Documentation&sp=2) | Twitter Data Mining: Degrees of separation | [
"",
"python",
"twitter",
"dump",
"social-graph",
""
] |
I need to print *arbitrary* SimpleXML objects in a specific manner, with special handling of attribute nodes.
The problem is that SimpleXML elements and attributes seem to use exactly the same class, attribute node even pretends to support `attributes()` method, and SimpleXML hides its internals, so there doesn't seem to be any way to tell type of node (short of generating XML and reparsing it).
Both give *identical* result:
```
$element = new SimpleXMLElement('<foo>test</foo>');
echo $element;
print_r($element);
$element = new SimpleXMLElement('<foo attr="test" />');
echo $element['attr'];
print_r($element['attr']);
```
Is there a hidden property/method that allows identifying type of node in SimpleXML? Equivalent of DOM's `$node->nodeType` or `$node instanceof DOMAttr`? (I can't use DOM instead, support for SimpleXML is core requirement). | There are no built-in properties in `SimpleXMLElement` which would allow you to tell these apart.
As others have suggested [`dom_import_simplexml`](http://php.net/dom_import_simplexml) can be appropriate, however, that function can change nodes on the fly sometimes, for example, if you pass in a list of childnodes or named childnodes, it will take those and turn them into the first element.
If it's an empty list, for example no attributes returned from `attributes()` or non-existing named childnodes, it will give a warning telling you an invalid nodetype has been given:
> Warning: dom\_import\_simplexml(): Invalid Nodetype to import
So if you need this precise with a snappy boolean `true`/`false`, here is how it works with Simplexml:
```
$isElement = $element->xpath('.') == array($element);
$isAttribute = $element[0] == $element
and $element->xpath('.') != array($element);
```
It works similar with attribute lists and element lists, I've [just blogged about this in the morning](http://hakre.wordpress.com/2013/02/12/simplexml-type-cheatsheet), you need to have some specific knowledge about what to evaluate for what, so I created a cheatsheet for it:
```
+------------------+---------------------------------------------+
| TYPE | TEST |
+------------------+---------------------------------------------+
| Element | $element->xpath('.') == array($element) |
+------------------+---------------------------------------------+
| Attribute | $element[0] == $element |
| | and $element->xpath('.') != array($element) |
+------------------+---------------------------------------------+
| Attributes | $element->attributes() === NULL |
+------------------+---------------------------------------------+
| Elements | $element[0] != $element |
| | and $element->attributes() !== NULL |
+------------------+---------------------------------------------+
| Single | $element[0] == $element |
+------------------+---------------------------------------------+
| Empty List | $element[0] == NULL |
+------------------+---------------------------------------------+
| Document Element | $element->xpath('/*') == array($element) |
+------------------+---------------------------------------------+
```
* [SimpleXML Type Cheatsheet (12 Feb 2013; by hakre)](http://hakre.wordpress.com/2013/02/12/simplexml-type-cheatsheet) | Using what palako pointed out, a function like this might work:
```
function is_attribute($node) {
return !($node->asXML()[0] == "<")
}
``` | How to tell apart SimpleXML objects representing element and attribute? | [
"",
"php",
"reflection",
"simplexml",
""
] |
I am developing an application in C#, using the server-client model, where the server sends a byte array with a bitmap to the client, the client loads it into the screen, sends an "OK" to the server, and the server sends another image, and so on.
The length of the image buffer deppends, usually it is between 60kb and 90kb, but I've seen that it doesn't matter. If I put the client and the server in the same computer, using localhost, everything works fine. The server does beginSend, and the client does endReceive and the whole buffer is transmitted.
However, I am now testing this in a wireless network and what happens is:
* The server sends the image.
* The callback function data\_received on the client is called, but there are only 1460 bytes to read (MTU - why? shouldn't only be in UDP?)
* The callback function data\_received on the client is called again, now with the rest of the buffer (either it be 1000 bytes or 100 kbytes)...
It's always like this, a first packet with 1460 bytes is received, and then the second packet contains the rest.
I can work around this by joining both byte arrays received, but this doesn't seem right. I'm not even sure why this is happening. Is it some restriction on the network? Why then doesn't C# wait for the whole data to be transmitted? I mean, it's TCP, I shouldn't have to worry about it, right?
Anyway, any help would be great!
Cheers | It's TCP - you should treat the data as a *stream*. You shouldn't care how the stream is broken up into packets, or make assumptions about it.
If you need to receive a single "block" of data, the simplest way to do that reliably is to prefix it with the length (e.g. as a 32-bit value). You read the length (noting that even those bytes *could* be split across multiple packets) and then repeatedly read (whether synchronously or asynchronously) taking note of how much you read each time, until you've read all the data. | Have a read of [9.2.4](http://www.wireshark.org/docs/wsdg_html_chunked/ChDissectReassemble.html)
> When dissecting an application layer protocol you cannot assume that each TCP packet contains exactly one application layer message. One application layer message can be split into several TCP packets. | When I send a packet over tcp, it is split into two packets | [
"",
"c#",
"tcp",
"packets",
"mtu",
""
] |
I have been learning the basics of generics in .NET. However, I don't see the generic equivalent of `Hashtable`. Please share some sample C# code for creating generic hashtable classes. | [`Dictionary<TKey, TValue>`](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx)
Note that Dictionary is not a 100% drop in replacement for HashTable.
There is a slight difference in the way they handle NULLs.
The dictionary will throw an exception if you try to reference a key that doesn't exist. The HashTable will just return null.
The reason is that the value might be a value type, which *cannot* be null. In a Hashtable the value was always Object, so returning null was at least possible. | The generic version of Hashtable class is [System.Collections.Generic.Dictionary](http://msdn.microsoft.com/en-us/library/xfhwa508(loband).aspx) class.
[Sample code](http://en.csharp-online.net/CSharp_Generics_Recipes%E2%80%94Replacing_the_Hashtable_with_Its_Generic_Counterpart):
```
Dictionary<int, string> numbers = new Dictionary<int, string>( );
numbers.Add(1, "one");
numbers.Add(2, "two");
// Display all key/value pairs in the Dictionary.
foreach (KeyValuePair<int, string> kvp in numbers)
{
Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
}
``` | What is the generic version of a Hashtable? | [
"",
"c#",
".net",
"generics",
""
] |
Does C# have extension properties?
For example, can I add an extension property to `DateTimeFormatInfo` called `ShortDateLongTimeFormat` which would return `ShortDatePattern + " " + LongTimePattern`? | ### For the moment it is still not supported out of the box by Roslyn compiler ...
Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. Various **C#** versions (maybe all of them?) have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right.
### But it will maybe... one day ...
***Update 2022:***
The features seems to be still in discussion **[here](https://github.com/dotnet/csharplang/discussions/5498)**.
### Moreover you can use a workaround
As specified in this [article](http://www.codeproject.com/Articles/386911/Csharp-Easy-Extension-Properties), you can use the `TypeDescriptor` capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
`string Data(this MyClass instance)` as an alias for extension method
`string GetData(this MyClass instance)` as it stores data into the class.
I hope that C# will soon provide a full featured extension everything (properties and fields), however on that point, only time will tell.
And feel free to contribute as the software of tomorrow will come from the community.
### Post processing approach
If you are allowed to do so, you could also add dynamically a property on a class in your assembly after compilation with tools like ***PostSharp***, ***Mono.Cecil*** (or similar code/IL rewrite tool).
However, as a developer explained in the **[above discussion](https://github.com/dotnet/csharplang/discussions/5498)**,
rewriting code won't let the compiler knows your intent and thus it will probably fail at optimizing your resulting code. As a language feature, the result is expected to be better.
### A bit of history
There was an **[extension members](https://github.com/dotnet/roslyn/issues/112)** item in the **[C# 7 work list](https://github.com/dotnet/roslyn/issues/2136)** so I thought it might be supported in the near future. The current status of extension property can be found on [Github under the related item](https://github.com/dotnet/roslyn/issues/2136).
However, there is an even more promising topic which is the ["extend everything"](https://github.com/dotnet/roslyn/issues/6136) with a focus on especially properties and static classes or even fields.
***Update: August 2016***
As dotnet team published [what's new in C# 7.0](https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/) and from a comment of [Mads Torgensen](https://social.msdn.microsoft.com/profile/Mads+Torgersen+-+MSFT):
> Extension properties: we had a (brilliant!) intern implement them over
> the summer as an experiment, along with other kinds of extension
> members. We remain interested in this, but it’s a big change and we
> need to feel confident that it’s worth it.
It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.
***Update: May 2017***
[**The extension members**](https://github.com/dotnet/roslyn/issues/112) has been closed as duplicate of [**extension everything issue**](https://github.com/dotnet/roslyn/issues/11159) which is closed too.
The main discussion was in fact about Type extensibility in a broad sense.
The feature is now tracked [**here as a proposal**](https://github.com/dotnet/csharplang/issues/192) and has been removed from [**7.0 milestone**](https://github.com/dotnet/csharplang/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22Proposal+champion%22+milestone%3A7.0).
***Update: August, 2017 - C# 8.0 proposed feature***
While it still remains only a *proposed* feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:
```
public interface IEmployee
{
public decimal Salary { get; set; }
}
public class Employee
{
public decimal Salary { get; set; }
}
public extension MyPersonExtension extends Person : IEmployee
{
private static readonly ConditionalWeakTable<Person, Employee> _employees =
new ConditionalWeakTable<Person, Employee>();
public decimal Salary
{
get
{
// `this` is the instance of Person
return _employees.GetOrCreate(this).Salary;
}
set
{
Employee employee = null;
if (!_employees.TryGetValue(this, out employee)
{
employee = _employees.GetOrCreate(this);
}
employee.Salary = value;
}
}
}
IEmployee person = new Person();
var salary = person.Salary;
```
Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in [Mads Torgensen podcast](https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen), ***the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance***. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...).
For this, you can still use the `TypeDescriptor`/`ConditionalWeakTable` technique described earlier and with the property extension, hides it under a nice property.
Syntax is still subject to change as implies this [issue](https://github.com/dotnet/csharplang/issues/840). For example, `extends` could be replaced by `for` which some may feel more natural and less java related.
**Update December 2018 - Roles, Extensions and static interface members**
*Extension everything* didn't make it to C# 8.0, because of some of drawbacks explained as the end of this [GitHub ticket](https://github.com/dotnet/csharplang/issues/1711). So, there was an exploration to improve the design. [Here](https://github.com/dotnet/csharplang/issues/1711), Mads Torgensen explains what are **roles and extensions** and how they differs:
> Roles allow interfaces to be implemented on specific values of a given
> type. Extensions allow interfaces to be implemented on all values of a
> given type, within a specific region of code.
It can be seen at a split of previous proposal in two use cases. The **new syntax for extension** would be like this:
```
public extension ULongEnumerable of ulong
{
public IEnumerator<byte> GetEnumerator()
{
for (int i = sizeof(ulong); i > 0; i--)
{
yield return unchecked((byte)(this >> (i-1)*8));
}
}
}
```
then you would be able to do this:
```
foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
WriteLine($"{e.Current:X}");
}
```
And for a **static interface**:
```
public interface IMonoid<T> where T : IMonoid<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
```
Add an **extension property** on `int` and treat the `int` as `IMonoid<int>`:
```
public extension IntMonoid of int : IMonoid<int>
{
public static int Zero => 0;
}
``` | No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.
At this point the best you can do is `GetXXX()` style extension methods. | Does C# have extension properties? | [
"",
"c#",
"properties",
"extension-methods",
""
] |
I have a small application that I have written that uses the MVP pattern as follows:
* I created an interface called IView
* I implemented this interface in the Form
* Passed in an instance of the form as type IView into the constructor of the presenter
The form contains a ListView component. The items that populates the ListView are created in the presenter. I heard that it is not a good idea to use UI component classes in the presenter. How and where should I create these ListViewItems? I could create the ListViewItems in the form itself but doesn't the form need to be as lightweight as possible with no logic in it?
Edit: N.B. This is a Windows Form application | > I could create the ListViewItems in
> the form itself but doesn't the form
> need to be as lightweight as possible
> with no logic in it?
A simple loop, and simple objects creation is not assumed to be difficult. Such code is fairly lilghtweight for a View:
```
class SomeView
{
void SetData(IEnumerable<DataItem> dataItems)
{
foreach(DataItem dataItem in dataItems)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = dataItem.Text;
...
}
}
}
```
Also, you can use Binding (as others suggested). This will simplify SetData even more.
Try too keep View code such simple that you can "validate" it by fast code review :-) | The ListViewItems are view specific so you should create them in the view. If you create them in the presenter all views must depend on ListViewItems which is not good. | Where should I create ListViewItem list when using the MVP pattern? | [
"",
"c#",
"winforms",
"design-patterns",
""
] |
Here's a simple problem. I have an application that takes a phone number like "13335557777", and needs to reverse it and insert a dot between each number, like this:
"7.7.7.7.5.5.5.3.3.3.1."
I know I can do this with a StringBuilder and a for-loop to reverse the string and insert the dots, but is there a clever way to do this in LINQ (or some other way)?
Note: for this, I'm not really concerned with performance or memory allocation or whatever, just curious to see how this would be done in LINQ. | Try this
```
var source = GetTheString();
var reversed = source.Reverse().Select(x => x.ToString()).Aggregate((x,y) => x + "." + y);
```
**EDIT**
This solution is definitely aimed at the "clever" end. It's likely much more performant to use a StringBuilder to build up the string. This solution creates many intermediate strings.
**EDIT2**
There was some debate about the relative speed of the "clever" solution vs. the StringBuilder approach. I wrote up a quick benchmark to measure the approach. As expected, StringBuilder is faster.
* Normal Aggregate (100 elements): 00:00:00.0418640
* WithStringBuilder (100 elements): 00:00:00.0040099
* Normal Aggregate (1000 elements): 00:00:00.3062040
* WithStringBuilder (1000 elements): 00:00:00.0405955
* Normal Aggregate (10000 elements): 00:00:03.0270392
* WithStringBuilder (10000 elements): 00:00:00.4149977
However, whether or not the speed difference is signficant is highly dependent upon where it is actually used in your application.
Code for the benchmark.
```
public static class AggregateUnchanged {
public static string Run(string input) {
return input
.Reverse()
.Select(x => x.ToString())
.Aggregate((x, y) => x + "." + y);
}
}
public static class WithStringBuilder {
public static string Run(string input) {
var builder = new StringBuilder();
foreach (var cur in input.Reverse()) {
builder.Append(cur);
builder.Append('.');
}
if (builder.Length > 0) {
builder.Length = builder.Length - 1;
}
return builder.ToString();
}
}
class Program {
public static void RunAndPrint(string name, List<string> inputs, Func<string, string> worker) {
// Test case. JIT the code and verify it actually works
var test = worker("123456");
if (test != "6.5.4.3.2.1") {
throw new InvalidOperationException("Bad algorithm");
}
var watch = new Stopwatch();
watch.Start();
foreach (var cur in inputs) {
var result = worker(cur);
}
watch.Stop();
Console.WriteLine("{0} ({2} elements): {1}", name, watch.Elapsed, inputs.Count);
}
public static string NextInput(Random r) {
var len = r.Next(1, 1000);
var builder = new StringBuilder();
for (int i = 0; i < len; i++) {
builder.Append(r.Next(0, 9));
}
return builder.ToString();
}
public static void RunAll(List<string> input) {
RunAndPrint("Normal Aggregate", input, AggregateUnchanged.Run);
RunAndPrint("WithStringBuilder", input, WithStringBuilder.Run);
}
static void Main(string[] args) {
var random = new Random((int)DateTime.Now.Ticks);
RunAll(Enumerable.Range(0, 100).Select(_ => NextInput(random)).ToList());
RunAll(Enumerable.Range(0, 1000).Select(_ => NextInput(random)).ToList());
RunAll(Enumerable.Range(0, 10000).Select(_ => NextInput(random)).ToList());
}
}
``` | The benefit of this one is that String.Join is going to be cheaper than ".Aggregate((x,y) => x + "." + y)".
```
var target = string.Join(".", source.Reverse().Select(c => c.ToString()).ToArray());
``` | C# string manipulation problem | [
"",
"c#",
"linq",
"string",
""
] |
Does anyone know of a great **small** open source Unicode handling library for C or C++? I've looked at [ICU](http://site.icu-project.org/), but it seems way too big.
I need the library to support:
* all the normal encodings
* normalization
* finding character types - finding if a character should be allowed in identifiers and comments
* validation - recognizing nonsense | I looked at UT8-CPP, and libiconv, and neither seemed to have all the features I needed. So, I guess I'll just use ICU, even though it is really big. I think there are some ways to strip out the unneeded functions and data, so I'll try that. [This page](https://unicode-org.github.io/icu/userguide/icu_data/#customizing-icus-data-library) (under "Customizing ICU's Data Library") describes how to cut out some of the data. | Well, [iconv](http://www.gnu.org/software/libiconv/) is a good starting point at least.
Also, a google search returns another stackoverflow question! The horror!
[SO: Light C unicode library](https://stackoverflow.com/questions/313555/light-c-unicode-library) | Small open source Unicode library for C/C++ | [
"",
"c++",
"c",
"unicode",
""
] |
How can I define a multi-statement function or procedure in using the MySQLdb lib in python?
Example:
```
import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;""")
```
Which creates the following traceback:
```
Traceback (most recent call last):
File "proof.py", line 21, in <module>
DELIMITER ;""")
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 173, in execute
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //\nCREATE FUNCTION trivial_func (radius float) \n RETURNS FLOAT\n\n ' at line 1")
```
If I copy the same SQL directly into a mysql shell client, it works as expected | The `DELIMITER` command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use `DELIMITER` if you execute SQL statements directly through an API.
The purpose of `DELIMITER` is to help you avoid ambiguity about the termination of the `CREATE FUNCTION` statement, when the statement itself can contain semicolon characters. This is important in the shell client, where by default a semicolon terminates an SQL statement. You need to set the statement terminator to some other character in order to submit the body of a function (or trigger or procedure).
```
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0; <-- does this semicolon terminate RETURN or CREATE FUNCTION?
ELSE
RETURN 1.0;
END IF;
END
```
Since the API typically allows you to submit one SQL statement at a time, there's no ambiguity -- the interface knows that any semicolons inside the body of your function definition don't terminate the whole `CREATE FUNCTION` statement. So there's no need to change the statement terminator with `DELIMITER`. | To add to the answer by Bill Karwin, the following python code sample can be used to properly execute a string where DELIMITER is used, such as a database creation script.
```
import MySQLdb
db = MySQLdb.connect(db='service')
cursor = db.cursor()
dbString = """DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;"""
# Find special delimiters
delimiters = re.compile('DELIMITER *(\S*)',re.I)
result = delimiters.split(dbString)
# Insert default delimiter and separate delimiters and sql
result.insert(0,';')
delimiter = result[0::2]
section = result[1::2]
# Split queries on delimiters and execute
for i in range(len(delimiter)):
queries = section[i].split(delimiter[i])
for query in queries:
if not query.strip():
continue
cursor.execute(query)
```
This will execute one delimited statement at a time, changing delimiters when needed. | Create function through MySQLdb | [
"",
"python",
"mysql",
""
] |
I need to be able to connect, disconnect, and re-connect a dial-up networking connection in a C# .NET Framework application. Creating the connection in the phone-book might also be useful/necessary.
Are there any classes or libraries written for C# or .NET out there that wrap all this functionality nicely for me? Anyone have some code they would be willing to share?
**Note**: Application is *unattended*, like a Kiosk, and thus requiring user action is unacceptable. | Check out the DotRas project on CodePlex.com, it has the entire API completed.
<http://www.codeplex.com/DotRas> | One way to do this is through Interop around RAS. RasDialDlg() can be used to open a dial-up networking connection without displaying the dialog box. Use RasHangUp() to disconnect.
RasEnumConnections() can be used to list available connections.
The dll is Rasapi32.dll - headers are in ras.h and raserror.h | How do I work with dial-up (RAS) connections in Windows using C#/.NET? | [
"",
"c#",
".net",
"dial-up",
"ras",
""
] |
I have the following sql (a simplification of the real problem):
```
SELECT *
FROM t
WHERE myname LIKE '%{$input}%';
```
How do I escape the $input?
I can't use the quoteInto (unless I miss something).
As
```
$sql=$DB->quoteInto("SELECT *
FROM t
WHERE myname LIKE '%?%'",$input);
```
Will give me
```
SELECT *
FROM t
WHERE myname LIKE '%'my input'%';
```
and
```
$sql=$DB->quoteInto("SELECT *
FROM t
WHERE myname LIKE ?",'%'.$input.'%');
```
Will give me something on the lines:
```
SELECT *
FROM t
WHERE myname LIKE '\%my input\%';
``` | The last option is works out well for me i've not experienced it escaping '%'. So `$db->quote('%'.$_GET['query'].'%')` outputs `%queryvalue%` | The solution is really simple. Zend\_Db has een Expression class that helps you work arround it.
```
$select = $this->select()
->where('value LIKE("?")', new Zend_Db_Expr('%' . $value . '%'))
$this->fetchAll( $select );
``` | How can I escape complex sql in Zend Framework? | [
"",
"php",
"zend-framework",
"zend-db-table",
""
] |
Does anyone know if there is a way to use a single XMLHTTPRequest object to send multiple asynchronous requests. I can do it with a single request and get a response back from my onreadystatechange() handler.
I'm wondering if there's a way to use the same object to send multiple parallel requests but I'm not seeing any way to match a response to a request from the onreadystatechange() function. | Short answer: You can't.
Question you really need to ask yourself is why would you want that over multiple XMLHTTPRequest objects ? There's hardly a downside to instantiating a dozen or so objects. | +1 to Martijn's answer, but I wanted to add that the enlightenment you're missing is that a Request is *by definition* a one time object. | Single XMLHTTPRequest object to make multiple requests | [
"",
"c++",
"internet-explorer-7",
"msxml",
""
] |
I would like to get a `byte[]` from a `float[]` as quickly as possible, without looping through the whole array (via a cast, probably). Unsafe code is fine. Thanks!
I am looking for a byte array 4 time longer than the float array (the dimension of the byte array will be 4 times that of the float array, since each float is composed of 4 bytes). I'll pass this to a BinaryWriter.
**EDIT**:
To those critics screaming "premature optimization":
I have benchmarked this using ANTS profiler before I optimized. There was a significant speed increase because the file has a write-through cache and the float array is exactly sized to match the sector size on the disk. The binary writer wraps a file handle created with `pinvoke`'d win32 API. The optimization occurs since this lessens the number of function calls.
And, with regard to memory, this application creates massive caches which use plenty of memory. I can allocate the byte buffer once and re-use it many times--the double memory usage in this particular instance amounts to a roundoff error in the overall memory consumption of the app.
So I guess the lesson here is not to make premature assumptions ;) | If you do not want any conversion to happen, I would suggest Buffer.BlockCopy().
```
public static void BlockCopy(
Array src,
int srcOffset,
Array dst,
int dstOffset,
int count
)
```
For example:
```
float[] floatArray = new float[1000];
byte[] byteArray = new byte[floatArray.Length * 4];
Buffer.BlockCopy(floatArray, 0, byteArray, 0, byteArray.Length);
``` | There is a dirty fast *(not unsafe code)* way of doing this:
```
[StructLayout(LayoutKind.Explicit)]
struct BytetoDoubleConverter
{
[FieldOffset(0)]
public Byte[] Bytes;
[FieldOffset(0)]
public Double[] Doubles;
}
//...
static Double Sum(byte[] data)
{
BytetoDoubleConverter convert = new BytetoDoubleConverter { Bytes = data };
Double result = 0;
for (int i = 0; i < convert.Doubles.Length / sizeof(Double); i++)
{
result += convert.Doubles[i];
}
return result;
}
```
This will work, but I'm not sure of the support on [Mono](http://en.wikipedia.org/wiki/Mono_%28software%29) or newer versions of the [CLR](http://en.wikipedia.org/wiki/Common_Language_Runtime). The only strange thing is that the `array.Length` is the bytes length. This can be explained because it looks at the array length stored with the array, and because this array was a byte array that length will still be in byte length. The indexer does think about the Double being eight bytes large so no calculation is necessary there.
I've looked for it some more, and it's actually described on [MSDN](http://en.wikipedia.org/wiki/Microsoft_Developer_Network), *[How to: Create a C/C++ Union by Using Attributes (C# and Visual Basic)](http://msdn.microsoft.com/en-us/library/acxa5b99.aspx)*, so chances are this will be supported in future versions. I am not sure about Mono though. | What is the fastest way to convert a float[] to a byte[]? | [
"",
"c#",
"unsafe",
""
] |
When I run this in Chrome (ver 2), it doesn't return the string, but it works in Firefox (ver 3). Why is this?
```
<html>
<head>
<script type="text/javascript">
function disp_prompt() {
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="") {
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_prompt()" value="Display a prompt box" />
</body>
</html>
``` | To append content to a document, you should only call `document.write()` during the <script>-block parsing phase.
If you have a call to `document.write` somewhere where it executes outside that context, such as in your event handler, there is no parsing going on, so nowhere for that string `'foo'` to go.
What should happen according to the [original JavaScript reference](http://docs.sun.com/source/816-6408-10/document.htm#1221642) is:
> Event handlers execute after the original document closes, so the write method implicitly opens a new document of mimeType text/html if you do not explicitly issue a document.open method in the event handler.
That is, it assumes you've made a mistake and meant to do:
```
document.open('text/html');
document.write(html);
```
Which replaces the entire document with new content. You'll also notice that because you didn't finish that off by calling:
```
document.close();
```
...in Firefox, the ‘loading’ throbber is still animating, expecting more content to be written to the document (but it never comes).
In this case, you are `document.write()`ing a string:
```
Hello bobince! How are you today?
```
that is clearly not a valid HTML document. Chrome (and Safari, which behaves the same) is trying to parse it as an HTML document, but fails because it is non-whitespace text content outside the document element (<html>), which is not allowed. If you put some tags in the name input:
```
Hello <em>bobince</em>! How are you today?
```
You'll see everything outside the <em> element is discarded. Firefox and IE manage to apply their “fix up text outside any element” broken-HTML-rule to save you, but Chrome doesn't.
If you want to `document.write()` a new document, you should make sure it is indeed a complete document:
```
<html><head><title>Greetings</title><body><p>Hello bobince! How are you today?</p></body></html>
```
Or, if you want to `document.write()` a text string, you should theoretically call:
```
document.open('text/plain');
```
before the write(). But beware, the mimetype parameter is not supported by Chrome or Safari; they'll always treat what you write as HTML.
In any case, **you probably don't want to be using this method**. If you want to add to (or change) the existing page you should normally be using DOM methods, such as setting the text on a status output div, or replacing the body contents using innerHTML.
`document.write()` is needed in a few places (in particular, when you are creating a new window or frame from scratch), but otherwise it's generally the wrong thing and should be viewed with suspicion. | don't use document.write. if you change it to soemthing like
```
if (name != null && name != "") {
document.getElementById('foo').innerHTML = "Hello " + name + "! How are you today?";
}
<body>
<input ...
<div id='foo'> </div>
</body>
```
document.write has pretty strange behavior. Where do you expect the text to be written to? | Why isn't chrome running this javascript | [
"",
"javascript",
"google-chrome",
""
] |
I need to load a file (usually ASCII) into a `DataSet`. How can I do that?
What data types should I use for my columns?
Thanks. | you can use byte[] for the type,
Maybe a DataTable like this can be useful for you
```
DataTable dt = new DataTable("files");
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("size", typeof(int));
dt.Columns.Add("content", typeof(byte[]));
``` | Not sure if this is what you are looking for but you can find a sample here:
[Fill a DataSet from delimited text files](http://www.codeproject.com/KB/database/DataSetFrmDelimTxt.aspx) | C# .NET - How do I load a file into a DataSet? | [
"",
"c#",
"file",
"dataset",
""
] |
i work at a large company and we haven't distributed dotnet runtimes 3.0+ out to the desktops so we are all using vs 2005 and c# 2.0
is there any big benefit of moving to vs 2008 and still targeting 2.0 (since the runtime deployment will not be there soon) for the developers.
also, if the suggestion is to do the upgrade to vs 2008, are there any gotchas or things to worry about or prepare for.
Note: We are mostly doing winforms projects | There is some good discussion on this topic [on another thread](https://stackoverflow.com/questions/193281/visual-studio-2005-vs-2008-what-are-the-benefits) and [on this one](https://stackoverflow.com/questions/46036/upgrading-to-visual-studio-2008-from-2005). | Some of the IDE improvements include a far better XML editor and the new web forms designer.
I would recommend you upgrade to VS2008 SP1, which also includes a schema viewer for editing XML schemas.
If you target .NET 2.0, then your code cannot require any of the new assemblies, so your code would still work on a machine without .NET 3.5. You should roll out .NET 2.0 SP1 and SP2 to the desktops. Then, I believe that any new code you write that uses a .NET 3.5 SP1 assembly could simply ship that assembly with the code. There would be no affect on anyone else on the computer. .NET 2.0 through .NET 3.5 SP1 all use the same CLR, so there is no conflict. | Migrate from vs 2005 to vs 2008 | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
"upgrade",
""
] |
I was doing some testing with nullable types, and it didn't work quite as I expected:
```
int? testInt = 0;
Type nullableType = typeof(int?);
Assert.AreEqual(nullableType, testInt.GetType()); // not the same type
```
This doesn't work either:
```
DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable)); //FAIL
DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable<>)); //STILL FAIL
```
My question is why does testInt.GetType() return int, and typeof(int?) return the true nullable type? | According to the [MSDN](http://msdn.microsoft.com/en-us/library/ms366789(VS.80).aspx) :
> Calling GetType on a Nullable type
> causes a boxing operation to be
> performed when the type is implicitly
> converted to Object. Therefore GetType
> always returns a Type object that
> represents the underlying type, not
> the Nullable type.
When you box a nullable object, only the underlying type is boxed.
Again, from [MSDN](http://msdn.microsoft.com/en-us/library/ms228597(VS.80).aspx) :
> Boxing a non-null nullable value type
> boxes the value type itself, not the
> System.Nullable that wraps the value
> type. | Further to Romain's correct answer, if you want to compare the "real" types (ie, without implicitly converting any nullable type to its underlying type) then you can create an extension method like so:
```
public static class MyExtensionMethods
{
public static Type GetRealType<T>(this T source)
{
return typeof(T);
}
}
```
And then try the following tests:
```
int? a = 0;
Console.WriteLine(a.GetRealType() == typeof(int?)); // True
Console.WriteLine(a.GetRealType() == typeof(int)); // False
int b = 0;
Console.WriteLine(b.GetRealType() == typeof(int)); // True
Console.WriteLine(b.GetRealType() == typeof(int?)); // False
DateTime? c = DateTime.Now;
Console.WriteLine(c.GetRealType() == typeof(DateTime?)); // True
Console.WriteLine(c.GetRealType() == typeof(DateTime)); // False
DateTime d = DateTime.Now;
Console.WriteLine(d.GetRealType() == typeof(DateTime)); // True
Console.WriteLine(d.GetRealType() == typeof(DateTime?)); // False
```
**EDIT...**
For completeness -- and prompted by SLaks's comments below -- here's an alternative version that only uses the compile-time type when `source` is either `null` or `Nullable<>`; otherwise it uses `GetType` and returns the runtime type:
```
public static class MyExtensionMethods
{
public static Type GetRealType<T>(this T source)
{
Type t = typeof(T);
if ((source == null) || (Nullable.GetUnderlyingType(t) != null))
return t;
return source.GetType();
}
}
``` | Nullable type is not a nullable type? | [
"",
"c#",
".net",
"nullable",
"gettype",
""
] |
OK,I know that I should use a DOM parser, but this is to stub out some code that's a proof of concept for a later feature, so I want to quickly get some functionality on a limited set of test code.
I'm trying to strip the width and height attributes of chunks HTML, in other words, replace
```
width="number" height="number"
```
with a blank string.
The function I'm trying to write looks like this at the moment:
```
function remove_img_dimensions($string,$iphone) {
$pattern = "width=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
$pattern = "height=\"[0-9]*\"";
$string = preg_replace($pattern, "", $string);
return $string;
}
```
But that doesn't work.
How do I make that work? | PHP is unique among the major languages in that, although regexes are specified in the form of string literals like in Python, Java and C#, you also have to use regex delimiters like in Perl, JavaScript and Ruby.
Be aware, too, that you can use single-quotes instead of double-quotes to reduce the need to escape characters like double-quotes and backslashes. It's a good habit to get into, because the escaping rules for double-quoted strings can be surprising.
Finally, you can combine your two replacements into one by means of a simple alternation:
```
$pattern = '/(width|height)="[0-9]*"/i';
``` | Your pattern needs the start/end pattern character. Like this:
```
$pattern = "/height=\"[0-9]*\"/";
$string = preg_replace($pattern, "", $string);
```
"/" is the usual character, but most characters would work ("|pattern|","#pattern#",whatever). | Replacing HTML attributes using a regex in PHP | [
"",
"php",
"html",
"regex",
"preg-replace",
""
] |
I have an array in this format:
```
Array
(
[0] => Array
(
[text] => tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 7480000
[lastMonthSearchVolume] => 9140000
)
[1] => Array
(
[text] => personality tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 165000
[lastMonthSearchVolume] => 201000
)
[2] => Array
(
[text] => online tests
[language] =>
[advertiserCompetitionScale] => 5
[avgSearchVolume] => 246000
[lastMonthSearchVolume] => 301000
)
)
```
How can I sort an array in that format, in the descending order of the `avgSearchVolume` field? Is there a built in function for this? | Use [`usort`](http://php.net/usort) and supply your own function to do the ordering, e.g.
```
function cmp($a, $b)
{
return $b['avgSearchVolume'] - $a['avgSearchVolume'];
}
usort($array, "cmp");
``` | Until PHP 5.3 this is the best function for sorting based on subkeys without making a new function for each key.
```
function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
foreach ($array as $subarray) {
$keys[] = $subarray[$subkey];
}
array_multisort($keys, $sortType, $array);
}
sortBySubkey($arr, 'avgSearchVolume');
```
With PHP 5.3 you can make something like this, same function call as now.
```
function getSortVariable($sortType = SORT_ASC) {
switch($sortType) {
case SORT_ASC:
return function ($a, $b) use ($subkey) { return strcmp($a[$subkey], $b[$subkey]); };
}
}
function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) {
$sortFunction = getSortVariable($sortType);
usort($array, $sortFunction($subkey));
}
``` | Sorting an associative array in PHP | [
"",
"php",
"arrays",
"sorting",
""
] |
I am currently trying to build an expanding panel in Swing (akin the WPF's `Expander` control) and I'd like to retain the usual methods for manipulating it (i. e. `setLayout`, `add`, etc.). Only they should be routed to an embedded panel (the one being shown or hidden).
How would one do that? Overriding every method of `JComponent` and re-routing that to an embedded `JPanel` would be cumbersome, but that's the only way I see.
Or should I rather make the embedded panel visible to the outside and force users to use something like `ExpanderPanel.getInnerPanel()` instead. But then it's no drop-in replacement for `JPanel` which I think would be nice to have. | In 1.5(ish) Swing routed a few methods to the content pane in `JFrame`, `JApplet`, etc. Whilst there appeared to be some usability benefits for those just starting, it doesn't actually fix the problem. So everyone has to deal with a very strangely behaving API. So my advice is to avoid this approach. | Take a look at the **JXTaskPane** from **Swingx** project. It already does what you need. | Best way of subclassing a JPanel in Swing | [
"",
"java",
"swing",
"jpanel",
""
] |
I've written a little application that does some text manipulation and writes the output to a file (html, csv, docx, xml) and this all appears to work fine on Mac OS X. On windows however I seem to get character encoding problems and a lot of '"' seems to disappear and be replaced with some weird stuff. Usually the closing '"' out of a pair.
I use a FreeMarker to create my output files and there is a byte[] array and in one case also a ByteArrayStream between reading the templates and writing the output. I assume this is a character encoding problem so if someone could give me advise or point me to some 'Best Practice' resource for dealing with character encoding in java.
Thanks | There's really only one best practice: be aware that Strings and bytes are two fundamentally different things, and that whenever you convert between them, you are using a character encoding (either implicitly or explicitly), which you need to pay attention to.
Typical problematic spots in the Java API are:
* `new String(byte[])`
* `String.getBytes()`
* `FileReader, FileWriter`
All of these implicitly use the platform default encoding, which depends on the OS and the user's locale settings. Usually, it's a good idea to avoid this and explicitly declare an encoding in the above cases (which FileReader/Writer unfortunately don't allow, so you have to use an InputStreamReader/Writer).
However, your problems with the quotation marks and your use of a template engine may have a much simpler explanation. What program are you using to write your templates? It sounds like it's one that inserts ["smart quotes"](http://blogs.msdn.com/oldnewthing/archive/2009/02/25/9443404.aspx), which are part of the Windows-specific cp1251 encoding but don't exist in the more global ISO-8859-1 encoding.
What you probably need to do is to be aware which encoding your templates are saved in, and configure your template engine to use that encoding when reading in the templates. Also be aware that some texxt files, specifically XML, explicitly declare the encoding in a header, and if that header disagrees with the actual encoding used by the file, you'll invariable run into problems. | You can control which encoding your JVM will run with by supplying f,ex
-Dfile.encoding=utf-8
for (UTF-8 of course) as an argument to the JVM. Then you should get predictable results on all platforms. Example:
java -Dfile.encoding=utf-8 my.MainClass | Character Encoding Trouble - Java | [
"",
"java",
"character-encoding",
""
] |
How do I raise an event in a content page that its master page can then respond to?
For example, I have a content page which is using a master page. The master page contains the website navigation bar. Depending on the page I'm on, I'd like to send an event to the master page to change the CSS class of the current page menu item in the navigation bar.
I'm using Visual Studio 2008 and ASP.NET 3.5 and C#.
Thanks! | Edit, from what your asking you don't really need an event, you just want to call a method on the master. off the top of my head, in the master:
```
public void ChangeCss(string className)
{
someObject.CssClass = className;
}
```
then in your page:
```
(this.Master as MyMasterType).ChangeCss("myclass");
``` | If the event happens on all content pages use Kirtan's BasePage solution. If a base page isn't appropriate, then within each page where the event happens add this when the page loads.
```
thisPage.Event += (Page.Master as YourMasterPageClass).YourCustomEventHandler
``` | Sending Event from a Page to its Master Page in ASP.NET | [
"",
"c#",
"asp.net",
"events",
"master-pages",
""
] |
I'm looking for a good multiplatform library for vector graphics in C/C++. Any recommendation or thougts?
Thanks
EDIT: Thanks for all your answers!! Could anyone tell me the pros and cons of qt vs cairo, for example? Cairo got more votes, but it seems to be from 5 to 7 times slower according to some benchmarks... | You can try out [Cairo](http://cairographics.org/) - it's opensource, not too heavy and has a flexible license. | I like Nokia's [QT](http://qt.nokia.com/). Not only vector graphics but also high level widgets. | What is a good multiplatform vector graphics library for C/C++? | [
"",
"c++",
"c",
"vector-graphics",
""
] |
I have two controls containing `DataGridView`s on different panes in a `DockPanel`. If one is in edit mode and I switch pane, I get a `NullReferenceException` thrown from within the `DataGridView`'s `EndEdit()` method. The stack trace doesn't go any deeper than that and the exception doesn't contain any more information.
I've looked at that method in the reflector, and I can't see anything obviously null. I suspect that the problem is actually in my code, but the exception is being rethrown from within Microsoft's code and that's resetting the stack trace. How do I find out what originally caused the exception? | If you suspect a bug in the MS code, you could download the debugging symbols from the symbol server, load them and trace it through at debug? [Like so](http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx).
Note that the symbols are subject to one of the various licences. This may impact you if (for example) you work on "mono" contributions etc. | Have you looked into the InnerException property? | How do I find out what originally caused an exception, if it gets thrown from Microsoft's code? | [
"",
"c#",
".net",
"exception",
"datagridview",
"dockpanel",
""
] |
I want to create an abstract collection class (called Space) and an
abstract element class (called Atom). Instances of both have to know each other (exactly typed).
That's the problem.
```
abstract class Space<A extends Atom>{
// ...
}
abstract class Atom<S extends Space>{
// ...
}
```
Not good:
"A extends Atom" means any Atom, but not a strongly typed one
"S extends Space" means any Space, but not a strongly typed one
I can't reach complete type-safety with the following attempts either:
```
abstract class Space<A extends Atom<? extends Space>>
abstract class Atom<S extends Space<? extends Atom>>
abstract class Space<S, A extends Atom<S extends Space<A>>>
abstract class Atom<A, S extends Space<A extends Atom<S>>>
and so on ...
```
**Remember, these two classes are abstract, and I want that any possible
two subclasses are typed according to each other.**
That means, the classes SomeSpace and SomeAtom in the following example
must have a strong "type knowledge" of each other:
```
class SomeSpace extends Space<SomeAtom>
class SomeAtom extends Atom<SomeSpace>
``` | This works for me, although I got really confused about all those generic constraints. Which means I can't guarantee that it does what it's supposed to do:
```
interface ISpace<S extends ISpace<S, A>, A extends IAtom<S, A>> {
List<? extends IAtom<S, A>> getList(); //// CHANGED
}
interface IAtom<S extends ISpace<S, A>, A extends IAtom<S, A>> {
S getSpace();
}
abstract class Space<S extends Space<S, A>, A extends Atom<S, A>>
implements ISpace<S, A> {
private final List<Atom<S, A>> atoms = new LinkedList<Atom<S, A>>(); ////CHANGED
public Space() {
}
public Space<S, A> getSpace() {
return this;
}
@Override
public List<Atom<S, A>> getList() { //// CHANGED
return atoms;
}
}
abstract class Atom<S extends Space<S, A>, A extends Atom<S, A>>
implements IAtom<S, A> {
private final S space;
public Atom(S someSpace) {
this.space = someSpace;
space.getList().add(this);
}
@Override
public S getSpace() {
return space;
}
public Atom<S, A> getAtom() {
return this;
}
}
class Space1 extends Space<Space1, Atom1> {
public Space1() {
}
}
class Atom1 extends Atom<Space1, Atom1> {
public Atom1(Space1 someSpace) {
super(someSpace);
}
}
``` | ```
abstract class Space<S extends Space<S,A>, A extends Atom <A, S>> {}
abstract class Atom <A extends Atom <A,S>, S extends Space<S, A>> {}
```
Or, I guess, if you prefer
```
abstract class Space<S extends Space<S,A>, A extends Atom<S, A>> {}
abstract class Atom <S extends Space<S,A>, A extends Atom<S, A>> {}
``` | Generic classes in Java (type-safely) depending on each other | [
"",
"java",
"generics",
"types",
""
] |
I'm using Javascript to parse an XML file with about 3,500 elements. I'm using a jQuery "each" function, but I could use any form of loop.
The problem is that the browser freezes for a few seconds while the loop executes. What's the best way to stop freezing the browser without slowing the code down too much?
```
$(xmlDoc).find("Object").each(function() {
//Processing here
});
``` | I would ditch the "each" function in favour of a for loop since it is faster. I would also add some waits using the "setTimeout" but only every so often and only if needed. You don't want to wait for 5ms each time because then processing 3500 records would take approx 17.5 seconds.
Below is an example using a for loop that processes 100 records (you can tweak that) at 5 ms intervals which gives a 175 ms overhead.
```
var xmlElements = $(xmlDoc).find('Object');
var length = xmlElements.length;
var index = 0;
var process = function() {
for (; index < length; index++) {
var toProcess = xmlElements[index];
// Perform xml processing
if (index + 1 < length && index % 100 == 0) {
setTimeout(process, 5);
}
}
};
process();
```
I would also benchmark the different parts of the xml processing to see if there is a bottleneck somewhere that may be fixed. You can benchmark in firefox using firebug's profiler and by writing out to the console like this:
```
// start benchmark
var t = new Date();
// some xml processing
console.log("Time to process: " + new Date() - t + "ms");
```
Hope this helps. | Set a timeOut between processing to prevent the loop cycle from eating up all the browser resources. In total it would only take a few seconds to process and loop through everything, not unreasonable for 3,500 elements.
```
var xmlElements = $(xmlDoc).find('Object');
var processing = function() {
var element = xmlElements.shift();
//process element;
if (xmlElements.length > 0) {
setTimeout(processing, 5);
}
}
processing();
``` | How to stop intense Javascript loop from freezing the browser | [
"",
"javascript",
"jquery",
"performance",
"loops",
""
] |
I'm getting this error:
> The remote certificate is invalid according to the validation procedure.
whenever I try to send e-mail using Gmail's SMTP server in my C# code.
Can someone point me to the right direction for a solution to this problem?
The following is the stack trace...
```
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Mail.SmtpConnection.Flush()
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at BulkEmail.frmemail.mailsending(String toaddress, String fromaddress, String fromname, String subject, String pwd, String attachements, String mailmessage, String htmlmessage, Int32 i, Int32 j, String replytoaddress)
``` | > # Warning: Do not use this in production code!
As a workaround, you can switch off certificate validation. Only ever do this to obtain confirmation that the error is being thrown because of a bad certificate.
Call this method before you call `smtpclient.Send()`:
```
[Obsolete("Do not use this in Production code!!!",true)]
static void NEVER_EAT_POISON_Disable_CertificateValidation()
{
// Disabling certificate validation can expose you to a man-in-the-middle attack
// which may allow your encrypted message to be read by an attacker
// https://stackoverflow.com/a/14907718/740639
ServicePointManager.ServerCertificateValidationCallback =
delegate (
object s,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
) {
return true;
};
}
``` | The link here solved my problem.
<http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html>
I went to url of the web service (on the server that had the issue), clicked on the little security icon in IE, which brought up the certificate. I then clicked on the Details tab, clicked the Copy To File button, which allowed me to export the certifcate as a .cer file. Once I had the certificate locally, I was able to import it into the certificate store on the server using the below instructions.
Start a new MMC.
File --> Add/Remove Snap-In...
Click Add...
Choose Certificates and click Add.
Check the "Computer Account" radio button. Click Next.
Choose the client computer in the next screen. Click Finish.
Click Close.
Click OK.
NOW install the certificate into the Trusted Root Certification Authorities certificate store. This will allow all users to trust the certificate. | "The remote certificate is invalid according to the validation procedure." using Gmail SMTP server | [
"",
"c#",
"email",
"smtp",
""
] |
Assume I have a website called Website A and it has some links on it to other websites. One of these links could be a link to Website B. Is there a way, using some existing solution, open source, or something you have to pay for where you can track who, what, where, etc clicked the link to go from Website A to Website B?
Website B could be Stackoverflow and my website is www.websiteA.com, so on my website, I have a link to www.stackoverflow.com. If a user clicks on www.stackoverflow.com from my page, I want to capture information, such as name, phone, etc (not sure if I can do this unless the user is actually logged into my website). In this case, this is a public page which anyone from anywhere can access. If I can't do it from my website, is there a way I can tell stackoverflow that this particular person clicked on my link to get to your website and I need their information. | The method most sites use for this is to have a script on your site handle the redirect. So instead of the link being directly to:
> `http://websiteB.com`
the link goes to something like:
> `http://websiteA.com/link/websiteB.com`
The "link" script logs the request and then forwards them to the address (this should be done instantly, don't give them a "forwarding you to Website B in 3 seconds!" page).
Note that as a *visitor* to your site, I much prefer a method where the link's destination is apparent when I hover over the link, as opposed to the method that some sites use where all you see is an id. What I mean is, instead of the link being something like:
> `http://websiteA.com/link/websiteB.com`
they instead have a link like:
> `http://websiteA.com/link/483`
Showing the destination can be achieved in a few ways. One way is something like I described above, where the destination is part of the query string. Alternatively, you can use some Javascript for this. The status bar's value can be changed with Javascript by setting the `window.status` variable, but many browsers prevent this by default (Firefox, for example).
Google has found a sneaky way around this problem by actually using Javascript to change the **link** instead of the status bar. When the page is loaded, the links in the results list go to their actual destinations, but every link has an `onmousedown` javascript event that changes the link when you click on it. You can see this in action by right-clicking on a link. After you've done that, hovering over the link will now show the true destination (Google's click-tracking script) in the status bar instead of the result's real URL.
Of course the information displayed with any method could be a misrepresentation of where I'm actually going to be sent, but I still prefer it over seeing a meaningless id number. | Try using HTTP\_REFERER | Capture who clicked a link from Website A to Website B? | [
"",
"c#",
"asp.net",
""
] |
Where is the correct place to initialize a class data member?
I have the class declaration in a header file like this:
Foo.h:
```
class Foo {
private:
int myInt;
};
```
Then I try to set a value to myInt in the corresponding .cpp file:
Foo.cpp:
```
int Foo::myInt = 1;
```
I get a compiler error for redefining myInt. What am I doing wrong??? | What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor:
```
class Foo {
private:
int myInt;
public:
Foo() : myInt(1) {}
};
```
A class variable is one where there is only one copy that is shared by every instance of the class. Those can be initialized as you tried. (See JaredPar's answer for the syntax)
For integral values, you also have the option of initializing a static const right in the class definition:
```
class Foo {
private:
static const int myInt = 1;
};
```
This is a single value shared by all instances of the class that cannot be changed. | To extend on Jared's answer, if you want to initialize it the way it is now, you need to put it in the Constructor.
```
class Foo
{
public:
Foo(void) :
myInt(1) // directly construct myInt with 1.
{
}
// works but not preferred:
/*
Foo(void)
{
myInt = 1; // not preferred because myInt is default constructed then assigned
// but with POD types this makes little difference. for consistency
// however, it's best to put it in the initializer list, as above
// Edit, from comment: Also, for const variables and references,
// they must be directly constructed with a valid value, so they
// must be put in the initializer list.
}
*/
private:
int myInt;
};
``` | Correct place to initialize class variables? | [
"",
"c++",
""
] |
I'm working on a java swing application that will be used in a psychology experiment and the researchers have requested that I make the program "black out the screen" in order that there should be no outside stimuli for the user. They want the swing app to be truly full-screen and without any type of title bar or minimize/maximize/close buttons on the top.
The software will be running in a Windows XP environment using JavaSE 6.
How can I do this and please provide a code snippet if applicable.
Thanks! | Use the Full Screen Java APIs?
<http://java.sun.com/docs/books/tutorial/extra/fullscreen/exclusivemode.html>
<http://www.artificis.hu/2006/03/16/java-awtswing-fullscreen>
```
JFrame fr = new JFrame();
fr.setResizable(false);
if (!fr.isDisplayable()) {
// Can only do this when the frame is not visible
fr.setUndecorated(true);
}
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
try {
if (gd.isFullScreenSupported()) {
gd.setFullScreenWindow(fr);
} else {
// Can't run fullscreen, need to bodge around it (setSize to screen size, etc)
}
fr.setVisible(true);
// Your business logic here
} finally {
gd.setFullScreenWindow(null);
}
``` | Use the [`setUndecorated(true)`](http://java.sun.com/javase/6/docs/api/java/awt/Frame.html#setUndecorated(boolean)) property. Note that this has to be done before making the frame visible.
```
JFrame frame = new JFrame();
Toolkit tk = Toolkit.getDefaultToolkit();
frame.setBounds(new Rectangle(new Point(0, 0), tk.getScreenSize()));
frame.setUndecorated(true);
frame.setVisible(true);
``` | How can I create a Java Swing app that covers the Windows Title bar? | [
"",
"java",
"user-interface",
"swing",
""
] |
I have a table T which has a column C which contains text that have the character & within it, but if I do the following query, it returns nothing, although I may have 10 rows.
```
SELECT * FROM T WHERE Contains(C, 'a&b')
``` | Use double quotes to make it a search term:
```
SELECT *
FROM T
WHERE CONTAINS(C, '"a&b"')
```
Otherwise you are searching for something that has a AND b. | Use like instead:
```
SELECT * FROM T WHERE C like '%&%'
```
if you're looking just for &
or
```
SELECT * FROM T WHERE C like '%a&b%'
```
if you need to search for a&b | How do you search for a & (ampersand) in the tsql contains function? | [
"",
"sql",
"sql-server",
"t-sql",
"full-text-search",
""
] |
Given this code:
```
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string InputString = arg_vec[1];
string toMatch = "FOO";
const regex e(toMatch);
if (const regex_match(InputString, e)) {// this is line 26
cout << "Match" << endl;
} else {
cout << "No Match" << endl;
}
return 0;
}
```
Compiled with this command:
```
g++ -I /home/foolishbrat/.boost/include/boost-1_37 test.cc -o test
```
It gives this error:
```
test.cc: In function `int main(int, char**)':
test.cc:26: error: syntax error before `)' token
```
What's wrong with my code?
If I remove "const" in line 26 and compiled with the same command.
I will get this errors:
```
/misc/raid2/Melchior/foolishbrat/tmp/ccr3zzcH.o(.gnu.linkonce.t._ZN5boost11regex_matchIN9__gnu_cxx17__normal_iteratorIPKcSsEESaINS_9sub_matchIS5_EEEcNS_12regex_traitsIcNS_16cpp_regex_traitsIcEEEEEEbT_SD_RNS_13match_resultsISD_T0_EERKNS_11basic_regexIT1_T2_EENS_15regex_constants12_match_flagsE+0x61): In function `bool boost::regex_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >(__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, boost::match_results<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >&, boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)':
: undefined reference to `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::match()'
/misc/raid2/Melchior/foolishbrat/tmp/ccr3zzcH.o(.gnu.linkonce.t._ZN5boost11basic_regexIcNS_12regex_traitsIcNS_16cpp_regex_traitsIcEEEEE6assignEPKcS7_j+0x27): In function `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign(char const*, char const*, unsigned)':
: undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned)'
/misc/raid2/Melchior/foolishbrat/tmp/ccr3zzcH.o(.gnu.linkonce.t._ZN5boost9re_detail12perl_matcherIN9__gnu_cxx17__normal_iteratorIPKcSsEESaINS_9sub_matchIS6_EEENS_12regex_traitsIcNS_16cpp_regex_traitsIcEEEEEC1ES6_S6_RNS_13match_resultsIS6_S9_EERKNS_11basic_regexIcSD_EENS_15regex_constants12_match_flagsES6_+0xf2): In function `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::perl_matcher[in-charge](__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, boost::match_results<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >&, boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >)':
: undefined reference to `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
collect2: ld returned 1 exit status
```
**Update:**
Resolved with this compilation and linking:
```
g++ -I ~/.boost/include/boost-1_37 test.cc -o test /home/foolishbrat/.boost/lib/libboost_regex-gcc33-mt-1_37.a
``` | You need to link the necessary boost libraries.
Add `-l <path to libraries>` to the build command | ```
if (const regex_match(InputString, e)) {// this is line 26
```
You don't need to (and indeed, should not) say `const` here. Just remove the word, and at least this error should go away. | Compiling C++ Code With Boost's regex_match | [
"",
"c++",
"regex",
"string",
"boost",
"matching",
""
] |
I am playing back audio in C# using the `waveOut` functions with the callback method where messages are sent back to a window handle. I am creating a Windows Form with an overidden `WndProc` function to listen for the `MM_WOM_DONE` messages.
```
result = WaveInterop.waveOutOpen(out hWaveOut, devNumber, waveStream.WaveFormat, waveOutWindow.Handle, 0, WaveInterop.CallbackWindow);
```
All this works completely reliably when I am on the main GUI thread of my app. But if a background thread tries to do this, the `waveOutWindow` never receives any of the `WOM_` messages. I thought at first that perhaps the window had not been created properly, and its message queue was not being serviced, but even if I put the following code in before the `waveOutOpen`, it still doesn't work.
```
waveOutWindow.Show();
Debug.Assert(waveOutWindow.IsHandleCreated, "Handle not created!");
Debug.Assert(waveOutWindow.Created, "Window not created!");
```
I should say that the call to `waveOutOpen` is successful as are the initial `waveOutWrite` calls, but I never get my callbacks back to know when to queue more audio.
Am I missing something really obvious about forms on background threads? | Are you pumping messages on your secondary thread? | You should monitor message input via [WinSpector](http://www.windows-spy.com/).
You don't know how audio library implemented message handling - perhaps it sends to the main application window procedure. Maybe you can even construct it another way to feed hwnd of the window that is to receive notifications.
Anyway, if any message is sent, you will see it in WinSpector. | WinForms window created on worker thread not receiving all expected messages | [
"",
"c#",
"winforms",
"multithreading",
"audio",
""
] |
I did a lot of research about this topic and didn't yet find a satisfying answer:
How can I make a scrollable list (iPhone SDK Dashboard List) inside some other html content? If I create a list inside a html body and I try to scroll the whole page is scrolled. I know there is this "double finger" scrolling, but that's not what i want.
Is there some way to prevent the whole iPhone Safari Webpage from scrolling and instead letting other lists inside scroll? Like redirecting java script events?
Background: the idea is to mimic a real native application behavior with tabs at the bottom and a selection list in the body.
Appreciate any hints!
Thanks,
Patrick | there is yet another possibility, with slightly nicer scrolling simulation:
<http://cubiq.org/scrolling-div-on-iphone-ipod-touch/5> | Ok, after consulting some friends, I found the answer to this question:
<http://doctyper.com/archives/200808/fixed-positioning-on-mobile-safari/>
have fun. | iPhone Safari: Scroll a list inside a html container | [
"",
"javascript",
"iphone",
"safari",
""
] |
Basically, what it says on the tin; I need a JTA implementation useable in a Java SE application, ideally one that doesn't carry too much of a framework burden with it. | I recommend [Bitronix](https://github.com/bitronix/btm). Before using any other transaction manager, I recommend thorough testing. Tests like killing power to various machines during each phase of the transaction. You want transactionality to protect you when failures occur. It is surprising how many transaction managers have failed to correctly implement recovery.
Bitronix does need JNDI, which is typically provided for you in a Java EE container, but they include a simple embedded implementation that will support Bitronix in a Java SE application. | From its webpage:
"With over 20 years of expertise in the area of transaction processing,
[JBoss Transactions](http://www.jboss.org/jbosstm/) (JBossTS) is the premier open source transaction manager.
It can be deployed within a range of application servers, containers or run stand-alone. Over the past 20 years it has been used extensively within industry and to drive standards including the OMG and Web Services." | What is a good open source Java SE JTA TransactionManager implementation? | [
"",
"jta",
"java",
"transactionmanager",
""
] |
Surprisingly the code bellow will not succeed.
```
int? n1 = null;
int? n2 = null;
Assert.IsTrue(n1 <= n2); // Fails here
```
Do you know why? | Using boolean logic with null nullable values in C# (and VB.Net) often times defies logic. I find the best way to make sense of it is to remember that "null is not a value". Because null is not a value you cannot do any operations on it. Hence things like "`1 > null`" and "`1 < null`" are both true.
Here is a detailed guide: <http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx>
If you do want to treat null as a value then you could use the GetValueOrDefaultMethod() to equate null with the default value. For example
```
Assert.IsTrue(n1.GetValueOrDefault() <= n2.GetValueOrDefault()); // True
```
This is a bit verbose but it will get the job done. | Either this is a typo and you meant "==" not "<=" or you misunderstand how nulls work.
In almost all languages (including c#) the only default legal operation on null is to check if something else is equal to it (in .Net == is by default reference equality).
<= and >= are not meaningful (as they would have very strange behaviour if they did)
Some languages (SQL being possibly the most well known) disallow the use of 'standard' equality operators to make this even more clear. in SQL null == null is NOT true, and a compliant server will refuse queries where you attempt to do this via a literal.
C# takes the same route as it's heritage (C style imperative languages) where the test for a null value is based on testing that the bits in it are zero (things get somewhat more complex but fundamentally that's what is happening). As such only reference types can truly be null (`Nullable<T>` has a lot of magic behind the scenes to make it look like it is but actually under the hood it *isn't null*). This means that the reference equality semantics follow nicely into null semantics, thus the == null is allowed.
Other languages implement null in a different fashion (for example SQL where anything can be made null thus the 'nullness' of something must be stored outside of it (much like Nullable). This means that the conventional use of equality need not be the primary concern and null can be truly special rather than a special case of certain types.
For further information on the specialness of null take a look at [This question has a list of such languages](https://stackoverflow.com/questions/75267/in-how-many-languages-is-null-not-equal-to-anything-not-even-null/75314#75314)
Most reference types do not define a >= or <= operator so there is little problem in practice with the disconnect between == and <= (where normally if something is true for == it would be true for <= and >= as well). | Why nullable types will not be equal in this case? | [
"",
"c#",
"null",
""
] |
Imagine we have 5 string variables and we want to assign "Foo" to them during runtime.
Instead of this
```
string a1 = "Foo";
string a2 = "Foo";
string a3 = "Foo";
string a4 = "Foo";
string a5 = "Foo";
```
Can't we use something like this:
```
for(int i = 0;i < 5;i++)
{
a+i = "Foo";
}
```
Is it impossible to access them in a similiar way? | As others have said, an array (or another collection) is a much better way of doing this.
Think of an array as just being a collection of variables which you *always* access by index.
I can't think of any reason why you'd want to have a set of variables as shown in your question. If you absolutely *have* to do that, and they're instance/static variables, you could use reflection to access them if you really wanted to - but using an array or other collection would be much, much better. | ```
Label[] labels = new Label[] { label1, label2, label3, label4, label5 };
for (int i = 0; i < labels.Length; i++)
{
labels[i].Text = "Foo";
}
``` | C#: How do i assign many variables with an integer(i) in for loop? | [
"",
"c#",
"object",
"integer",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.