Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need to remove diagramming support tables, stored procs, views, etc from SQL Servrer using TSQL script. Is there such a script available? SQL 2005 and 2008.
You can drop the objects, but a user will be prompted to recreate them when they click the diagrams node. Objects: * sp\_upgraddiagrams * sp\_helpdiagrams * sp\_helpdiagramdefinition * sp\_creatediagram * sp\_renamediagram * sp\_alterdiagram * sp\_dropdiagram * fn\_diagramobjects * sysdiagrams * dt\_properties (?)
``` DROP PROCEDURE dbo.sp_alterdiagram; DROP PROCEDURE dbo.sp_creatediagram; DROP PROCEDURE dbo.sp_dropdiagram; DROP PROCEDURE dbo.sp_helpdiagramdefinition; DROP PROCEDURE dbo.sp_renamediagram; DROP PROCEDURE dbo.sp_upgraddiagrams; DROP PROCEDURE dbo.sp_helpdiagrams; DROP FUNCTION dbo.fn_diagramobjects; DROP TABLE dbo.sysdiagrams; ``` That removes all of them. Would be nice if there was as remove diagrams references wizard like the add.
How to remove diagramming support objects from SQL Server?
[ "", "sql", "sql-server", "sql-server-2005", "sql-server-2008", "diagram", "" ]
I have some code that works and changes the style sheet using a form. That work as long as you keep the browser window open. You can got to a different site come back and the style will be the one you selected, thats fine but if u close the browser and come back it will be set to the default. Is this due to the fact that I am starting a new session each time or is due to the fact I have not set how long the cookie is valid? Thats question one. Question 2 is that I have the drop down menu that currenty works and chooses the correct style sheet but I also have some radio buttons for text size. I want these to be incorperated but they will work using a different style sheets that simply have just the text sizes in so the default text size is standard and the user can change them along with the style sheet but they work indepdantly. Could anyone suggest some coding thanks. Below is what I am currently working with. Cheers Php setting the style: ``` if (isset($_COOKIE["selectedStyle"])) // has the cookie already been set { $style=$_COOKIE["selectedStyle"]; }else{ $style = spring; } if (isset($_POST["changeStyle"])) // changing the style { $style=$_POST["changeStyle"]; } setcookie("selectedStyle",$style); // update or create the cookie ?> ``` Form with drop down that works and radio buttons for the text changer: ``` <div id="headerInfo"> <p><strong>User Controls</strong></p> <form method="post" action="<?= $_SERVER["PHP_SELF"];?>"> Select Page Style:<br/> <select name="changeStyle"> <option value="spring">Spring (Green)</option> <option value="summer">Summer (Yellow)</option> <option value="winter">Winter (Blue)</option> <option value="autumn">Autumn (Orange)</option> </select> <input type="submit" name="submitstyle" value="Set Style"> </form> <form method="post" action="<?= $_SERVER["PHP_SELF"];?>"> Select Font Size:<br/> <span class="smallText">A</span><input type="radio" name="changeFontSize" value="small"/> <span class="standardText">A</span><input type="radio" name="changeFontSize" value="standard"/> <span class="largeText">A</span><input type="radio" name="changeFontSize" value="large"/> <span class="xLargeText">A</span><input type="radio" name="changeFontSize" value="extraLarge"/> </select> <input type="submit" name="submitfont" value="Set Size"> </div> ```
[setcookie](http://php.net/setcookie) has an `expire` parameter, which you can use to set desired expiration date. docs have an example on how to do this. just create another cookie with font size information and invoke relevant stylesheet. radio button need to be inside the `form` tag to be send as a part of http request.
When it comes to the font resizing I would personally say, you are better off changing the size on the client side, [with jQuery for example](http://www.shopdev.co.uk/blog/text-resizing-with-jquery/). I think generally if someone requires a larger font size on every page (for accessibility) they would have the font size increased in the browser. Although you could also do an AJAX call to set a cookie / save a record in the DB if you wanted to change stylesheet elements / set a higher font size permanently.
Using cookies and php to change style sheets(CSS)
[ "", "php", "css", "cookies", "styles", "" ]
The question is: How to make default button be focused on form focus and response on "Enter" hit, but not focused when the caret is in textbox with multiline property set to true for example?..I know that i can do some exceptions in code, but maybe there is some "best practices" i dont know for now :( thank you
Maybe I got you wrong, but what I would do is: 1. Set the "AcceptButton" of the form to the Button you want to respond on "Enter" 2. Set the "AcceptsReturn" of the textbox with multiline to true et voila
(edit - the answer [here](https://stackoverflow.com/questions/446147/default-button-hit-in-windows-forms-trying-to-find-the-best-solution#446177) is very good for `TextBox`; this pattern might be useful for other controls that lack the `AcceptsReturn` or equivalent) You can use the `GotFocus` and `LostFocus` events to change the `AcceptButton` fairly easily, for example: ``` [STAThread] static void Main() { Application.EnableVisualStyles(); TextBox multi, single; Button btn; using(Form form = new Form { Controls = { (multi= new TextBox { Multiline = true, Dock = DockStyle.Fill}), (btn = new Button { Text = "OK", Dock = DockStyle.Bottom, DialogResult = DialogResult.OK}), (single = new TextBox { Multiline = false, Dock = DockStyle.Top}), }, AcceptButton = btn }) { multi.GotFocus += delegate { form.AcceptButton = null; }; multi.LostFocus += delegate { form.AcceptButton = btn; }; btn.Click += delegate { form.Close(); }; Application.Run(form); } } ```
Default button hit in windows forms (trying to find the best solution)
[ "", "c#", ".net", "windows", "winforms", "" ]
I have a controller build for a web application with a web presentation. But now I need to create a iphone (mobile phone) version of this application. Basically this is a blog application with comments. In the regular version comments are loaded at the same time as the entry. But on the mobile application I want to comments to be load on request. How do you achieve that. * 1 controller 2 views : 2 different action (one for each view). But I can have a lot of actino that will be similar but not exactly. And routing will be an issue * 2 controller 1 view per controller : 1 manage the regular version the other manage the mobile version. I open to other ideas. BTW I use Zend Framework.
You should define a [ContextSwitch action helper](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch). You'd also need a way to recognize requests made from iPhone platforms.
I think the "RESTful" way to do it would be to use the same URI (so same controller/action), and to detect (either from session, or by looking at the User Agent header) whether you want to render the full version or the mobile version. So you'd only have one controller/action which looked like this: ``` class BlogController { function ShowPost() { if (IsMobile) { View("PostWithComments_Mobile"); } else { View("PostWithComments"); } } } ``` Depending on how much control you have over the framework (I don't know PHP nor Zend) you might be able to automatically have it switch to a different view depending on whether a mobile version exists and the user agent. A quick Google search results in many samples for detecting mobile browsers.
MVC with different presentation
[ "", "php", "model-view-controller", "zend-framework", "" ]
I have 2 tables like which I would like to query to form a new table. table 1 ``` number type serial index 1000001 613 3 1 1000001 613 3 1 1000001 613 3 1 1000001 613 3 1 1000001 613 4 1 1000001 613 3 1 ``` table 2 ``` number type serial index 1000001 613 3 2 1000001 613 3 3 1000001 613 3 4 1000001 613 3 4 1000001 613 4 2 1000001 613 3 1 ``` I am looking for a query which gives a resultant of indexes and numbers like this, and adds the index, and gives the result: ``` output table number index 1000001 3 1000001 4 1000001 5 1000001 5 1000001 3 1000001 2 ``` I want to prevent cross joins here. I can't use where clause because the numbers are same in both tables only the index varies. How can I execute this one-to-one and not one-to-many.
I don't think it's possible to do what you are asking. You would have to be able to distinguish each row uniquely to guarantee a 1-to-1 result (this is normally the job of your index column or ID column). You might be able to jerry-rig something with rownum, however, if the tables are identically ordered, then perhaps you've over-normalised. Table 1 and 2 should really just be one, and you have two index columns (index1 and index2) in the one table.
Based on my understanding of the problem, you want to add the index column on the equivalent rows in each table. Since MS Access has no row number function like database servers, what I can suggest is temporarily add a new autonumber field for each table. This will give you something to inner join on and then add. Say you call this column tempAuto on both tables. ``` SELECT t1.number, (t1.index + t2.index) AS index FROM table1 t1 INNER JOIN table2 t2 ON t1.tempAuto = t2.tempAuto; ``` You can then delete the extra columns after you have performed whatever data manipulation.
Query in Access
[ "", "sql", "ms-access", "" ]
My (C#, .NET 3.5) application generates files and, in addition to raising events that can be caught and reacted to, I want to display the target folder to the user in a form. The file-list is being shown within the same form as other information. I'm using an instance of the `WebBrowser` control (`System.Windows.Forms.WebBrowser`), then navigating to the folder. This shows some default view of the explorer window, with the file summary panel on the left and the files in the 'Tiles' (large icon and text) view. For example, ``` wb.Navigate(@"c:\path\to\folder\"); ``` I'd like to suppress the panel and to view the file list in the Details view. The user can get to this via a right-click, context menu, but I'd like it to come up automatically. I'd rather not have to build my own TreeView, DataGridView or whatever; the WebBrowser control does all the updating and re-sorting and whatnot 'for free'. Is there a better way? A different control to use or some additional arguments to pass to the control? And if I could trap events (for example, files being selected/renamed/double-clicked, etc.) then all the better!
In order to handle renaming, deleting and make other customization you need to write your own file explorer. WebBrowser control is not suitable for your needs. It's just a wrapper over ActiveX component. You should check [this codeproject article](http://www.codeproject.com/KB/miscctrl/FileBrowser.aspx). It contains an implementation of file explorer. There are few more samples of file browser: [one](http://www.c-sharpcorner.com/UploadFile/satisharveti/enhancedWinExplorer02092009014722AM/enhancedWinExplorer.aspx) [two](http://www.c-sharpcorner.com/UploadFile/ssrivastav/AdvancedFileExplorerusingCSharpandWindowsForms11232005033710AM/AdvancedFileExplorerusingCSharpandWindowsForms.aspx)
WARNING: Long post with lots of code. When you navigate the web browser control to a file system folder the web browser control hosts a shell view window that in turn hosts the explorer list view. In fact this is exactly the same thing that the Explorer process does as well as the file dialogs and Internet Explorer. This shell window is not a control so there are no methods that can be called on it or events that can be subscribed to but it can receive windows messages and it can be sub-classed. It turns out that the part of your question dealing with setting the view to Details automatically is actually quite easy. In your web browser control's Navigated event simply find the handle to the shell view window and send it a WM\_COMMAND message with a particular shell constant (SHVIEW\_REPORT). This is an undocumented command but it is supported on all Windows platforms up to and including Windows 2008 and almost certainly will be on Windows 7. Some code to add to your web browser's form demonstrates this: ``` private delegate int EnumChildProc(IntPtr hwnd, IntPtr lParam); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", SetLastError = true)] private static extern int EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); private const int WM_COMMAND = 0x0111; private const int SHVIEW_REPORT = 0x702C; private const string SHELLVIEW_CLASS = "SHELLDLL_DefView"; private IntPtr m_ShellView; void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { m_ShellView = IntPtr.Zero; EnumChildWindows(webBrowser1.Handle, EnumChildren, IntPtr.Zero); if (m_ShellView != IntPtr.Zero) { SendMessage(m_ShellView, WM_COMMAND, (IntPtr)SHVIEW_REPORT, (IntPtr)0); } } private int EnumChildren(IntPtr hwnd, IntPtr lParam) { int retval = 1; StringBuilder sb = new StringBuilder(SHELLVIEW_CLASS.Length + 1); int numChars = GetClassName(hwnd, sb, sb.Capacity); if (numChars == SHELLVIEW_CLASS.Length) { if (sb.ToString(0, numChars) == SHELLVIEW_CLASS) { m_ShellView = hwnd; retval = 0; } } return retval; } ``` Every time the web browser navigates to a new window (including when a folder is opened from within the explorer view) a new shell view window is created so the message must be re-sent to the new window in every Navigated event. For the second part of your question you would like to receive events from the explorer list view. This is quite a bit more difficult than the first part. To do this you would need to sub-class the list view window and then monitor the windows messages for ones that interest you (such as WM\_LBUTTONDBLCLK). In order to sub-class a window you would need to create your own class derived from the NativeWindow class and assign it the handle of the window that you need to monitor. You can then override its Window procedure and handle the various messages as you wish. Below is an example of creating a double click event - it is relatively simple but to get extensive access to the explorer list view may involve a lot more work than you are willing to do. Add this to your form: ``` private ExplorerListView m_Explorer; void OnExplorerItemExecuted(object sender, ExecuteEventArgs e) { string msg = string.Format("Item to be executed: {0}{0}{1}", Environment.NewLine, e.SelectedItem); e.Cancel = (MessageBox.Show(msg, "", MessageBoxButtons.OKCancel) == DialogResult.Cancel); } ``` and these two lines to the Navigated event handler (right after the SendMessage): ``` m_Explorer = new ExplorerListView(m_ShellView); m_Explorer.ItemExecuted += OnExplorerItemExecuted; ``` Then add the following classes: ``` class ExplorerListView : NativeWindow { public event EventHandler<ExecuteEventArgs> ItemExecuted; [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); private const int WM_LBUTTONDBLCLK = 0x0203; private const int LVM_GETNEXTITEM = 0x100C; private const int LVM_GETITEMTEXT = 0x1073; private const int LVNI_SELECTED = 0x0002; private const string EXPLORER_LISTVIEW_CLASS = "SysListView32"; public ExplorerListView(IntPtr shellViewHandle) { base.AssignHandle(FindWindowEx(shellViewHandle, IntPtr.Zero, EXPLORER_LISTVIEW_CLASS, null)); if (base.Handle == IntPtr.Zero) { throw new ArgumentException("Window supplied does not encapsulate an explorer window."); } } protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_LBUTTONDBLCLK: if (OnItemExecution() != 0) return; break; default: break; } base.WndProc(ref m); } private int OnItemExecution() { int cancel = 0; ExecuteEventArgs args = new ExecuteEventArgs(GetSelectedItem()); EventHandler<ExecuteEventArgs> temp = ItemExecuted; if (temp != null) { temp(this, args); if (args.Cancel) cancel = 1; } return cancel; } private string GetSelectedItem() { string item = null; IntPtr pStringBuffer = Marshal.AllocHGlobal(2048); IntPtr pItemBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LVITEM))); int selectedItemIndex = SendMessage(base.Handle, LVM_GETNEXTITEM, (IntPtr)(-1), (IntPtr)LVNI_SELECTED).ToInt32(); if (selectedItemIndex > -1) { LVITEM lvi = new LVITEM(); lvi.cchTextMax = 1024; lvi.pszText = pStringBuffer; Marshal.StructureToPtr(lvi, pItemBuffer, false); int numChars = SendMessage(base.Handle, LVM_GETITEMTEXT, (IntPtr)selectedItemIndex, pItemBuffer).ToInt32(); if (numChars > 0) { item = Marshal.PtrToStringUni(lvi.pszText, numChars); } } Marshal.FreeHGlobal(pStringBuffer); Marshal.FreeHGlobal(pItemBuffer); return item; } struct LVITEM { public int mask; public int iItem; public int iSubItem; public int state; public int stateMask; public IntPtr pszText; public int cchTextMax; public int iImage; public IntPtr lParam; public int iIndent; public int iGroupId; int cColumns; // tile view columns public IntPtr puColumns; public IntPtr piColFmt; public int iGroup; } } public class ExecuteEventArgs : EventArgs { public string SelectedItem { get; private set; } public bool Cancel { get; set; } internal ExecuteEventArgs(string selectedItem) { SelectedItem = selectedItem; } } ``` This should give you an idea of what you would need to do. If you want more than fairly simple events you may want to look for a alternative control, though from what I have seen in the free and low cost areas there are some pretty decent controls but they all have some quirks and will not give a seamless explorer experience. Remember this code was put together fairly quickly without error handling or comments and ignoring several issues such as multiple selected items, so use it as a guideline and at your own risk.
Embedding a File Explorer instance in a Windows Forms application form
[ "", "c#", "winforms", "explorer", "" ]
I'm using Google Ajax API and they suggest I use `google.setOnLoadCallback()` to do various things related to their API but I'm using also jQuery's `$(document).ready()` to do other JS things, not related to Google API. Is it safe to mix these two approaches in one document? I did not notice any problems yet but I suppose it's a matter of scale.
You pretty much have to do this: ``` google.setOnLoadCallback(function() { $(function() { // init my stuff }); }); ``` You can't do `$(document).ready()` without `$` (the jQuery object) being available, so that needs to go inside the callback. And you can't be sure the document is ready inside the callback, so you have to do `ready()` too.
Sorry to be raising this from the dead, but 1) It still comes up as an 'answer' to this problem and 2) I've found a better solution. There is an optional 3rd argument on the `google.load` function that takes an object of configuration options. One of the options is `callback`. It also gets rid of the need for a separate `setOnLoadCallback` call. E.g. ``` google.load('visualization', '1.0', { 'packages': "charttype", 'callback': $jQ.proxy(me.setupChart, me) }); ``` So: ``` <script src="https://www.google.com/jsapi"></script> <script> $(document).ready(function () { function mapsLoaded() { etc etc etc } google.load("maps", "2", {"callback" : mapsLoaded}); }); </script> ``` See: <https://developers.google.com/loader/#Dynamic>
google.setOnLoadCallback with jQuery $(document).ready(), is it OK to mix?
[ "", "javascript", "jquery", "onload", "google-ajax-api", "" ]
I am trying to set a variable that I will refer to in a custom JSP tag, so I have something like this in my JSP: ``` <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="path" value="test"/> ``` However, I am getting this error when The JSP runs: ``` java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext; at org.apache.taglibs.standard.tag.common.core.SetSupport.doEndTag(SetSupport.java:140) ``` I am running Tomcat 5.5, and Java 1.5, with JSTL 1.2. Am I doing something wrong here? Thanks!
Looks like you may have some versioning problem, maybe a conflicting jar file of some sort. Look [here](http://faq.javaranch.com/view?JstlTagLibDefinitions), maybe it'll help. You need to supply some more info about your runtime environment if you can't solve it.
This seems to come up quite a bit. We had Hadoop as a dependency and had to do multiple exclusions. Some of these are probably redundant, but this finally worked. I should note that there was no change until I started excluding Jasper at the bottom. ``` <exclusions> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>jsp-2.1</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>jsp-api-2.1</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>jsp-api</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>servlet-api</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>servlet-api-2.5</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty</artifactId> </exclusion> <exclusion> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-util</artifactId> </exclusion> <exclusion> <groupId>tomcat</groupId> <artifactId>jasper-compiler</artifactId> </exclusion> <exclusion> <groupId>tomcat</groupId> <artifactId>jasper-runtime</artifactId> </exclusion> </exclusions> ```
java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext;
[ "", "java", "jsp", "jstl", "jsp-tags", "" ]
Let's say I have two classes like the following: ``` Class A { public: .. private: int length; } Class B: public Class A { public: .. private: float length; } ``` What I would like to know is: 1. Is *overriding of base class data members* allowed? 2. If yes, is it a good practice? 3. If no, what is the best way to extend the type of the data members of a class? There is a class that satisfies my needs and I want to reuse it. However for my program needs, its data members should be of another type. I have some books, but all of them refer only to overriding of base class member methods.
You can use templatized members i.e., generic members instead of overriding the members. You can also declare a VARIANT(COM) like union. ``` struct MyData { int vt; // To store the type union { LONG lVal; BYTE bVal; SHORT iVal; FLOAT fltVal; . . } }; ```
1) No you can't. You can create your own internal/hidden/private members, but you can't overide them. 2) If you could, not it wouldn't be good practice. Think about it ;) 3) You shouldn't, as you're changing the meaning of the member.
In Inheritance: Can I override base class data members?
[ "", "c++", "" ]
**Can a regular expression match whitespace *or* the start of a string?** I'm trying to replace currency the abbreviation GBP with a £ symbol. I could just match anything starting GBP, but I'd like to be a bit more conservative, and look for certain delimiters around it. ``` >>> import re >>> text = u'GBP 5 Off when you spend GBP75.00' >>> re.sub(ur'GBP([\W\d])', ur'£\g<1>', text) # matches GBP with any prefix u'\xa3 5 Off when you spend \xa375.00' >>> re.sub(ur'^GBP([\W\d])', ur'£\g<1>', text) # matches at start only u'\xa3 5 Off when you spend GBP75.00' >>> re.sub(ur'(\W)GBP([\W\d])', ur'\g<1>£\g<2>', text) # matches whitespace prefix only u'GBP 5 Off when you spend \xa375.00' ``` Can I do both of the latter examples at the same time?
Use the OR "`|`" operator: ``` >>> re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text) u'\xa3 5 Off when you spend \xa375.00' ```
`\b` is word boundary, which can be a white space, the beginning of a line or a non-alphanumeric symbol (`\bGBP\b`).
Regular expression: match start or whitespace
[ "", "python", "regex", "" ]
This is quite straightforward - gcc fails to to compile this sample code (c++). ``` class myclass { struct mystruct { myclass something; int something_else; }; }; ``` It tells me, that > Field 'something' has incomplete type. I probably miss something trivial, because I'm quite new in c++, but why can't I make nested class/struct with references to outside class?
You can't put an object into itself. Perhaps you wanted a pointer to myclass.
Well, at the time you put that member, the nesting class, myclass, is not complete yet. You can define the mystruct type afterwards, when myclass is complete: ``` class myclass { struct mystruct; }; struct myclass::mystruct { myclass something; int something_else; }; ``` Note that just because mystruct is a nested type of myclass, that does not mean that myclass contains an object of mystruct. So there is no problem with circular containment here. Since you mention you come from Java - maybe it helps you when i tell you nested classes are like static nested classes in Java. In fact, C++ does not have "non-static nested classes" like they exist in Java. So if you create a myclass object, neither there is a mystruct object automatically created and embedded, nor there is a special relationship between a mystruct that can be created and any created object of the nesting class. What nested classes in C++ buy you (probably some more - this is from the top of my head): * Including members of the outer class into usual unqualified name-lookup (1) * Automatic friendship of the nested class and the nesting class - the nested class can access non-public members of the nesting class. (2) * Hiding or encapsulating the nested class from outside into the nesting class. Here is an example: ``` class myclass { typedef int test_type; struct mystruct; mystruct * s; }; struct myclass::mystruct { mystruct() { // note, setting private member (2) something.s = this; // note, we don't have to type myclass::test_type (1) test_type silly_integer = 42; } myclass something; int something_else; }; ``` But you probably meant to put a pointer to the nesting class anyway in your code - which is often needed when nested classes are into the game. You have to remember that when you have a variable, that variable is the name for the object itself - instead of merely a reference (like in java) to it. A C++ pointer, however, behaves like a Java reference - it can be nulled and point to different objects during its lifetime: ``` struct myclass::mystruct { myclass *something; int something_else; }; ``` That will make it merely reference an object of type myclass, which is to be created elsewhere, instead of being that object itself. So, it is like a node that *may* have one parent (pointed to by something) - but doesn't have to. And like an iterator that points to some container it's iterating over. There is also the other way around, where the nesting class has a pointer to the nested class (apart from my silly example above). That's very commonly used in the **pimpl idiom**. I highly recommend you to have a look at it.
nested classes and references to outside classes (c++)
[ "", "c++", "" ]
Can you explain to me: * What is a Predicate Delegate? * Where should we use predicates? * Any best practices when using predicates? Descriptive source code will be appreciated.
A predicate is a function that returns `true` or `false`. A predicate delegate is a reference to a predicate. So basically a predicate delegate is a reference to a function that returns `true` or `false`. Predicates are very useful for filtering a list of values - here is an example. ``` using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int> { 1, 2, 3 }; Predicate<int> predicate = new Predicate<int>(greaterThanTwo); List<int> newList = list.FindAll(predicate); } static bool greaterThanTwo(int arg) { return arg > 2; } } ``` Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion: ``` using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int> { 1, 2, 3 }; List<int> newList = list.FindAll(i => i > 2); } } ```
Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below). ``` using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int> { 1, 2, 3 }; List<int> newList = list.FindAll(delegate(int arg) { return arg> 2; }); } } ``` Hope this helps.
What is a Predicate Delegate and where should it be used?
[ "", "c#", ".net", "predicate", "" ]
Is there a way to do character translation / transliteration (kind of like the [`tr`](https://perldoc.perl.org/functions/tr) command) using **Python**? Some examples in Perl would be: ``` my $string = "some fields"; $string =~ tr/dies/eaid/; print $string; # domi failed $string = 'the cat sat on the mat.'; $string =~ tr/a-z/b/d; print "$string\n"; # b b b. (because option "d" is used to delete characters not replaced) ```
See [`string.translate`](http://docs.python.org/library/stdtypes.html#str.translate) ``` import string "abc".translate(string.maketrans("abc", "def")) # => "def" ``` Note the doc's comments about subtleties in the translation of unicode strings. And for Python 3, you can use directly: ``` str.translate(str.maketrans("abc", "def")) ``` Edit: Since `tr` is a bit more advanced, also consider using `re.sub`.
If you're using python3 translate is less verbose: ``` >>> 'abc'.translate(str.maketrans('ac','xy')) 'xby' ``` Ahh.. and there is also equivalent to `tr -d`: ``` >>> "abc".translate(str.maketrans('','','b')) 'ac' ``` For `tr -d` with python2.x use an additional argument to translate function: ``` >>> "abc".translate(None, 'b') 'ac' ```
Character Translation using Python (like the tr command)
[ "", "python", "tr", "transliteration", "" ]
Is there any way to take a StreamWriter and output the file (in this case a .txt file) to the user with the option to open/save without actually writing the file to disk? If it is not saved it will basically go away. I am looking for the same functionality of ``` HttpContext.Current.Response.TransmitFile(file); ``` but without having to save anything to disk. Thanks!
Try a `System.IO.MemoryStream` ``` System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(ms); sw.Write("hello"); ```
I've done this recently for a XML file, Should be easy for you to adapt ``` protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.AppendHeader("content-disposition", "attachment; filename=myfile.xml"); Response.ContentType = "text/xml"; UTF8Encoding encoding = new UTF8Encoding(); Response.BinaryWrite(encoding.GetBytes("my string")); Response.Flush(); Response.End(); } ```
output a .txt file from a StreamWriter without writing to disk?
[ "", "c#", "asp.net", ".net", "" ]
I am looking for a good API documentation for Javascript especially related to browsers and DOM. I am not looking for any kind of Javascript tutorial, but simply a documentation for all standard Javascript classes and for classes used in web browsers. Something similar to Java's Javadoc ( <http://java.sun.com/j2se/1.4.2/docs/api/> )
How about the standards? 1. [DOM2 Core](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.pdf) (W3C) 2. [DOM2 Events](http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/DOM2-Events.pdf) (W3C) 3. [DOM2 HTML](http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/DOM2-HTML.pdf) (W3C) 4. [DOM2 CSS](http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/DOM2-Style.pdf) (W3C) And for javascript itself: 5. [Standard ECMA-262 ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (ECMA)
[Gecko DOM Reference](https://developer.mozilla.org/en/Gecko_DOM_Reference) [JavaScript Kit - DOM Reference](http://www.javascriptkit.com/domref/) [And many more](http://www.google.com/search?q=dom+reference).
A good Javascript API reference documentation related to browsers and DOM
[ "", "javascript", "api", "reference", "" ]
I could just create a form and use that to do a POST request to any site, thing is the FORM method isn't asynchronous, I need to know when the page has finished loading. I tried messing around with this using an iframe with a form inside, but no success. Any ideas? **EDIT** unfortunately I have no control over the response data, it varies from XML, json to simple text.
You can capture the `onload` event of an `iframe`. Target your `form` to the iframe and listen for the onload. You will not be able to access the contents of the iframe though, just the event. Try something like this: ``` <iframe id='RS' name='RS' src='about:blank' onload='loaded()'></iframe> <form action='wherever.php' target='RS' method='POST'>...</form> ``` script block: ``` var loadComplete = 0 function loaded() { //avoid first onload if(loadComplete==0) { loadComplete=1 return() } alert("form has loaded") } ```
IF you want to make cross domain requests you should either made a JSON call or use a serverside proxy. A serverside proxy is easy to set up, not sure why people avoid it so much. Set up rules in it so people can not use the proxy to request other things.
Asynchronous cross-domain POST request via JavaScript?
[ "", "javascript", "ajax", "cross-domain", "" ]
I wonder if there is an easy way to check if two strings match by excluding certain characters in the strings. See example below. I can easily write such a method by writing a regular expression to find the "wild card" characters, and replace them with a common character. Then compare the two strings str1 and str2. I am not looking for such implementations, but like to know whether there are any .Net framework classes that can take care of this. Seems like a common need, but I couldn't find any such method. For example: ``` string str1 = "ABC-EFG"; string str2 = "ABC*EFG"; ``` The two strings must be declared equal. Thanks!
Sorry but I think either regex, or replacing the "wildcard" characters with a common character are going to be your best solution. Basically, the answers that you stated you didn't want to receive.
I found myself having the same requirements, the solution I used was based on the String.Compare method: ``` String.Compare(str1, str2, CultureInfo.InvariantCulture, CompareOptions.IgnoreSymbols) ```
Compare two strings by ignoring certain characters
[ "", "c#", "string", "" ]
A while back I read (before I lost it) a great book called [GUI Bloopers](http://www.gui-bloopers.com/) which was full of examples of [bad GUI design](https://stackoverflow.com/questions/238177/worst-ui-youve-ever-used) but also full of useful tidbits like *Don't call something a* `Dialog` *one minute and a* `Popup` *the next*. What top tips would you give for designing/documenting a GUI? It would be particularly useful to hear about widgets you designed to cram readable information into as little screen real-estate as possible. I'm going to roll this off with one of my own: **avoid trees** (e.g. Swing's `JTree`) unless you really can't avoid it, or have a unbounded hierarchy of stuff. I have found that users don't find them intuitive and they are hard to navigate and filter. PS. I think this question differs from [this one](https://stackoverflow.com/questions/136910/gui-design-how-do-you-do-it) as I'm asking for generalist tips
well I personally follow these simple rules: * be consistent throughout the application **DO NOT CHANGE BEHAVIOUR/LAYOUT** * information flow: from top to bottom from left to right (in western-countries) * not too much info on a page (like a ppt-presentation) * big letters (so old people can read them too) * KISS (whoever can use a videorecorder can use this page/form/etc.) * use relaxing colors like blue, green, etc. (not bright-red or neon-pink) * Structure (can change of course but as a first draft mostly it is): + top -> navigation/menu + left -> navigation/info + middle -> content + bottom -> status + bottom right -> buttons
Just one rather concrete tip I got once from a skillful GUI techlead: When you have a dialog/form with buttons, text fields, lists etc, try to keep the space between them consistent and symetric. For instance, try using the same distance between widgets in all directions, and if a group of widgets is separated from another by increasing the space between the groups, try to make that space a duplicate of the space between the controls within the groups. For example if all buttons in one section are separated by 16 pixels in all directions, try making the larger space to the next group 32, 64, 128 or so pixels. It's much more comfortable for the human eye to interpret something which is bound to a distinct symmetry. Ever since I tried it I always use this method with very nice results. I even went back and reworked older GUIs and was surprised to see such a facelift from this adjustment only. **EDIT:** Forgot to mention an important lesson I learned from the above method: When you arrange all widgets according to this system (in particular when reworking old cluttered GUIs) you might run out of space, and your dialog needs to be inflated. At some point one can feel that the dialog is getting too large (e.g. blocking related background GUI or related widgets ending up too far from eachother). That might be a good indicator that you maybe should split the dialog into tabs, move things into the menu or just making it into a wizard-style concept etc. This is pretty unrelated to widget spacing but touches the subject of less-is-more for the user to interact with at any given time. It's interesting that when you start making things right it "ripples the water" and sometimes forces you to make more things right (kind of like fixing const correctness :p ).
Top tips for designing GUIs?
[ "", "java", "user-interface", "swing", "" ]
I have a the following dictionary: ``` IDictionary<int, IList<MyClass>> myDictionary ``` and I am wanting to get all the values in the dictionary as an IList.... --- Just to add a bit of a background as to how I've gotten into this situation.... I have a method that gets me a list of MyClass. I then have another method that converts that list into a dictionary where they key is the id for MyClass. Later on...and without access to that original list...I'm needing to obtain the original ungrouped list of MyClass. --- When I pass myDictionary.Values.ToList() to a method that takes an IList I get a compile error that says that it can't convert from ``` System.Collections.Generic.List<System.Collections.Generic.IList<MyClass>> ``` to: ``` System.Collections.Generic.IList<MyClass> ``` Now, I can understand that its gone and added each of the groups of IList to the new list as separate elements of the list....but in this instance its not really what I'm after. I just want a list of all the values in the entire dictionary. How then can I get what I'm after without looping through each of the key values in the dictionary and creating the list I want?
Because of how a dictionary (or hash table) is maintained this is what you would do. Internally the implementation contains keys, buckets (for collision handling) and values. You might be able to retrieve the internal value list but you're better of with something like this: ``` IDictionary<int, IList<MyClass>> dict; var flattenList = dict.SelectMany( x => x.Value ); ``` It should do the trick ;) SelectMany flattens the result which means that every list gets concatenated into one long sequence (IEnumerable`1).
Noticed a lot of answer were quite old. This will also work: ``` using System.Linq; dict.Values.ToList(); ```
How do I get all the values of a Dictionary<TKey, TValue> as an IList<TValue>?
[ "", "c#", ".net-3.5", "dictionary", "ilist", "" ]
I had no luck with [this question](https://stackoverflow.com/questions/553331/detecting-unusable-pooled-sqlconnections) so I've produced this simple-as-possible-test-case to demonstrate the problem. In the code below, is it possible to detect that the connection is unusable before trying to use it? ``` SqlConnection c = new SqlConnection(myConnString); c.Open(); // creates pool setAppRole(c); // OK c.Close(); // returns connection to pool c = new SqlConnection(myConnString); // gets connection from pool c.Open(); // ok... but wait for it... // ??? How to detect KABOOM before it happens? setAppRole(c); // KABOOM ``` The KABOOM manifests as a error in the Windows event log; > The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context. This scenario is not supported. See "Impersonation Overview" in Books Online. ...plus an exception in code. setAppRole is a simple method to set an application role on the connection. It is similar to this... ``` static void setAppRole(SqlConnection conn) { using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "exec sp_setapprole "; cmd.CommandText += string.Format("@rolename='{0}'",myUser); cmd.CommandText += string.Format(",@password='{0}'",myPassword); cmd.ExecuteNonQuery(); } } ``` In the real code an attempt is made to use **sp\_unsetapprole** prior to closing the connection but it cannot always be guaranteed (inherited buggy multithreaded app). In any case it still seems reasonable to expect to be able to detect the kaboom before causing it.
In short, it doesn't look like you can in any simple way. My first thought was to run this SQL: ``` SELECT CASE WHEN USER = 'MyAppRole' THEN 1 ELSE 0 END ``` This works if you use SQL Server Management Studio, but fails when you run it from C# code. The trouble is the error you are getting is not occuring when the call to sp\_setapprole is made, it is actually occuring when connection pooling calls sp\_reset\_connection. Connection pooling calls this when you first use a connection and there is no way to get in before it. So I guess you have four options: 1. Turn connection pooling off by adding "Pooling=false;" to your connection string. 2. Use some other way to connect to SQL Server. There are lower level APIs than ADO.Net, but frankly it is probably not worth the trouble. 3. As casperOne says you could fix your code to close the connection correctly. 4. Catch the exception and reset the connection pool. I'm not sure what this will do to other open connections though. Example code below: ``` class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection("Server=(local);Database=Test;UID=Scrap;PWD=password;"); setAppRole(conn); conn.Close(); setAppRole(conn); conn.Close(); } static void setAppRole(SqlConnection conn) { for (int i = 0; i < 2; i++) { conn.Open(); try { using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "exec sp_setapprole "; cmd.CommandText += string.Format("@rolename='{0}'", "MyAppRole"); cmd.CommandText += string.Format(",@password='{0}'", "password1"); cmd.ExecuteNonQuery(); } } catch (SqlException ex) { if (i == 0 && ex.Number == 0) { conn.Close(); SqlConnection.ClearPool(conn); continue; } else { throw; } } return; } } } ```
> it is actually occuring when connection pooling calls > sp\_reset\_connection. Connection pooling calls this when you first use > a connection and there is no way to get in before it. Based on [Martin Brown's answer](https://stackoverflow.com/questions/556494/how-can-i-detect-condition-that-causes-exception-before-it-happens/557514#557514), you could try adding "Connection Reset=False" to the connection string as a way to "get in before" sp\_reset\_connection. (See "[Working with “soiled” connections](http://betav.com/blog/billva/2007/05/managing_and_monitoring_net_co.html)" for an explanation of many of the drawbacks of this setting.) Your problem is a [known issue with connection pooling](http://support.microsoft.com/kb/229564). The suggested work-around is to disable connection pooling... if this is a desktop app it may be worth considering holding a few connections open instead (also explained in [the article linked above](http://betav.com/blog/billva/2007/05/managing_and_monitoring_net_co.html)). These days (SQL 2005+) the recommendation (under [Application Roles and Connection Pooling](http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx)) is to "take advantage of the [new security mechanisms](http://msdn.microsoft.com/en-us/library/bb669062.aspx) that you can use instead of application roles", like EXECUTE AS.
How can I detect condition that causes exception before it happens?
[ "", "c#", "sql-server", "ado.net", "connection-pooling", "application-role", "" ]
Imagine the following sql query: ``` UPDATE MYTABLE SET COL2 = (SELECT COL2 + 1 FROM (SELECT MAX(COL2) FROM MYTABLE) AS X) WHERE ID IN (1,2,3,4,5) ``` Assume that before the update is executed MAX(COL2) is 1. My intention is that for the update where ID=1 COL2 is updated to 'max(COL2) + 1' (i.e. 2), and that for subsequent updates 'MAX(COL2) + 1' is re-evaluated, so that for ID=2, COL2=3 and ID=3, COL2=4 etc... What actually happens is that for all rows (ID=1,2,3,4,5), the value of COL2 is 2. Is there a smart way to have the value of MAX(COL2) +1 "re-evaluated" at each update? I realize there may be performance issues with doing this, but I am curious none-the-less! Is there a better alternative (that does not involve multiple update statements) ? BTW: incase you are wondering about the syntax used for the above query (the nested inner table) see here: [SQL : Using the target table in an UPDATE statement in a nested FROM clause](https://stackoverflow.com/questions/556237/sql-using-the-target-table-in-an-update-statement-in-a-nested-from-clause)
``` UPDATE mytable, ( SELECT @loop := MAX(col1) FROM mytable ) o SET col1 = (@loop := @loop + 1) ``` What you encountered here is called `query stability`. No query can see the changes made by itself, or the following query: ``` UPDATE mytable SET col1 = col2 + 1 WHERE col1 > col2 ``` would never end.
Here's the way I'd do it: ``` SELECT MAX(col2) FROM mytable INTO @max; UPDATE mytable SET col2 = @max:=@max+1 WHERE id IN (1,2,3,4,5) ORDER BY id; ``` I tested this on MySQL 5.1.30 and it works. I set the `@max` variable first just because I find @Quassnoi's trick of doing it in a Cartesian product to be unnecessary and less readable. Note that MySQL supports `ORDER BY` in an `UPDATE` statement (this is not standard SQL), and you should do this, to ensure the values are updated in the order you want. Otherwise MySQL guarantees no specific order.
SQL : update statement with dynamic column value assignment
[ "", "mysql", "sql", "sql-update", "" ]
In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries. Consider this simplification of my design: ``` class BaseClass { public: BaseClass() {} ~BaseClass() {} bool init() { return doInit(); } bool run() { return doWork(); } void shutdown() { destroy(); } private: virtual bool doInit() = 0; virtual bool doWork() = 0; virtual void destroy() = 0; }; ``` And a class that inherits from it: ``` class LibrarySupportClass : public BaseClass { public: LibrarySupportClass() : BaseClass(), state_manager(new SomeOtherClass()) {} int callbackA(int a, int b); private: virtual bool doInit(); virtual bool doWork(); virtual void destroy(); SomeOtherClass* state_manager; }; // LSC.cpp: bool LibrarySupportClass::doInit() { if (!libraryInit()) return false; // the issue is that I can't do this: libraryCallbackA(&LibrarySupportClass::callbackA); return true; } // ... and so on ``` The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form `int (*)(int, int)`, but the library doesn't support an extra userdata pointer for these callbacks. I would **prefer** doing all of these callbacks within the class because the class carries a state object. What I ended up doing is... ``` static LibrarySupportClass* _inst_ptr = NULL; static int callbackADispatch(int a, int b) { _inst_ptr->callbackA(a, b); } bool LibrarySupportClass::doInit() { _inst_ptr = this; if (!libraryInit()) return false; // the issue is that I can't do this: libraryCallbackA(&callbackADispatch); return true; } ``` This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice. Is there a better way?
You can justify that choice: your justification is that the C library only supports one callback instance. > Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach. Here's how I'd do it. **LibrarySupportClass.h** ``` class LibrarySupportClass : public BaseClass { public: LibrarySupportClass(); ~LibrarySupportClass(); static int static_callbackA(int a, int b); int callbackA(int a, int b); private: //copy and assignment are rivate and not implemented LibrarySupportClass(const LibrarySupportClass&); LibrarySupportClass& operator=(const LibrarySupportClass&); private: static LibrarySupportClass* singleton_instance; }; ``` **LibrarySupportClass.cpp** ``` LibrarySupportClass* LibrarySupportClass::singleton_instance = 0; int LibrarySupportClass::static_callbackA(int a, int b) { if (!singleton_instance) { WHAT? unexpected callback while no instance exists } else { return singleton_instance->callback(a, b); } } LibrarySupportClass::LibrarySupportClass() { if (singleton_instance) { WHAT? unexpected creation of a second concurrent instance throw some kind of exception here } singleton_instance = this; } LibrarySupportClass::~LibrarySupportClass() { singleton_instance = 0; } ``` --- My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy). Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class. Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
The external constraint of the c library dictates that when your callback is called you don't have the identification of the "owning" instance of the callback. Therefore I think that your approach is correct. I would suggest to declare the callbackDispatch method a static member of the class, and make the class itself a singleton (there are lots of examples of how to implement a singleton). This will let you implement similar classes for other libraries.
Reconciling classes, inheritance, and C callbacks
[ "", "c++", "c", "oop", "" ]
Basically what I am trying to do is make my drawing job easier. Back in the days of VB6 there was something called Scalewidth and Scaleheight and I could set them to custom values. Ex. 100. Then when I needed to draw a point at the center of the available space i would just draw it at 50,50. Is there any way in .Net that I can get similar functionality? So that no matter what the size of drawing canvas I get, I can draw on it using absolute co-ordinates.
I don't know if there's a way to achieve this in .NET, but you could easily implement this yourself: ``` // Unscaled coordinates = x, y; canvas size = w, h; // Scaled coordinates = sx, sy; Scalewidth, Scaleheight = sw, sh; x = (sx / sw) * w; y = (sy / sh) * h; // Or the other way round sx = (x / w) * sw; sy = (y / h) * sh; ```
First, why don't you use [Graphics.ScaleTransform](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.scaletransform.aspx) instead of handling all the scaling yourself? Something like: ``` e.Graphics.ScaleTransform( 100.0 / this.ClientSize.Width, 100.0 / this.ClientSize.Height ); ``` Your code will end up much clearer, and I'd bet a beer this would be a little faster. Second, if you stick with your cnvX/rcnvX functions, make sure to use [this.ClientSize.Width](http://msdn.microsoft.com/en-us/library/9278sfx2.aspx) (and the same for height) instead of "this.Width".
.Net equivalent for ScaleHeight and Scalewidth
[ "", "c#", ".net", "gdi+", "drawing", "gdi", "" ]
I wrote a fairly complex method that yield-returns `IEnumerable<string>`, but when I inspected the compiler output in Reflector, I didn't understand a specific part of the compiler-generated implementation of `IEnumerator`: ``` void IDisposable.Dispose() { switch (this.<>1__state) { case 1: case 2: case 3: switch (this.<>1__state) // empty switch! why?! { } break; default: return; try // What?! AFTER return?! { } finally // is the try-finally block anyhow relevant? { this.<>m__Finallya(); } break; } this.<>m__Finally7(); } ``` I'm guessing (or hoping) that Reflector misplaced the closing brace of the outer `switch`, and that it should be directly after the `return`. Still, I don't understand why there is an empty switch in case 3, or why `m__Finallya` is being called in a `finally` block. (Is there a semantic difference between running normally and inside a `finally` block? Other than CER's, which I don't have in my code.) For reference, here is the IL: ``` .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { .override [mscorlib]System.IDisposable::Dispose // Code size 69 (0x45) .maxstack 2 .locals init ([0] int32 CS$0$0000, [1] int32 CS$0$0001) IL_0000: ldarg.0 IL_0001: ldfld int32 FBD.TIP.Reader.MissingMessagesReader/'<GetMissingMessages>d__0'::'<>1__state' IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: sub IL_000a: switch ( IL_001c, IL_001c, IL_001c) IL_001b: ret IL_001c: ldarg.0 IL_001d: ldfld int32 FBD.TIP.Reader.MissingMessagesReader/'<GetMissingMessages>d__0'::'<>1__state' IL_0022: stloc.1 IL_0023: ldloc.1 IL_0024: ldc.i4.2 IL_0025: sub IL_0026: switch ( IL_0035, IL_0035) IL_0033: br.s IL_003e .try { IL_0035: leave.s IL_003e } // end .try finally { IL_0037: ldarg.0 IL_0038: call instance void FBD.TIP.Reader.MissingMessagesReader/'<GetMissingMessages>d__0'::'<>m__Finallya'() IL_003d: endfinally } // end handler IL_003e: ldarg.0 IL_003f: call instance void FBD.TIP.Reader.MissingMessagesReader/'<GetMissingMessages>d__0'::'<>m__Finally7'() IL_0044: ret } // end of method '<GetMissingMessages>d__0'::System.IDisposable.Dispose ```
That is simply reflector struggling to keep up with the IL that has been generated (since iterator blocks don't have to relate to "normal" C# as long as they are valid IL). In particular, the `ret` is after the `finally` block.
You haven't shown what your original iterator block looks like, but my experience of Reflector and compiler-generated code is that it doesn't always manage to decompile entirely accurately, because the compiler uses some IL which doesn't have an equivalent in C#. I've got an [article about iterator block implementation](http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx) which may help you a bit, but I wouldn't worry too much about what the compiled code looks like. In some cases the C# compiler is almost certainly generating unnecessary code on the grounds that that keeps the compiler simpler. Iterator blocks must have been very tricky to get right (it can get very complicated, with finally blocks and iterator disposal) so I think it's reasonable to just trust the JIT to optimise away the unnecessary bits like the switch/case in your generated code.
What does this compiler-generated enumerator mean?
[ "", "c#", ".net", "compiler-construction", "cil", "" ]
In short, I think boxing is an annoyance. Let's look at some alternatives... ``` public class Box<T> where T : struct { public T Value { get; set; } public static implicit operator T(Box<T> box) { return box.Value; } } ``` System.Int32 derives from abstract class System.ValueType which derives from class System.Object. You cannot derive from System.ValueType in C# but I would guess that the struct keyword does exactly that and the CLI recognizes these kind of type definitions as having pass-by-value semantic. Anyhow, when a struct is assigned to type of object boxing occurs. I don't wanna get caught up in boxing per se, instead I wanna get straight to it. I looked at some of the IL generated by the C# compiler. ``` object obj = 1; .locals init ([0] object obj) L_0000: nop L_0001: ldc.i4.1 L_0002: box int32 // Convert a value type (of the type specified in valTypeToken) to a true object reference. L_0007: stloc.0 ``` Found this on MSDN... A value type has two separate representations within the Common Language Infrastructure (CLI): * A 'raw' form used when a value type is embedded within another object or on the stack. * A 'boxed' form, where the data in the value type is wrapped (boxed) into an object so it can exist as an independent entity. This have lead me to conclude that it should be equally expensive to write code like this... ``` var box = obj as Box<int>; if (box != null) { Console.WriteLine(box.Value); } ``` If I intend to pass that same value around as an System.Object do I really wanna unbox and box the ValueType every time? My gut feeling is telling me no, but I cant really find good motivation anyone care to comment on all this blabbering? ## EDIT Anyone ever find themselves doing this? I realize that it might look bizarre but at one point I found myself in a position were I wanted to abstract computations based of several different representations. I did it like this and with lambda expressions. Its not really related to boxing but it sort of allowed me to treat any ValueType (this struct is conveniently 8-byte aligned) as if it were one single type "ReinterpretCast". ``` [StructLayout(LayoutKind.Explicit)] public struct ReinterpretCast { [FieldOffset(0)] sbyte @sbyte; [FieldOffset(0)] byte @byte; [FieldOffset(0)] short @ushort; [FieldOffset(0)] ushort @short; [FieldOffset(0)] int @int; [FieldOffset(0)] uint @uint; [FieldOffset(0)] long @long; [FieldOffset(0)] ulong @ulong; [FieldOffset(0)] float @float; [FieldOffset(0)] double @double; } ```
I'm not entirely sure of your question here. Are you just asking whether your solution is perhaps better than normal boxing? It certainly has some appeal. If you're asking why boxing wasn't implemented this way in the first place, just remember that .NET didn't have generics to start with. EDIT: Boxing is relatively rare with generics anyway. Don't forget that you'll still have to do a runtime cast if a reference to an instance of your type is passed around as `object` (which is usually the case anyway for boxing). Also don't forget interfaces - if a value type implements an interface, so does its corresponding reference type used for boxing. Your solution won't remove that use of boxing, as you can't make your type "pretend" to implement the interface. (You might be able to do something with the DLR, but by that time most of the point has been lost :)
What we think is faster is completely irrelevant. Only the profiler is relevant when considering what is faster.
Boxing, what's your preference and which do you think is faster?
[ "", "c#", "word-wrap", "boxing", "" ]
I already managed to split the CSV file using this regex: "/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/" But I ended up with an array of strings that contain the opening and ending double quotes. Now I need a regex that would strip those strings of the delimiter double quotes. As far as I know the CSV format can encapsulate strings in double quotes, and all the double quotes that are already a part of the string are doubled. For example: My "other" cat becomes "My ""other"" cat" What I basically need is a regex that will replace all sequences of N doublequotes with a sequence of (N/2 - rounded down) double quotes. Or is there a better way ? Thanks in advance.
There is function for reading csv files: [fgetcsv](http://www.php.net/fgetcsv)
Why do you bother splitting the file with regex when there's fgetcsv function that does all the hard work for you? You can pass in the separator and delimiter and it will detect what to do.
Regular expression for parsing CSV in PHP
[ "", "php", "regex", "csv", "" ]
Best way to allow the User to define a Table’s Order? We are using SQL Server 2005 and DevExpress controls. We have a table that contains the following: 1. Process A 2. Process B 3. Process C 4. Report A 5. Report B 6. Report C We want to allow the user to change the order to anything they want. Here is one example: 1. Process C 2. Process A 3. Process B 4. Report B 5. Report A 6. Report C To accommodate this we added a DisplayOrder (INT) field to the table that is maintainted by the our application. Is using an INT field the best solution for a user defined order? Are there any other methods to accomplish this? The reason, I am asking, is in our current application it takes about 1 second to move a row down (or up). I am about to crack open the code to see why it is taking so long and if you Stack Overflow gurus have any good ideas, I might implement them at that time. If you are curious, here is how I believe our application allows editing of the DisplayOrder: 1. Load the table into a GridView 2. Select a row 3. Clicking a Move Down button (there is also a Move Up button) 4. The Click Event will swap DisplayOrder of the current row with the row underneath it. 5. The change, to both of the records, are written back to the database 6. This takes about 1 second per click (i.e. 10 clicks equal 10 seconds)
Could it be taking 1 second per exchange because you are updating the DB with each click? Maybe even reselecting the data again too? Why not select the data into local objects. Bind to those objects in the grid. When you move the objects up and down adjust their display order property. Then only do an update to the DB 1. When the user finally clicks Save. 2. If any of the values of the object have changed.
I would move the saving decision into an explicit Save button for the re-ordering because the user may change their mind and, as Peter Morris suggests, that will get past your performance problem. Further things to consider - explicit Move to Top and Move to Bottom items. I implemented a very successful UI using this kind of approach for user-driven selection of searchable items and reporting items, in an enterprise system. More details of the UI are [available for you to see](http://www.oofile.com.au/adsother/SearchAndReport.html) (be kind, remember it's about 15 years old - back in flat mono days!). One key refinement from a lot of user testing - the sweet spot for saving this order was not per-user or per-company but per-group. Groups were people working together who had a the same starting page (essentially the same root in a massively connected graph). We had about 7 unique groups in the organisation. So, if you go for a per-user or per-group approach, you need to pull the sort data out into a separate table which maps data keys to ordinal integers.
Best way to allow the User to define a Table’s Order?
[ "", ".net", "sql", "sql-server", "vb.net", "devexpress", "" ]
There was an earlier thread on [Java graph or chart library](https://stackoverflow.com/questions/527640/java-graph-or-chart-library), where JFreeChart was found to be quite good, **but**, as [stated in its FAQ](http://www.jfree.org/jfreechart/faq.html#FAQ5), it's not meant for real-time rendering. Can anyone recommend a comparable library that supports real-time rendering? Just some basic xy-rendering - for instance, getting a voltage signal from data acquisition system and plotting it as it comes (time on x-axis, voltage on y-axis).
What the FAQ actually says is that JFreeChart doesn't support hard real-time charting, meaning that the chart isn't updated when new data arrives or at deterministic interval after it. However I have found that JFreeChart can be used for the kind of applications you are describing. You can achieve 1 update per second, which is fine. I don't think a human eye can follow something quicker than this. If you want something more than this, I doubt you will find anything in Java (or even in another language). Operating Systems that we use aren't designed to be real time. You can't have a guaranty that they will respond in a minimum interval after an event. A tight integration with the hardware driver will be needed to show more than 1-10 frames per second. However, if you design your application correctly, the OS will do respond quickly and your application can easily display a "real-time" graph (meaning a graph that updates once a second). Just don't use your application to shut down a valve in an emergency situation!
<http://www.live-graph.org/>
Real-time Java graph / chart library?
[ "", "java", "charts", "graph", "real-time", "" ]
What is the best way to determine if there is a network connection available?
You can check for a network connection in .NET 2.0 using [`GetIsNetworkAvailable()`](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getisnetworkavailable.aspx): ``` System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() ``` To monitor changes in IP address or changes in network availability use the events from the [NetworkChange](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.aspx) class: ``` System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged ```
The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...). Here is a piece of code that checks for these cases: ``` /// <summary> /// Indicates whether any network connection is available /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable() { return IsNetworkAvailable(0); } /// <summary> /// Indicates whether any network connection is available. /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable(long minimumSpeed) { if (!NetworkInterface.GetIsNetworkAvailable()) return false; foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { // discard because of standard reasons if ((ni.OperationalStatus != OperationalStatus.Up) || (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) || (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel)) continue; // this allow to filter modems, serial, etc. // I use 10000000 as a minimum speed for most cases if (ni.Speed < minimumSpeed) continue; // discard virtual cards (virtual box, virtual pc, etc.) if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) || (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0)) continue; // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card. if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase)) continue; return true; } return false; } ```
How do I check for a network connection?
[ "", "c#", "networking", "" ]
Let's say I have two strings: a and b. To compare whether a and be have the same values when case is ignored, I've always used: ``` // (Assume a and b have been verified not to be null) if (a.ToLower() == b.ToLower()) ``` However, using Reflector, I've seen this a few times in the .NET Framework: ``` // (arg three is ignoreCase) if (string.Compare(a, b, true) == 0) ``` I tested which is faster, and the `ToLower()` beat `Compare()` every time with the strings I used. Is there a reason why to `Compare()` instead of `ToLower()`? Something about different `CultureInfo`? I'm scratching my head.
The Remarks section of the [MSDN article](http://msdn.microsoft.com/en-us/library/zkcaxw5y.aspx) should explain things. Essentially, the reason is for compatibility across different cultures settings.
The main thing you should be concerned about isn't performance, it's correctness, and from that aspect the method you *probably* want to be using for a case insensitive comparison is either: ``` string.Compare(a, b, StringComparison.OrdinalIgnoreCase) == 0; ``` or ``` a.Equals(b, StringComparison.OrdinalIgnoreCase) ``` (The first one is useful if you know the strings may be null; the latter is simpler to write if you already know that at least one string is non-null. I've never tested the performance but assume it will be similar.) `Ordinal` or `OrdinalIgnoreCase` are a safe bet unless you know you want to use another comparison method; to get the information needed to make the decision [read this article on MSDN](http://msdn.microsoft.com/en-us/library/ms973919.aspx).
Caselessly comparing strings in C#
[ "", "c#", ".net", "string", "string-comparison", "" ]
I am a .NET Developer with about 5 years of web development experience using Microsoft technologies starting with classic ASP to ASP .NET 3.5. I do have a little background in Java as well and can write/understand Java code very easily. I am looking for resources (online, books) that are compatible with my .NET experience. I am only interested in web development in Java and want to start at intermediate level even if it may require me to look up some details. What path or resources would you recommend for intermediate .NET web developers to gain equivalent proficiency in Java web development tools?
* Get an IDE: IntelliJ (my preference), Eclipse, Netbeans; * Get an application server: Glassfish (my preference; either v2 or v3 Prelude), JBoss or, if you're feeling adventurous, SpringSource dm server; * Get a JDK eg 6u11; * Get a copy of Spring 2.5.6 (or 3.0M2 if you're feeling adventurous); * Get a copy of the Spring reference documentation; Put the pieces together.
Get yourself a copy of eclipse, and just start reading other people's code, and reading some java docs. The Java website has all the docs online, and they're one of the best language specs I've seen. Really, if you know C# pretty well, Java should be a cake walk. The languages are pretty similar, so you just need to get to know the different frameworks.
Java for intermediate .NET Developer
[ "", "java", ".net", "" ]
**Scenario:** I have a Javascript-generated web page that someone else wrote a long time ago that I'd like to pretty up using jQuery. My goal is to clean up the Javascript generated html that someone else produces just by using some jQuery calls against that HTML, after it has been generated. This will be *much* simpler than modifying the other person's Javascript directly, at least for now. My first attempt was to just add in a script tag at the end of the HTML head that invokes the desired jQuery code. ``` <script src="/someone-elses-js-generator.js" /> <script> $(document).ready(function() { alert('the other stuff ran, now do the jquery cleanup'); $('.foobar').css("display","none"); $('.doobar').css("display","inline"); /// ... so on and so forth ... }); </script> ``` **Problem:** The above works just fine, but when I comment out the "alert" message. The jquery no longer performs the cleanup. Apparently, what is happening is that the alert msg box was delaying the run of the subsequent cleanup code, which is great, but without the alert, the jQuery seems to run before the other javascript has finished its output. **Question:** Is there a way to get the jQuery clean-up code to run *after* the js-generator code, but without having to put an alert() box in there?
You can delay your cleanup code upto some extend by using following JavaScript function: ``` setTimeout('JS Cleanup Code', number_of_miliseconds); ```
Perhaps `$(document).ready()` is not the right way to go. How does the other script get triggered? If it's on a `window.onload` then it probably only starts after your jQuery has started. You want to wait until the other script has stopped running. Probably the best way to do this is wrap your jQuery in a function and call it from the other script when you're sure it has finished.
using jQuery after someone else's Javascript
[ "", "javascript", "jquery", "html", "events", "dom", "" ]
I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode). Currently I am setting `FormBorderStyle` to `None` and `WindowState` to `Maximized` which gives me a little more space, but it doesn't cover over the taskbar if it is visible. What do I need to do to use that space as well? For bonus points, is there something I can do to make my `MenuStrip` autohide to give up that space as well?
To the base question, the following will do the trick (hiding the taskbar) ``` private void Form1_Load(object sender, EventArgs e) { this.TopMost = true; this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; } ``` But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.
# A tested and simple solution I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle. Note: I'm using **Windows 8** and my taskbar isn't on auto-hide mode. I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar. ### The code I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method: ``` class FullScreen { public void EnterFullScreenMode(Form targetForm) { targetForm.WindowState = FormWindowState.Normal; targetForm.FormBorderStyle = FormBorderStyle.None; targetForm.WindowState = FormWindowState.Maximized; } public void LeaveFullScreenMode(Form targetForm) { targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; targetForm.WindowState = FormWindowState.Normal; } } ``` ### Usage example ``` private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e) { FullScreen fullScreen = new FullScreen(); if (fullScreenMode == FullScreenMode.No) // FullScreenMode is an enum { fullScreen.EnterFullScreenMode(this); fullScreenMode = FullScreenMode.Yes; } else { fullScreen.LeaveFullScreenMode(this); fullScreenMode = FullScreenMode.No; } } ``` I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: [How to display a Windows Form in full screen on top of the taskbar?](https://stackoverflow.com/questions/2272019/how-to-display-a-windows-form-in-full-screen-on-top-of-the-taskbar))
How do I make a WinForms app go Full Screen
[ "", "c#", ".net", "winforms", "" ]
Is there a way to display the contents from memory directly in a Notepad window?
Double-click on the file, making sure the association is set to Notepad. If you want Notepad to show it without saving it to disk, you can open an instance of Notepad, get the handle for the window, then write the text directly into there. You will need to use Windows User APIs to do this.
I'm assuming that I understand your question. If the file already exists on the machine you can execute the following: ``` System.Diagnostics.Process.Start( "notepad.exe", "[PATH]\[FILE].txt"); ``` If not then save the file locally and then run the above code.
How to Display the Contents from StreamReader directly on Notepad?
[ "", "c#", "streamreader", "notepad", "" ]
I want to achieve the following functionality using LINQ. Case 1: ``` listOfStrings = {"C:","D:","E:"} myString = "C:\Files" Output: True ``` Case 2: ``` listOfStrings = {"C:","D:","E:"} myString = "F:\Files" Output: False ```
``` bool b = listOfStrings.Any(myString.StartsWith); ``` or slightly more verbose (but easier to understand): ``` bool b = listOfStrings.Any(s => myString.StartsWith(s)); ```
Try this: ``` bool contains = listOfStrings.Exists(s => myString.IndexOf(s)!=-1); ``` If you know that it should be at the start of the string, then: ``` bool contains = listOfStrings.Exists(s => myString.StartsWith(s)); ``` **EDIT** Marc's solution is nicer :)
To determine if one of the Strings from a list contains the initial part of a specified string using LINQ
[ "", "c#", "vb.net", "linq", "list", "string", "" ]
``` std::map<std::string, std::string> myMap; std::map<std::string, std::string>::iterator i = m_myMap.find(some_key_string); if(i == m_imagesMap.end()) return NULL; string *p = &i->first; ``` Is the last line valid? I want to store this pointer p somewhere else, will it be valid for the whole program life? But what will happen if I add some more elements to this map (with other unique keys) or remove some other keys, won’t it reallocate this string (key-value pair), so the p will become invalid?
First, maps are guaranteed to be stable; i.e. the iterators are not invalidated by element insertion or deletion (except the element being deleted of course). However, stability of iterator does not guarantee stability of pointers! Although it usually happens that most implementations use pointers - at least at some level - to implement iterators (which means it is quite safe to assume your solution will work), *what you should really store is the iterator itself*. What you could do is create a small object like: ``` struct StringPtrInMap { typedef std::map<string,string>::iterator iterator; StringPtrInMap(iterator i) : it(i) {} const string& operator*() const { return it->first; } const string* operator->() const { return &it->first; } iterator it; } ``` And then store that instead of a string pointer.
Section 23.1.2#8 (associative container requirements): > The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements. So *yes* storing pointers to data members of a map element is guaranteed to be valid, unless you remove *that* element.
std::map, pointer to map key value, is this possible?
[ "", "c++", "stl", "pointers", "dictionary", "" ]
I need to create TCP/IP headers manually for my application. For that i used Raw socket. My system os is win xp (SP3). My code compiles fine :) but it throws a run time error: ``` Initialising Winsock...Initialised successfully. Creating Raw TCP Socket...Raw TCP Socket Created successfully. Setting the socket in RAW mode...Successful. Enter hostname : 192.168.1.152 Resolving Hostname...Resolved. Enter Source IP : 192.168.1.151 Sending packet... Error sending Packet : 10022 ``` I have set IP\_HDRINCL to 1. What am i doing wrong? I switched off the firewall too but still get the same result.
I suggest using [WinPcap](http://www.winpcap.org/) for this purpose. Even when you figure out how to do this properly with the win32 API it is going to be horribly slow. I've used WinPcap successfully to inject packets to a Gigabit ethernet port as fast as the hardware can handle.
Starting with Windows XP SP2, raw sockets are intentionally disabled by Microsoft. * <http://msdn.microsoft.com/en-us/library/ms740548.aspx> * <http://seclists.org/nmap-hackers/2005/0004.html> * <http://www.zdnet.com.au/news/security/soa/Microsoft-tries-to-quell-TCP-IP-danger-/0,130061744,139189876,00.htm>
Raw socket implementation in windows?
[ "", "c++", "sockets", "tcp", "" ]
I want to create a class file dynamically. Here it goes... With the given ResultSet, extracting the metadata I want to build a class file dynamically with getter and setter methods for all the columns that exist in ResultSet. Also I should be able to use this class file generated where ever I want in my later use. Can any body suggest me a better way to implement this. Also if any existing jar files available to implement this, that would be helpful.
Perhaps [Apache Beanutils](http://commons.apache.org/beanutils/) might suit your requirements? See the section on [Dynabeans](http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#dynamic) In particular: > 3.3 ResultSetDynaClass (Wraps ResultSet in DynaBeans) > > A very common use case for DynaBean APIs is to wrap other collections of "stuff" that do not normally present themselves as JavaBeans. One of the most common collections that would be nice to wrap is the java.sql.ResultSet that is returned when you ask a JDBC driver to perform a SQL SELECT statement. Commons BeanUtils offers a standard mechanism for making each row of the result set visible as a DynaBean, which you can utilize as shown in this example: ``` Connection conn = ...; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery ("select account_id, name from customers"); Iterator rows = (new ResultSetDynaClass(rs)).iterator(); while (rows.hasNext()) { DynaBean row = (DynaBean) rows.next(); System.out.println("Account number is " + row.get("account_id") + " and name is " + row.get("name")); } rs.close(); stmt.close(); ``` --- > 3.4 RowSetDynaClass (Disconnected ResultSet as DynaBeans) > > Although ResultSetDynaClass is a very useful technique for representing the results of an SQL query as a series of DynaBeans, an important problem is that the underlying ResultSet must remain open throughout the period of time that the rows are being processed by your application. This hinders the ability to use ResultSetDynaClass as a means of communicating information from the model layer to the view layer in a model-view-controller architecture such as that provided by the Struts Framework, because there is no easy mechanism to assure that the result set is finally closed (and the underlying Connection returned to its connection pool, if you are using one). > > The RowSetDynaClass class represents a different approach to this problem. When you construct such an instance, the underlying data is copied into a set of in-memory DynaBeans that represent the result. The advantage of this technique, of course, is that you can immediately close the ResultSet (and the corresponding Statement), normally before you even process the actual data that was returned. The disadvantage, of course, is that you must pay the performance and memory costs of copying the result data, and the result data must fit entirely into available heap memory. For many environments (particularly in web applications), this tradeoff is usually quite beneficial. > > As an additional benefit, the RowSetDynaClass class is defined to implement java.io.Serializable, so that it (and the DynaBeans that correspond to each row of the result) can be conveniently serialized and deserialized (as long as the underlying column values are also Serializable). Thus, RowSetDynaClass represents a very convenient way to transmit the results of an SQL query to a remote Java-based client application (such as an applet).
The thing is though - from the sounds of your situation, I understand that you want to create this class at runtime, based on the contents of a ResultSet that you just got back from a database query. This is all well and good, and can be done with bytecode manipulation. However, what benefit do you perceive you will get from this? Your other code will not be able to call any methods on this class (because it did not exist when they were compiled), and consequently the only way to actually use this generated class would be either via reflection or via methods on its parent class or implemented interfaces (I'm going to assume it would extend ResultSet). You can do the latter without bytecode weaving (look at [dynamic proxies](http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html) for arbitrary runtime implementations of an interface), and if you're doing the former, I don't see how having a class and mechanically calling the `getFoo` method through reflection is better than just calling `resultSet.getString("foo")` - it will be slower, more clunky *and* less type-safe. So - are you sure you really want to create a class to achieve your goal?
How can I create a class file dynamically?
[ "", "java", "class", "dynamic", "class-design", "javabeans", "" ]
I need to get a list of weeks for a given month, with Monday as the start day. So for example, for the month of February 2009, this method would return: ``` 2/2/2009 2/9/2009 2/16/2009 2/23/2009 ```
``` // Get the weeks in a month DateTime date = DateTime.Today; // first generate all dates in the month of 'date' var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n)); // then filter the only the start of weeks var weekends = from d in dates where d.DayOfWeek == DayOfWeek.Monday select d; ```
``` public static List<DateTime> GetWeeks( this DateTime month, DayOfWeek startOfWeek) { var firstOfMonth = new DateTime(month.Year, month.Month, 1); var daysToAdd = ((Int32)startOfWeek - (Int32)month.DayOfWeek) % 7; var firstStartOfWeek = firstOfMonth.AddDays(daysToAdd); var current = firstStartOfWeek; var weeks = new List<DateTime>(); while (current.Month == month.Month) { weeks.Add(current); current = current.AddDays(7); } return weeks; } ```
C# - What is the best way to get a list of the weeks in a month, given a starting weekday?
[ "", "c#", "datetime", "" ]
In a upcoming project I'm going to write an application in C# which partly has to communicate with a HTTP server. I'm very fond of writing my code TDD-style, and I would just love it if I could mock all of the HTTP requests in my tests. Does any one here know about an easly mockable HTTP client framework? Ps. I usually use Moq for mocks. If you know of some free mocking framework that would be better to mock HTTP requests, that would be nice too.
DotNetOpenId, an open source project from which you may reuse code, uses HTTP wrapper classes through which all calls are made. During testing, a mock HTTP handler is injected so that the responses can be programmatically set before the call is made. It has another mode where it hosts its own ASP.NET site so that the full actual stack can be exercised. This works well, although it hasn't been pulled out as a standalone solution. If you're interested in reusing it, here are some relevant links to the source. And you can ask for help integrating it at dotnetopenid@googlegroups.com. Live one: [StandardWebRequestHandler.cs](http://github.com/AArnott/dotnetopenid/blob/656ef7b1b405d56d986776082a2670c68c415c44/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs) Mocks: [MockHttpRequest.cs](http://github.com/AArnott/dotnetopenid/blob/656ef7b1b405d56d986776082a2670c68c415c44/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs), [TestWebRequestHandler.cs](http://github.com/AArnott/dotnetopenid/blob/656ef7b1b405d56d986776082a2670c68c415c44/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs)
I suggest you use the framework support for this i.e. System.Net.WebRequest. Define a really simple interface, and a simple wrapper for the webrequest. This way you will get what you want, and won't add an external dependency for something the framework already does well.
Easily mockable HTTP client framework for C#
[ "", "c#", "http", "tdd", "mocking", "" ]
I have a C# client and a java server. I have data object that go on the wire back and forth. Lets call them FooData.cs where everything is just a get and a set (no logic) ``` FooData data = new FooData(); data.Price = 10; data.Quantity = 20; ``` i have other derived fields that i want to use in the application but dont need to be sent on the wire so i have anothe class FooWrapper.cs. I inject the data object into the wrapper ``` FooWrapper wrapper = new FooWrapper(Foodata); wrapper.Price = 10; wrapper.Quantity = 20; double total = wrapper.GetTotal(); ``` and the wrapper has a lot of the same properties as the data object (and we just delegate down) or the wrapper also has a number of calculated properties. The only state the wrapper has is the data object (no other member variables) We were having a debate about using this model versus using converters. The converter way would be to instead of having FooWrapper, have a FooBusinessObject and instead of injecting the "on the wire" object, we call a convert method that passes all of the data from the on the wire object to the business object. ``` FooData data = new FooData(); FooBusinessObject busObj = new FooBusinessObject(); busObj.Price = data.Price; busObj.Quant= data.Quantity; double total = busObj.GetTotal(); ``` Any thoughts on what is better (wrapper versus business object / converter)
(edit) What version of C# are you using? With C# 3.0 you could place the "logic" bits (calculations etc) in extension methods in a busines logic assembly, but still see them via the DTO - i.e. (data layer) ``` public class Foo { public int Bar {get;set;} } ``` (business layer) ``` static class FooExt { public static int Blop(this Foo foo) {return 2 * foo.bar;} } ``` (ui layer) ``` Foo foo = ... int blop = foo.Blop(); ``` --- What model are you using to transfer the data? web services? xml? data-contracts? binary? Most would allow you to ignore the extra properties without any extra code (i.e. no need for a wrapper/facade object): `XmlSerializer`: ``` [Serializable] public class MyData { public int Foo {get;set;} // is sent [XmlIgnore] public int Bar {get {...} set {...}} // is ignored } ``` `DataContractSerializer`: ``` [DataContract] class MyData { [DataMember] public int Foo {get;set;} // is sent public int Bar {get {...} set {...}} // is ignored } ``` If you are talking binary, there are portable java/C#-friendly models such as "[protocol buffers](http://code.google.com/p/protobuf/)" - Jon Skeet has a [C# port](http://github.com/jskeet/dotnet-protobufs/tree/master) of the official java version (allowing you to use very similar code on both sides) - or I have a more C#-idiomatic version ([protobuf-net](http://code.google.com/p/protobuf-net/)): `ProtoSerializer`: ``` [ProtoContract] class MyData { [ProtoMember(1)] public int Foo {get;set;} // is sent public int Bar {get {...} set {...}} // is ignored } ```
The way the question is written, the only real difference I can see is whether you pass the fooData instance in through the constructor or call a separate method that constructs it, but implicit in the first method is that the Wrapper object keeps a reference to the original object, whereas in the second approach it seems to me like you avoid this connection. I think the underlying issue is really if you want to keep a reference to the original object. This *may* sometimes be relevant if the original object contains state that you will not be exposing to your application but *could* be necessary to perform updates. If this is not the case then I would try to hide the wire-level objects away from your business logic. Part of the intention of wrapping is to protect your code from the details of the wire-level stuff, and the further up in the stack you let these things seep, the greater the chance they'll be used where not intended, increasing unintentional coupling.
Exposing your core on the wire data model
[ "", "c#", "model", "" ]
just adding a zero like below ``` [assembly: AssemblyVersion("2.03.406.2")] ``` results in 2.3.406.2 which is not what I want. So this may not be possible?
Each portion of the assembly version is stored as a 16-bit integer, so no, it's not possible.
Probably you can read AssemblyFileVersionAttribute ``` AssemblyFileVersionAttribute[] attributes = (AssemblyFileVersionAttribute[])typeof(Program) .Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); Console.WriteLine(attributes[0].Version); ```
How can I set leading zeros in AssemblyVersion like "2.03.406.2" in .net
[ "", "c#", ".net", "versioning", "" ]
Been doing Java for number of years so haven't been tracking C++. Has ***finally*** clause been added to C++ exception handling in the language definition? Is there a favored idiom that mimics Java's try/finally? Am also bothered that C++ doesn't have an ultimate super type for all possible exceptions that could be thrown - like Java's Throwable class. I can write: ``` try { // do something } catch(...) { // alas, can't examine the exception // can only do cleanup code and perhaps rethrow, ala: throw; } ``` **ADDENDUM EDIT:** > I ended up accepting the answer that > had the most up votes, i.e., use > destructors to do cleanup. Of course, > from my own comments, it is clear I > don't entirely agree with that. > However, C++ is what it is and so in > the application endeavor I have in > mind, I'm going to more or less strive > to adhere to common community > practice. I'll use template classes to > wrap resources that don't already have > a class destructor (i.e., C library > resources), thus bestowing on them > destructor semantics. **NEW ADDENDUM EDIT:** > Hmm, instead of ***finally*** then a closure > feature perhaps? A closure combined with > ScopeGuard approach (see one of the > answers below) would be a way to > accomplish cleanup with arbitrary > actions and access to the cleanup > code's outer scope context. Cleanup could be done in the idiom fashion that is seen in Ruby programming where they supply cleanup blocks when a resource is being opened. Isn't a > closure feature being considered for > C++?
By making effective use of destructors. When an exception is thrown in a try block, any object created within it will be destroyed immediately (and hence its destructor called). This is different from Java where you have no idea when an object's finalizer will be called. **UPDATE**: Straight from the horse's mouth: [Why doesn't C++ provide a "finally" construct?](http://www.research.att.com/~bs/bs_faq2.html#finally)
My $.02. I've been programming in managed languages like C# and Java for years, but was forced to make the switch to C++ for the purposes of speed. At first I couldn't believe how I had to write out the method signature twice in the header file and then the cpp file, and I didn't like how there was no finally block, and no garbage collection meant tracking memory leaks everywhere - gosh I didn't like it at all! However, as I said I was forced to use C++. So I was forced to seriously learn it, and now I've finally understood all the programming idioms like RAII and I get all the subtleties of the language and such. It took me a while but now I see just how different of a language it is compared to C# or Java. These days I think C++ is the best language there is! Yes, I can understand that there is a little more what I call 'chaff' sometimes (seemingly unnecessary stuff to write), but after actually using the language seriously, I've changed my mind about it completely. I used to have memory leaks all the time. I used to write all my code into the .h file because I hated the separation of code, I couldn't understand why they would do that! And I used to always end up with stupid cyclic include dependencies, and heaps more. I was really hung up on C# or Java, to me C++ was a huge step down. These days I get it. I almost never have memory leaks, I enjoy the separation of interface and implementation, and I don't have problems with cycle dependencies anymore. And I don't miss the finally block either. To be honest, my opinion is that these C++ programmers that you talk about writing repeated cleanup actions in catch blocks just sound to me like they're just bad C++ programmers. I mean, it doesn't look like any of the other C++ programmers in this thread are having any of the problems you mention. RAII really does make finally redundant, and if anything, it's less work. You write one destructor and then you never have to write another finally ever! Well at least for that type. With respect, what I think is going on is you're just used to Java now, just like I had been.
Is there a favored idiom for mimicing Java's try/finally in C++?
[ "", "c++", "exception", "try-catch", "finally", "throwable", "" ]
I have heard and read that a string can not be changed (immutable?). That should be correct I guess. But I have also heard that two strings with the same contents share the same memory-space (or what you call it). Is this correct? And if so, does that mean that if I create a List with thousands of strings, it wouldn't really take up much space at all if most of those strings were equal to each other?
EDIT: In the answer below I've referred to the intern pool as being AppDomain-specific; I'm pretty sure that's what I've observed before, but the MSDN docs for [String.Intern](http://msdn.microsoft.com/en-us/library/system.string.intern.aspx) suggest that there's a single intern pool for the whole process, making this even more important. **Original answer** (I was going to add this as a comment, but I think it's an important enough point to need an extra answer...) As others have explained, string interning occurs for all string literals, but not on "dynamically created" strings (e.g. those read from a database or file, or built using `StringBuilder` or `String.Format`.) However, I *wouldn't* suggest calling `String.Intern` to get round the latter point: it will populate the intern pool *for the lifetime of your `AppDomain`*. Instead, use a pool which is local to just your usage. Here's an example of such a pool: ``` public class StringPool { private readonly Dictionary<string,string> contents = new Dictionary<string,string>(); public string Add(string item) { string ret; if (!contents.TryGetValue(item, out ret)) { contents[item] = item; ret = item; } return ret; } } ``` You'd then just use something like: ``` string data = pool.Add(ReadItemFromDatabase()); ``` (Note that the pool isn't thread-safe; normal usage wouldn't need it to be.) This way you can throw away your pool as soon as you no longer need it, rather than having a potentially large number of strings in memory forever. You could also make it smarter, implementing an LRU cache or something if you really wanted to. EDIT: Just to clarify why this is better than using `String.Intern`... suppose you read a bunch of strings from a database or log file, process them, and then move onto another task. If you call `String.Intern` on those strings, they will *never* be garbage collected as long as your `AppDomain` is alive - and possibly not even then. If you load several different log files, you'll gradually accumulate strings in your intern pool until you either finish or run out of memory. Instead, I'm suggesting a pattern like this: ``` void ProcessLogFile(string file) { StringPool pool = new StringPool(); // Process the log file using strings in the pool } // The pool can now be garbage collected ``` Here you get the benefit of multiple strings in the same file only existing once in memory (or at least, only getting past gen0 once) but you don't pollute a "global" resource (the intern pool).
This is more or less true. It is called "string interning". String literals will be present in memory only once and every variable set to the same value points to this single representation. Strings that are created in code are not automatically interned though. <http://msmvps.com/blogs/manoj/archive/2004/01/09/1549.aspx>
C#: Strings with same contents
[ "", "c#", "string", "" ]
What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too. An example transformation would be ``` ['a','b',None,'c'] ``` to ``` ['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9'] ``` My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well: ``` def extendChoices(cList): for i in range(0,9): try: if cList[i] is None: cList[i] = "Choice %d"%(i+1) except IndexError: cList.append("Choice %d"%(i+1) ``` and ``` def extendChoices(cList): # Fill in any blank entries for i, v in enumerate(cList): cList[i] = v or "Choice %s" % (i+1) # Extend the list to 9 choices for j in range(len(cList)+1, 10): cList.append("Choice %s" % (j)) ``` I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.
Unlike `zip`, Python's `map` automatically extends shorter sequences with `None`. ``` map(lambda a, b: b if a is None else a, choicesTxt, ['Choice %i' % n for n in range(1, 10)]) ``` You could simplify the lambda to ``` map(lambda a, b: a or b, choicesTxt, ['Choice %i' % n for n in range(1, 10)]) ``` if it's okay to treat other false-like objects in `choicesTxt` the same as `None`.
My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so: ``` for i, v in enumerate(my_list): my_list[i] = v or "Choice %s" % (i+1) for j in range(len(my_list)+1, 10): my_list.append("Choice %s" % (j)) # maybe this is nicer for the extension? while len(my_list) < 10: my_list.append("Choice %s" % (len(my_list)+1)) ``` If you do stick with the `try...except` approach, do catch a specific exception as [Douglas](https://stackoverflow.com/questions/516039/most-pythonic-way-to-extend-a-potentially-incomplete-list/516070#516070) shows. Otherwise, you'll catch **everything**: `KeyboardInterrupts`, `RuntimeErrors`, `SyntaxErrors`, ... . You do not want to do that. **EDIT:** fixed 1-indexed list error - thanks [DNS](https://stackoverflow.com/users/51025/dns)! **EDIT:** added alternative list extension
Most pythonic way to extend a potentially incomplete list
[ "", "python", "" ]
I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring. I came up with a solution combining `exec` and `setattr`, here's a dummy example: ``` class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ ``` Is there a better / safer / more idiomatic way of achieving the same result?
Based on Theran's code, but extending it to methods on classes: ``` class Dynamo(object): pass def add_dynamo(cls,i): def innerdynamo(self): print "in dynamo %d" % i innerdynamo.__doc__ = "docstring for dynamo%d" % i innerdynamo.__name__ = "dynamo%d" % i setattr(cls,innerdynamo.__name__,innerdynamo) for i in range(2): add_dynamo(Dynamo, i) d=Dynamo() d.dynamo0() d.dynamo1() ``` Which should print: ``` in dynamo 0 in dynamo 1 ```
Function docstrings and names are mutable properties. You can do anything you want in the inner function, or even have multiple versions of the inner function that makedynamo() chooses between. No need to build any code out of strings. Here's a snippet out of the interpreter: ``` >>> def makedynamo(i): ... def innerdynamo(): ... print "in dynamo %d" % i ... innerdynamo.__doc__ = "docstring for dynamo%d" % i ... innerdynamo.__name__ = "dynamo%d" % i ... return innerdynamo >>> dynamo10 = makedynamo(10) >>> help(dynamo10) Help on function dynamo10 in module __main__: dynamo10() docstring for dynamo10 ```
Dynamic/runtime method creation (code generation) in Python
[ "", "python", "metaprogramming", "exec", "" ]
I am currently working on a web application that requires certain requests by users to be persisted. I have three choices: 1. Serialize each request object and store it as an xml text file. 2. Serialize the request object and store this xml text in a DB using CLOB. 3. Store the requests in separate tables in the DB. In my opinion I would go for option 2 (storing the serialized objects' xml text in the DB). I would do this because it would be so much easier to read from 1 column and then deserialize the objects to do some processing on them. I am using c# and asp .net MVC to write this application. I am fairly new to software development and would appreciate any help I can get.
The answer for this really depends on the details. What kind of data are storing? How do you need to query it? How often will you need to query it? Generally, I would say it's not a good idea to do both 1 and 2. The problem with option 2 is that you it will be much harder to query for specific fields. If you're going to do a LIKE query and have it search a really long string, it's going to be an expensive operation and you'll likely run into perf issues later on. If you really want to stay away from having to write code to read multiple columns to load your data, look into using an ORM like Linq to SQL. That will help load database tables into objects for you.
Short answer: If option 2 fits your needs well, use it. There's nothing wrong with storing your data in the database.
Is it a good idea to store serialized objects in a Database instead of multiple xml text files?
[ "", "c#", "database-design", "" ]
From MSDN: *[DeflateStream Class](http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx)* DeflateStream cannot be used to compress files larger than 4 GB. Are there any other implementations for .NET without the 4 GB limit? NOTE: I really need to decompress a file in GZ format with content larger than 4 GB. Can any code do that?
Take a look at [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx). Not sure if it's subject to the same limitation, but worth a look.
FYI, we have removed the 4 GB limit from DeflateStream in .NET 4.
DeflateStream 4GB Limit in .NET
[ "", "c#", ".net", "compression", "gzip", "" ]
I'm working on a large collaborative C++ project that is both developed and run on various flavors of Linux, OS X and Windows. We compile across these platforms with GCC, Visual Studio C++ and the Intel C++ compiler. As more and more people start developing code for the project, we're starting to see weird errors in compilation and runtime that are specific to particular compilers on particular operating systems. An example of this is implicit inclusion of headers that certain OS/compiler pairs seem to find for you, accidentally overloading a function from a base class in a derived class. My goal is to make compilation on GCC more strict and catch more errors across all platforms so that we don't keep running into these problems. Here's my list of flags that I'm thinking about trying out for GCC that I've found via Google and the GCC man pages: * [-Wall](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall) * [-Wextra](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra) * -Winit-self * -Wold-style-cast * -Woverloaded-virtual * [-Wuninitialized](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wuninitialized) * -Wmissing-declarations * -Winit-self * [-ansi](https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-ANSI-support) * [-pedantic](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1) What are the other flags that people use to make GCC (and less importantly Visual Studio C++ and the Intel C++ Compiler) obey a stricter standard of the C++ language? Be specific about which compiler and version you're talking about, as some of these might not be implemented in all versions of all compilers.
Beside the pedantic-error that everyone else suggested, IMO, it's always good to run lint as part of your compile process. There are some tools out there: * [cpplint](http://sourceforge.net/projects/cpplint/) (free) * [gimple lint](http://www.gimpel.com/) * [coverity](http://www.coverity.com/) They will save a lot of your time.
You can make pedantic warnings into errors with `-pedantic-errors`. This will prevent developers from ignoring it. For that matter you could make all warnings into errors as well with `-Werror` although that can be counter productive in some cases (maybe not in yours though). Overall, I think, as far as adhering to a strict standard goes, the `-pedantic` options are the most helpful.
Making GCC and other C++ compilers very strict
[ "", "c++", "cross-platform", "compilation", "compiler-warnings", "" ]
I have a servlet which processes a request for a long time. It suppose to keep doing stuff in the loop inside doPost and send data through response's out writer. Effectively that continuously appends data in the clients browser . But the problems accures when client just closes the browser. Inspite of the broken connection the response's writer stream in the servlet never gets closed, thus servlet is unaware of the brocen connection, and keep dumping data into the writer without any errors. How is that posssible? And how do I detect and cancel long request processing in case of browser disconnect? I thougth checkError() on the response writer should do the trick, but it does not seam to work. Any ideas why? This is the servlet code which never stops: ``` protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); System.out.println("Session " + session.getId() + " started"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { while (!out.checkError()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } Date date = new Date(); // TODO append output to the client browser here out.println("....."); System.out.println("Session " + session.getId() + "data sent at: " + date); out.flush(); //break; // _TEST } } finally { System.out.println("Session " + session.getId() + " finished"); out.close(); } } ``` Thanks, Mike
The only real way of dealing with this is to have the browser constantly tell you that it's still there, say every 5-10 seconds. If you go for a minute without hearing anything, you assume the client is gone and forget what you're doing. There are several ways to implement this: * Meta refresh: I don't like this because it's disconcerting and obvious for the user; * An iframe that does that (less obvious); or * Some AJAX technique, which is probably the best option. There's no real way you can detect if the client is still reading what you're sending. It takes time for TCP connections to die and the path to the client is often indirect anyway (through proxies and so forth) so forget about detecting that.
You're trying to do something that is not supported by the HTTP protocol. The whole nature of the Web is based on a request/response. One way to simulate what you need is to use Ajax. The flow would be something like this: 1. Browser sends, using Ajax, a request for items 1 through 10 2. Server process request, build and send response with items from 1 through 10. 3. Browser receives response, parse result, display items from 1 to 10 and repeat step 1, requesting items 11 to 20. This architecture will eliminate the need to check for the "availability" of the client, and also will improve the scalability of your server side components. I hope it helps.
Servlet long processing cancelation when browser closes
[ "", "java", "http", "servlets", "jakarta-ee", "browser", "" ]
I need to implement a Routing Table where there are a number of paramters. For eg, i am stating five attributes in the incoming message below ``` Customer Txn Group Txn Type Sender Priority Target UTI CORP ONEOFF ABC LOW TRG1 UTI GOV ONEOFF ABC LOW TRG2 ``` What is the best way to represent this data in XML so that it can be queried efficiently. I want to store this data in XML and using Java i would load this up in memory and when a message comes in i want to identify the target based on the attributes. Appreciate any inputs. Thanks, Manglu
If you're loading it into memory, it doesn't really matter what form the XML takes - make it the easiest to read or write by hand, I would suggest. When you load it into memory, *then* you should transform it into an appropriate data structure. (The exact nature of the data structure would depend on the exact nature of the requirements.) EDIT: This is to counter the arguments made in comments by Dimitre: I'm not sure whether you thought I was suggesting that people implement their own hashtable - I certainly wasn't. Just keep a straight hashtable or perhaps a [MultiMap](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html) for each column which you want to use as a key. Developers know how to use hashtables. As for the runtime efficiency, which do you think is going to be more efficient: * You build some XSLT (and bear in mind this *is* foreign territory, at least relatively speaking, for most developers) * XSLT engine parses it. This step *may* be avoidable if you're using an XSLT library which lets you just parameterise an existing query. Even so, you've got *some* extra work to do. * XSLT engine hits hashtables (you hope, at least) and returns a node * You convert the node into a more useful data structure Or: * You look up appropriate entries in your hashtable based on the keys you've been given, getting straight to a useful data structure I think I'd trust the second one, personally. Using XSLT here feels like using a screwdriver to bash in a nail...
**Here is a pure XML representation that can be processed very efficiently as is**, without the need to be converted into any other internal data structure: ``` <table> <record Customer="UTI" Txn-Group="CORP" Txn-Type="ONEOFF" Sender="ABC1" Priority="LOW" Target="TRG1"/> <record Customer="UTI" Txn-Group="Gov" Txn-Type="ONEOFF" Sender="ABC2" Priority="LOW" Target="TRG2"/> </table> ``` **There is an extremely efficient way to query data in this format using the [`<xsl:key>`](http://www.w3.org/TR/xslt#key) instruction and the XSLT [key()](http://www.w3.org/TR/xslt#function-key) function**: **This transformation**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes"/> <xsl:key name="kRec" match="record" use="concat(@Customer,'+',@Sender)"/> <xsl:template match="/"> <xsl:copy-of select="key('kRec', 'UTI+ABC2')"/> </xsl:template> </xsl:stylesheet> ``` **when applied on the above XML document produces the desired result**: ``` <record Customer="UTI" Txn-Group="Gov" Txn-Type="ONEOFF" Sender="ABC2" Priority="LOW" Target="TRG2"/> ``` **Do note the following**: 1. **There can be multiple `<xsl:key>`s defined** that identify a record using different combinations of values to be concatenated together (whatever will be considered "keys" and/or "primary keys"). 2. **If an `<xsl:key>` is defined to use the concatenation of "primary keys"** then a unique record (or no record) will be found when the key() function is evaluated. 3. **If an `<xsl:key>` is defined to use the concatenation of "non-primary keys**", then more than one record may be found when the key() function is evaluated. 4. **The `<xsl:key>` instruction is the equivalent of defining an index in a database**. This makes using the key() function **extremely efficient**. 5. **In many cases it is not necessary to convert the above XML form to an intermediary data structure**, due neither to reasons of understandability nor of efficiency.
Storing a 2 dimensional table (decision table) in XML for efficient Query(ies)
[ "", "java", "xml", "" ]
``` declare begin for i in (select * from emp) loop if i.sal=1300 then update emp set sal=13000; end if; end loop; end; ``` This code is updating all the records with salary 13000. Instead i want to update records having salary 1300 to the value 13000. Can you tell where I made a mistake? I am accesing records using implicit cursor.. for every record i am checking the sal value of that record.. if salary value in a particular record is 1500 i want to update it to 15000..
Whenever you can do the update with one single statement, you should do that instead of using a loop. You'll get a very huge performance gain that way; or, the other way round, updates in a loop cost you a lot of performance. If you really really have to use a loop, of course you need a where condition to make sure you are only updating the record you really want to update. A possible way that always works (even if there is no unique key available) is to use the rowid pseudocolumn: ``` begin for i in (select rowid, emp.* from emp) loop if i.sal=1300 then update emp set sal=13000 where rowid=i.rowid; end if; end loop; end; ``` Another possibility would be using an explicit cursor and the "update ... where current of *cursorname*" syntax.
delete that code and just use: ``` update emp set sal = 13000 where sal = 1300 ```
Updating database records in a loop?
[ "", "sql", "plsql", "" ]
I pull data from a table in a database and assign it as a datasource to a listbox. If there is a blank item in the listbox, it shows up as something like this: 1. All 3. Red 4. Green 5. Blue What is the best way to remove the blank in the listbox. If there is a blank, it is always in the second position. I was going to try to test to see if the second position contained blank text, but I am not sure how to do that. Thanks, XaiSoft
I'd say the best thing to do is to remove the blank item from your datasource before you bind it to the listbox. How you do this depends on where your data's coming from and how much control you have over it. You could add a view to the database that only returns non-blank items; if you're using LINQ to SQL you could modify your query so that it only returns non-blank items; you could copy the items into a List and remove the blank ones yourself (I guess there aren't too many items if you're putting them in a listbox).
Hook up an event to the data bind of the list box. If the data item is empty or has an invalid string, then do not add it, else go ahead an add it. Or loop through the data source yourself, and add only what is needed.
Is there a way to clear blank values from a listbox at runtime?
[ "", "c#", "asp.net", "" ]
I have two tables involved in this query I need to create, and I'm not exactly sure how to join these two tables in order to update. I have a ITEM and CONSUMER\_ITEMS table. The ITEM table has a distinct code for each item and a UPC code. I need to concatenate a string with the ITEM.UPC\_CODE to CONSUMER\_ITEMS.NEW\_ITEM\_CODE where CONSUMER\_ITEMS.ITEM\_CODE = (Specific list of ITEM.ITEM\_CODES) How would I go about updating the CONSUMER\_ITEMS.NEW\_ITEM\_CODE Field? It would essentially be equal to 'string' || ITEM.UPC but how do I reference the CONSUMER\_ITEMS.ITEM\_CODE to be equal to the specific ITEM\_CODE in the list of ITEM\_CODES to be updated.
Sounds like you want: ``` UPDATE consumer_items ci SET new_item_code = (SELECT 'string' || item.upc_code FROM item WHERE item.item_code = ci.item_code ) WHERE ci.item_code IN ('a','b','c'); ``` Alternatively, assuming there is a foreign key relationship between the tables and that consumer\_items has a primary key, this should work: ``` UPDATE (SELECT ci.id, ci.new_item_code, item.upc_code FROM consumer_items ci JOIN item ON item.item_code = ci.item_code WHERE ci.item_code IN ('a','b','c') ) v SET v.new_item_code = 'string' || v.upc_code ``` EDIT: Added WHERE clauses
Right, that looks great but the item.item\_code = ci.item\_code doesn't work because: ``` SELECT distinct i.code, i.upc FROM item i, consumer_items ci WHERE i.ccode = '123132' AND i.scode = 'ACTIVE' AND i.upc IS NOT NULL AND ci.item_code = i.code AND i.code IN (SELECT DISTINCT tr.item_code FROM t_r tr WHERE tr.category = 'RRE') AND ci.NEW_ITEM_CODE IS NULL ``` This is the distinct list of CODES and UPC associated with those codes that much be used to update the CONSUMER\_ITEMS. ``` new_item_code = (SELECT 'string' || item.upc_code FROM item WHERE item.item_code = (SELECT distinct i.code, i.upc FROM item i, consumer_items ci WHERE i.ccode = '123132' AND i.scode = 'ACTIVE' AND i.upc IS NOT NULL AND ci.item_code = i.code AND i.code IN (SELECT DISTINCT tr.item_code FROM t_r tr WHERE tr.category = 'RRE') AND ci.NEW_ITEM_CODE IS NULL)); ``` doesn't seem to work
UPDATE using two tables, Concatenation
[ "", "sql", "oracle", "sql-update", "" ]
I'm currently designing a Java application where a Rule engine could be useful. Where is a good place I can learn about how to use them, how they work, how to implement them, see samples, etc.?
The Drools [documentation](http://www.drools.org/learn/documentation.html) includes a lot of useful, general purpose information. Especially chapter 2, which covers rule engine basics, knowledge representation, etc. It also includes a nice recommended reading list for coming up to speed on rule engines and expert systems. For most rule engines, a basic understanding of the [rete](http://en.wikipedia.org/wiki/Rete_algorithm) algorithm usually comes in handy for writing efficient rules. I have personally found the [Doorenbos](http://reports-archive.adm.cs.cmu.edu/anon/1995/CMU-CS-95-113.pdf) paper referenced in the Wikipedia article to be the clearest technical explanation. Also, [here](http://java-source.net/open-source/rule-engines) is a list of open source rule engines in Java.
You might want to read "[Should I use a Rules Engine?](http://martinfowler.com/bliki/RulesEngine.html)" from Martin Fowler's blog. I have worked on a project where we built our own (very simple) rules engine, with the intention to move to a general rule engine when things got too complicated. Never reached that point though, the system has been running happily with the simple homegrown engine for several years now.
Where can I get started learning about Rule Engines?
[ "", "java", "rule-engine", "" ]
Setting the DBIC\_TRACE environment variable to true: ``` BEGIN { $ENV{DBIC_TRACE} = 1 } ``` generates very helpful output, especially showing the SQL query that is being executed, but the SQL query is all on one line. Is there a way to push it through some kinda "sql tidy" routine to format it better, perhaps breaking it up over multiple lines? Failing that, could anyone give me a nudge into where in the code I'd need to hack to add such a hook? And what the best tool is to accept a badly formatted SQL query and push out a nicely formatted one? "nice formatting" in this context simply means better than "all on one line". I'm not particularly fussed about specific styles of formatting queries Thanks!
[As of DBIx::Class 0.08124 it's built in.](http://blog.afoolishmanifesto.com/archives/1444) Just set `$ENV{DBIC_TRACE_PROFILE}` to `console` or `console_monochrome`.
From the documentation of DBIx::Class::Storage > If DBIC\_TRACE is set then trace information is produced (as when the > debug method is set). > > ... > > debug > Causes trace information to be emitted on the debugobj > object. (or STDERR if debugobj has not specifically been set). > > debugobj > Sets or retrieves the object used for metric collection. > Defaults to an instance of DBIx::Class::Storage::Statistics that is > compatible with the original method of using a coderef as a callback. > See the aforementioned Statistics class for more information. In other words, you should set `debugobj` in that class to an object that subclasses [DBIx::Class::Storage::Statistics](http://search.cpan.org/perldoc?DBIx::Class::Storage::Statistics). In your subclass, you can reformat the query the way you want it to be.
Can I pretty-print the DBIC_TRACE output in DBIx::Class?
[ "", "sql", "perl", "formatting", "dbix-class", "" ]
What sync mechanism should I use to give exclusive access to the text file in boost? The file will likely be accessed by threads from only one process.
If you are sure it will only be accessed from one process, a read-write lock with file handles in thread local storage could be a solution. That would simulate the above with only one writer but several readers.
The file locking APIs are generally for inter process locking. If you are in a single process everything in [Boost.Thread package](http://www.boost.org/doc/libs/release/libs/thread/) that suits your needs will do. Outside processes the [Boost.Interprocess](http://www.boost.org/doc/libs/release/libs/interprocess/) should be used. You might want to read the following warning from Boost.Interprocess: ``` Caution: Synchronization limitations ``` If you plan to use file locks just like named mutexes, be careful, because portable file locks have synchronization limitations, mainly because different implementations (POSIX, Windows) offer different guarantees. Interprocess file locks have the following limitations: * It's unspecified if a `file_lock` synchronizes two threads from the same process. * It's unspecified if a process can use two `file_lock` objects pointing to the same file. The first limitation comes mainly from POSIX, since a file handle is a per-process attribute and not a per-thread attribute. This means that if a thread uses a `file_lock` object to lock a file, other threads will see the file as locked. Windows file locking mechanism, on the other hand, offer thread-synchronization guarantees so a thread trying to lock the already locked file, would block. The second limitation comes from the fact that file locking synchronization state is tied with a single file descriptor in Windows. This means that if two file\_lock objects are created pointing to the same file, no synchronization is guaranteed. In POSIX, when two file descriptors are used to lock a file if a descriptor is closed, all file locks set by the calling process are cleared. To sum up, if you plan to use file locking in your processes, use the following restrictions: * For each file, use a single `file_lock` object per process. * Use the same thread to lock and unlock a file. * If you are using a std::fstream/native file handle to write to the file while using file locks on that file, don't close the file before releasing all the locks of the file.
What is an analog for win32 file locking in boost::interprocess?
[ "", "c++", "multithreading", "boost", "ipc", "" ]
Is there a way to find how much memory is used for a particular object? For example a List. Taking everything into account, like string interning and whatever is done by compiler/runtime environment/whatever.
You'd really have to define *exactly* what you meant by "how much memory is used for a particular object". For instance, you could mean "if this object were garbage collected, how much would be freed" - or you could mean "how much memory does this object and everything it touches take up." Your point about string interning is a good example. Suppose you do: ``` List<string> internedStrings = new List<string>(); List<string> nonInternedStrings = new List<string>(); for (int i=0; i < 1000; i++) { string tmp = new string(' ', i+1); nonInternedStrings.Add(tmp); tmp = tmp.Intern(); internedStrings.Add(tmp); } ``` Does `nonInternedStrings` really take up more memory than `internedStrings`? If `internedStrings` were garbage collected, it wouldn't free as much memory - but if `internedStrings` had never been *created* (including not interning each of its elements) then more memory would never have been required. If you can be more specific about *exactly* what you mean, we may be able to help you. It's a complex issue though.
[ANTS Memory Profiler](http://www.red-gate.com/products/ants_memory_profiler/index.htm) profiles the memory consumption of .NET code. I've had great results with it in the past.
C#: Memory usage of an object
[ "", "c#", "memory", "memory-management", "" ]
I'm trying to scale this but I'm a little green when it comes to creating JS functions. I managed to get this far on my own, but alas... When a span gets a value of whatever (in this case, a city name), I want the select box to automatically match it. And I want to scale this by getting rid of all these else if's. ``` $(document).ready(function() { $('select#field1 option').removeAttr('selected'); var whereEvent = $('span#field2').html(); if (whereEvent == 'New York') { $('select#field1 option[value=New York]').attr('selected', 'true'); } else if (whereEvent == 'Los Angeles') { $('select#field1 option[value=Los Angeles]').attr('selected', 'true'); } else if (whereEvent == 'Tokyo') { $('select#field1 option[value=Tokyo]').attr('selected', 'true'); } else if (whereEvent == 'London') { $('select#field1 option[value=London]').attr('selected', 'true'); } else if (whereEvent == 'Sydney') { $('select#field1 option[value=Sydney]').attr('selected', 'true'); } else if (whereEvent == 'Paris') { $('select#field1 option[value=Paris]').attr('selected', 'true'); } }); ``` Can someone help me out here? I promise I'll be grateful for your help. Thank you.
This is an option: ``` $(document).ready(function() { $('select#field1 option').removeAttr('selected'); var whereEvent = $('span#field2').html(); var filter = 'select#field1 option[value=' + whereEvent + ']'; $(filter).attr('selected', 'true'); } ``` Or you could do: ``` $(document).ready(function() { var filter = $('span#field2').html(); $('select#field1 option').each(function(){ this.selected = (this.value == filter); }); } ```
Maybe: ``` $('select#field1 option').removeAttr('selected'); var whereEvent = $('span#field2').html(); $('select#field1 option[value='+whereEvent+']').attr('selected', 'true'); ``` ?
How can I simplify this Javascript function?
[ "", "javascript", "jquery", "" ]
I have a Java program/thread that I want to deploy into an Application Server (GlassFish). The thread should run as a "service" that starts when the Application Server starts and stops when the Application Server closes. How would I go about doing this? It's not really a Session Bean or MDB. It's just a thread.
Check out the *LifecycleListener* interface: <http://glassfish.java.net/nonav/docs/v3/api/index.html?com/sun/appserv/server/LifecycleListener.html> <http://docs.oracle.com/cd/E18930_01/html/821-2418/beamc.html>
I've only done this with Tomcat, but it should work in Glassfish. Create a Listener class that implements [`javax.servlet.ServletContextListener`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContextListener.html), then put it in web.xml. It will be notified when your web app is started and destroyed. A simple Listener class: ``` public class Listener implements javax.servlet.ServletContextListener { MyThread myThread; public void contextInitialized(ServletContextEvent sce) { myThread = new MyThread(); myThread.start(); } public void contextDestroyed(ServletContextEvent sce) { if (myThread != null) { myThread.setStop(true); myThread.interrupt(); } } } ``` This goes in web.xml after your last 'context-param' and before your first 'servlet': ``` <listener> <listener-class>atis.Listener</listener-class> </listener> ``` Don't know whether this kind of thing is recommended or not, but it has worked fine for me in the past.
Threading in an Application Server
[ "", "java", "multithreading", "glassfish", "ejb", "application-server", "" ]
Is there any way (through a extention mechanism?) to get the `Sum()` function to allways return 0. My workaround now is to write like this, but I'm hoping there's a better solution? ``` ((int?)e.CampaignCodes.Sum(f => f.Enquiries.Count()) ?? 0), ```
Your workaround there is a good one. Why don't you write an extension method for IEnumerable similar to Sum called something like SumOrDefault. Then you could just reuse your extension method and you will not have to see the workaround. Your extension method will be very simple and just use the exact code from your workaround.
That's a pretty good way actually. I think the better question is why is it null to begin with? Unless the entity you're invoking the sum on is null, the query should always return 0. It might be a better solution to see whether your entity is valid at the start as opposed to forcing the sum to always return 0 -- Null means there's a problem.
Linq2SQL: Always get .Sum() to return 0 instead of null
[ "", "c#", "linq-to-sql", "null", "" ]
I'm facing a deadlock, my code structure is similar to this: ``` private delegate void UpdateControlDelegate(string value); public void UpdateControl(string value) { if (txtAddress.InvokeRequired) { txtAddress.Invoke(new UpdateControlDelegate(UpdateControl), value); } else { txtAddress.Text = value; // This is in GroupBox1 txtValue.Text = value; // This is in GroupBox2 } } class ThreadHandler { List<string> _list = new List<string>(); object _criticalSection = new object(); public ThreadHandler() { new Thread(new ThreadStart(Run)).Start(); } public static ThreadHandler _threadHandler = null; public static ThreadHandler GetThreadHandler() { if (_threadHandler == null) { _threadHandler = new ThreadHandler(); } return _threadHandler; } public void Run() { while (true) { // some code lock (_criticalSection) { foreach (string str in _list) { // some Code } } // some code Thread.Sleep(SomeTime); } } public void AddItem(string item) { lock (_criticalSection) { _list.Add(item); } } public void RemoveItem(string item) { lock (_criticalSection) { _list.Remove(item); } } } ``` But using the same code, I just modified the UpdateControl method like this: ``` private delegate void UpdateControlDelegate(string value); public void UpdateControl(string value) { if (InvokeRequired) { BeginInvoke(new UpdateControlDelegate(UpdateControl), value); } else { txtAddress.Text = value; // This is in GroupBox1 txtValue.Text = value; // This is in GroupBox2 } } ``` This is working fine. What is the problem?
The problem is almost certainly that you're acquiring the lock within a background thread, then calling `Control.Invoke`, and invoking a delegate (on the UI thread) which tries to acquire the same lock. It can't do that, because the other thread holds the lock - and will keep holding the lock while it waits for the UI operation to complete. Admittedly there's no locking within the UpdateControl method you've posted, but I suspect that's not the complete code - and you haven't shown where you're using `AddItem` or `RemoveItem`. I note that GetThreadHandler() isn't thread-safe, by the way - that looks like a bug to me...
Are you calling AddItem and RemoveItem from the main thread while calling UpdateControl from the worker thread? That will cause deadlocks.
Deadlocking lock() method
[ "", "c#", "locking", "deadlock", "" ]
I am not sure whether I am missing something basic. But I am unable to understand why the compiler is generating the error for this code: ``` class A { }; class B { public: B(); A* get() const; private: A* m_p; }; B::B() { m_p = new A; } A* B::get() const { //This is compiling fine return m_p; } class C { public: A* get() const; private: A m_a; }; A* C::get() const { //Compiler generates an error for this. Why? return &m_a; } ``` EDIT: The compiler error is : error C2440: 'return' : cannot convert from 'const class A \*' to 'class A \*' Conversion loses qualifiers
`const` in the function signature tells the compiler that the object's members may not be modified. Yet you return a non-`const` pointer to a member, thus allowing a violation of that promise. In your class `B`, you make/break no promise since you don't return a pointer to a member, you return a copy of it (and the member happens to be a pointer).
It's because you're returning a non-const pointer to a member from a const function. The first part works because you're returning a *copy* of a member pointer, so this doesn't violate the const-ness of the get function: ``` class B { public: B(); A* get() const; private: A* m_p; }; A* B::get() const { //This is compiling fine return m_p; } ``` But the next bit generates the compile error (on gcc 4) > testfile.cpp:37: error: invalid conversion from ‘const A\*’ to ‘A\*’ Because your const get function is providing non-const acess to m\_a by returning a non-const pointer to it. ``` class C { public: A* get() const; private: A m_a; }; A* C::get() const { //Compiler generates an error for this. Why? return &m_a; } ```
Compiler Error with const function
[ "", "c++", "constants", "" ]
References in C# are quite similar to those on C++, except that they are garbage collected. Why is it then so difficult for the C# compiler to support the following: 1. Members functions marked `const`. 2. References to data types (other than string) marked `const`, through which only `const` member functions can be called ? I believe it would be really useful if C# supported this. For one, it'll really help the seemingly widespread gay abandon with which C# programmers return naked references to private data (at least that's what I've seen at my workplace). Or is there already something equivalent in C# which I'm missing? (I know about the `readonly` and `const` keywords, but they don't really serve the above purpose)
I suspect there are some practical reasons, and some theoretical reasons: * Should the constness apply to the *object* or the *reference*? If it's in the reference, should this be compile-time only, or as a bit within the reference itself? Can something else which has a non-const reference to the same object fiddle with it under the hood? * Would you want to be able to cast it away as you can in C++? That doesn't sound very much like something you'd want on a managed platform... but what about all those times where it makes sense in C++? * Syntax gets tricky (IMO) when you have more than one type involved in a declaration - think arrays, generics etc. It can become hard to work out exactly which bit is const. * If you can't cast it away, *everyone has to get it right*. In other words, both the .NET framework types and any other 3rd party libraries you use all have to do the right thing, or you're left with nasty situations where your code can't do the right thing because of a subtle problem with constness. There's a big one in terms of why it can't be supported *now* though: * Backwards compatibility: there's no way all libraries would be correctly migrated to it, making it pretty much useless :( I agree it would be useful to have some sort of constness indicator, but I can't see it happening, I'm afraid. EDIT: There's been an argument about this raging in the Java community for ages. There's rather a lot of commentary on the [relevant bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=4211070) which you may find interesting.
As Jon already covered (of course) const correctness is not as simple as it might appear. C++ does it one way. D does it another (arguably more correct/ useful) way. C# flirts with it but doesn't do anything more daring, as you have discovered (and likely never well, as Jon well covered again). That said, I believe that many of Jon's "theoretical reasons" are resolved in D's model. In D (2.0), const works much like C++, except that it is fully transitive (so const applied to a pointer would apply to the object pointed to, any members of that object, any pointers that object had, objects they pointed to etc) - but it is explicit that this *only* applies from the variable that you have declared const (so if you already have a non-const object and you take a const pointer to it, the non-const variable can still mutate the state). D introduces another keyword - invariant - which applies to the object itself. This means that nothing can ever change the state once initialised. The beauty of this arrangement is that a const method can accept both const and invariant objects. Since invariant objects are the bread and butter of the functional world, and const method can be marked as "pure" in the functional sense - even though it may be used with mutable objects. Getting back on track - I think it's the case that we're only now (latter half of the naughties) understanding how best to use const (and invariant). .Net was originally defined when things were more hazy, so didn't commit to too much - and now it's too late to retrofit. I'd love to see a port of D run on the .Net VM, though :-)
Why doesn't C# offer constness akin to C++?
[ "", "c#", "compiler-construction", "reference", "constants", "" ]
As the topic says I'm very new to c++, but I have some experience with java. To start learning c++ I had the (not very original) idea of making a simple command line calculator. What I'm trying to do is store the numbers and operators in a binary tree. ``` #include <iostream> using namespace std; class Node { bool leaf; double num; char oper; Node* pLNode; Node* pRNode; public: Node(double n) { num = n; leaf = true; pLNode = 0; pRNode = 0; } Node(char o, Node lNode, Node rNode) { oper = o; pLNode = &lNode; pRNode = &rNode; leaf = false; } bool isLeaf() { return leaf; } double getNumber() { return num; } char getOperator() { return oper; } Node* getLeftNodePointer() { return pLNode; } Node* getRightNodePointer() { return pRNode; } //debug function void dump() { cout << endl << "**** Node Dump ****" << endl; cout << "oper: " << oper << endl; cout << "num: " << num << endl; cout << "leaf: " << leaf << endl; cout << "*******************" << endl << endl; } }; class CalcTree { Node* pRootNode; Node* pCurrentNode; public: Node* getRootNodePointer() { return pRootNode; } Node* getCurrentNodePointer() { return pCurrentNode; } void setRootNode(Node node) { pRootNode = &node; } void setCurrentNode(Node node) { pCurrentNode = &node; } double calculateTree() { return calculateTree(pRootNode); } private: double calculateTree(Node* nodePointer) { if(nodePointer->isLeaf()) { return nodePointer->getNumber(); } else { Node* leftNodePointer = nodePointer->getLeftNodePointer(); Node* rightNodePointer = nodePointer->getRightNodePointer(); char oper = nodePointer->getOperator(); if(oper == '+') { return calculateTree(leftNodePointer) + calculateTree(rightNodePointer); } else if(oper == '-') { return calculateTree(leftNodePointer) - calculateTree(rightNodePointer); } else if(oper == '*') { return calculateTree(leftNodePointer) * calculateTree(rightNodePointer); } else if(oper == '/') { return calculateTree(leftNodePointer) / calculateTree(rightNodePointer); } } } }; int main(int argc, char* argv[]) { CalcTree tree; tree.setRootNode(Node('+', Node(1), Node(534))); cout << tree.calculateTree() << endl; return 0; } ``` I've got a couple of questions about this code: 1. This compiles but does not do what's intended. It seems that after tree.setRootNode(Node('+', Node(1), Node(534))); in main, the rightnode is initialized properly but the leftnode isn't. Compiling and running this prints out 534 for me (gcc, freebsd). What is wrong here? 2. It seems in c++ people prefer to define members of a class outside the class, like class A { public: void member(); }; A :: member(){std::cout << "Hello world" << std::endl;} why is that? 3. I'd very much like some pointers on c++ conventions (naming, indenting etc.) 4. I'm used to coding java with eclipse. Atm I'm using emacs for learning c++. Can someone advise me on a good (free) c++ ide, or should I stfu and stick with emacs like a real man? :)
First, i recommend you a good book too. There are very good SO threads about C++ books, like [The definitive C++ book guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). In the following, you find i tell you how to solve some problems, but i don't delve into details, because i think that's what a book can do much better. I've glanced over the code, here is what i've figured: ``` Node(char o, Node lNode, Node rNode) { oper = o; pLNode = &lNode; pRNode = &rNode; leaf = false; } ``` That constructor has 3 parameters, all of which are local to the function. When the function returns, the parameters do not exist anymore, and their memory occupied by them is cleaned up automatically. But you store their addresses into the pointers. That will fail then. What you want is passing pointers. By the way always use constructor initializer lists: ``` Node(char o, Node *lNode, Node *rNode) :oper(o), pLNode(lNode), pRNode(rNode), leaf(false) { } ``` Creating the tree now does look different: ``` CalcTree tree; tree.setRootNode(new Node('+', new Node(1), new Node(534))); cout << tree.calculateTree() << endl; ``` New creates a dynamic object and returns a pointer to it. The pointer must not be lost - otherwise you have a memory-leak because you can't delete the object anymore. Now, make sure you delete child nodes ordinarily by creating a destructor for Node (put it as you would put any other member function): ``` ~Node() { delete pLNode; delete pRNode; } ``` Here you see it's important to always null-ify pointers: delete on a null pointer will do nothing. To start cleaning-up, you create a CalcTree destructor too, which starts the delete chain: ``` ~CalcTree() { delete pRootNode; } ``` Don't forget to create a default constructor for CalcTree that initializes that pointer to 0! Now, you have one remaining problem: If you copy your object, the original object and the copy share the same pointer, and when the second object (the copy) goes out of scope, it will call delete on the pointer a second time, thus deleting the same object twice. That's unfortunate. It can be solved by forbidding copying your classes - or by using smart pointers that have shared ownership semantics (look into **shared\_ptr**). A third variant is to write your own copy constructor and copy assignment operator. Well, here is how you would disable copy constructor and copy assignment operators. Once you try to copy, you will get a compile error. Put this into Node: ``` private: Node(Node const&); Node& operator=(Node const&); ``` The same for CalcTree, and you are protected from that subtle bug now. Now, onto your other questions: ### It seems in c++ people prefer to define members of a class outside the class That is because the more code you add to the header, the more you have to include into your header from other files (because your code depends on something that's defined in them). Note that all other files that include that header then will transitively include the headers that one includes too. So you will in the end have less indirectly included headers when you put your code into separately compiled files instead. Another problem that is solved are cyclic references. Sometimes, you have to write a method that needs to have access to something defined later in the header. Since C++ is a single-pass language, the compiler can't resolve references to symbols that are declared after the point of use - generally. ### I'd very much like some pointers on c++ conventions That's very subjective, but i like this convention: * Class data-members are written like *`mDataMember`* * Function are written like *`getDataMember`* * Local variables are written like *`localVariable`* * Indenting with spaces, 4 spaces each (uh oh, *this* one is controversial. There are many possible ways to indent, please do not ask for the best one!) ### I'm used to coding java with eclipse. Atm I'm using emacs for learning c++. I'm using emacs for my C++ development, and eclipse for Java. Some use eclipse for Java too (there is a package called CDT for eclipse C++ development). It seems to be quite common gist (i agree) that Visual C++ on windows is the best IDE you get for windows. There are also some answers on SO regarding this: [Best IDE for C++](https://stackoverflow.com/questions/93326/which-ide-is-best-for-c) (best search with google in stackoverflow, it will give you much more results than the builtin search).
* First, I can only recommend to have a look at the book "Accelerated C++". It will jump-start you into **STL**, and C++ **style**, and can save you a year of bad experiences. (There is quite an amount of extraordinary well written literature on C++ out there, if you decide to go deeper). * C++ does not use automatic memory management on the heap. You are storing pointers to temporaries. Your program is incorrect as it tries to access destructed objects. Like it or not, you'll have to learn on object lifetime first. You can simplify a good part of this in simple cases by using value semantics (not storing pointers, but storing a copy of the object). * Eclipse/CDT is reported to be quite OK on linux. On Windows you'll do easier with Microsoft Visual C++ Express Edition. When you've gotten into the basics, switching later will be no problem for you. * Defining members outside of the class itself is preferred as we usually split header and implementation files. In the header you try not to expose any unnecessary information, and also to reduce code-size, it's a simple matter of compile **time**. But for many modern programming techniques (like using template meta-programming) this cannot be used, so quite some C++ code moves in the direction of inline definitions.
Making the leap from Java to C++
[ "", "c++", "" ]
How do you add a destructor to a custom made class made in C# so as to destroy it when it's not needed anymore?
Read [this](http://msdn.microsoft.com/en-us/library/system.object.finalize(VS.71).aspx). But you might consider implementing IDisposable which usually offers a more elegant solution. Go [here](http://www.devx.com/dotnet/Article/33167) for more info.
Don't use a destructor. Use Dispose() and Finalize() instead. This is a quite good article on this subject: [When and How to Use Dispose and Finalize in C#](http://www.devx.com/dotnet/Article/33167 " When and How to Use Dispose and Finalize in C#")
C#: How do you add a destructor to a custom made class?
[ "", "c#", "" ]
``` function DeleteData(ID) { var ctrlId=ID.id; var divcontents=document.getElementById(ctrlId).innerHTML; var tabid=ctrlId.replace(/div/,'tab'); var tabcontents=document.getElementById(tabid).innerHTML; alert(document.getElementById(tabid).innerHTML); document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>"; document.getElementById(ctrlId).innerHTML=''; } ``` I am trying to replace the Table with empty table but ``` document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>"; ``` this line is causing `Unknown Runtime Error`
You can't set value to a table's innerHTML, you should access to child cells or rows and change them like that : ``` document.getElementById(tabid).rows[0].cells.innerHTML = 'blah blah'; ``` For more info/example : [Table, TableHeader, TableRow, TableData Objects](http://www.w3schools.com/JS/js_examples_3.asp)
In IE8, you cannot change the innerHTML of an object when the code that attempts that is fired from within the object. For example: ``` <span id='n1'> <input type=button value='test' onclick='DoSomething(this);'> </span> ``` with the following code tucked in some remote corner of your document: ``` <script type='text/javascript'> function DoSomething(element) { document.getElementById("n1").innerHTML = "This is a test" } </script> ``` This will fail with the error unknown runtime error. I believe it has to do with the fact that you're trying to replace the HTML code which fired the current line of execution. The onclick event is part of the code being replaced by the DoSomething function. IE8 doesn't like that. I resolved my issue by setting a timer event for 250 milliseconds, such that the function called at the end of the 250 milliseconds replaces the span's innerHTML.
Debugging IE8 Javascript Replace innerHTML Runtime Error
[ "", "javascript", "debugging", "innerhtml", "" ]
These days I have learned some basic usage of C#. I think that because C# is often used in application programming ,we should practice the language in an engineering way rather than solving some algorithmic problems. But what is the best way to practice C# if I cannot find any projects related to the language in the work.
I think you can try start with personal small utilities. For example, write a file backuper, personal asp.net blog site, password reminder, time tracker, etc.. the product will be used by you, so you will get exceptions or performance problems so you will be learning more..
You could also check out [AntMe](http://www.antme.net), it is a simulation of ants which you program in C#.
How to practice a language like C#?
[ "", "c#", "programming-languages", "" ]
I have noticed two different approaches to writing out data to an XML file (error handling omitted for brevity). The first method has you build the XML document and then simply save the XML to a file: ``` using (XmlWriter writer = XmlWriter.Create(fileName)) { writer.WriteStartDocument(true); writer.WriteStartElement("parentelement"); writer.WriteEndElement(); writer.WriteEndDocument(); } ``` The second method has you create a MemoryStream, and then save the MemoryStream to a file: ``` XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; MemoryStream ms = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(ms, settings)) { writer.WriteStartDocument(true); writer.WriteStartElement("parentelement"); writer.WriteEndElement(); writer.WriteEndDocument(); } using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write)) { ms.WriteTo(fs); ms.Dispose(); } ``` I'm guessing the logic for using a MemoryStream is to ensure the XML file can be built before trying to save the file. Would the the MemoryStream method provide for an Atomic write event and/or protect against write issues while you are adding entries into the XML file? Can anyone explain if this is actually necessary or just an overkill way to add unnecessary lines of code to my project?
The `MemoryStream` version is wasteful on this occasion. `MemoryStream` is useful if you want to perform `Stream`-like work, but don't want an actual file. If you **are** writing a file, then just write to the file. This avoids the need to buffer all the data in memory.
It is true that the memory stream approach is wasteful for simple operations but it is very useful for cases such as saving the xml as encrypted file, as compressed file etc.
Using MemoryStream to write out to XML
[ "", "c#", "xml", "memorystream", "" ]
I have an array: ``` $array = array("apple", "banana", "cap", "dog", etc..) up to 80 values. ``` and a string variable: ``` $str = "abc"; ``` If I want to check whether this string (`$str`) exists in the array or not, I use the `preg_match` function, which is like this: ``` $isExists = preg_match("/$str/", $array); if ($isExists) { echo "It exists"; } else { echo "It does not exist"; } ``` Is it the correct way? If the array grows bigger, will it be very slow? Is there any other method? I am trying to scaling down my database traffic. And if I have two or more strings to compare, how can I do that?
``` bool in_array ( mixed $needle , array $haystack [, bool $strict ] ) ``` <http://php.net/manual/en/function.in-array.php>
If you just need an exact match, use [in\_array](http://php.net/in_array)($str, $array) - it will be faster. Another approach would be to use an associative array with your strings as the key, which should be logarithmically faster. Doubt you'll see a huge difference between that and the linear search approach with just 80 elements though. If you *do* need a pattern match, then you'll need to loop over the array elements to use preg\_match. --- You edited the question to ask "what if you want to check for several strings?" - you'll need to loop over those strings, but you can stop as soon as you don't get a match... ``` $find=array("foo", "bar"); $found=count($find)>0; //ensure found is initialised as false when no terms foreach($find as $term) { if(!in_array($term, $array)) { $found=false; break; } } ```
How to find a string in an array in PHP?
[ "", "php", "arrays", "" ]
Mind you, I am using master pages, but can I locate a div within the page and throw some html in there? Thanks.
You can add a div with runat="server" to the page: ``` <div runat="server" id="myDiv"> </div> ``` and then set its InnerHtml property from the code-behind: ``` myDiv.InnerHtml = "your html here"; ``` If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this: ``` <script type="text/javascript"> Sys.Application.add_load(MyLoad); function MyLoad(sender) { $get('<%= div.ClientID %>').innerHTML += " - text added on client"; } </script> ```
Use `asp:Panel` for that. It translates into a div.
Can I dynamically add HTML within a div tag from C# on load event?
[ "", "c#", "asp.net", ".net-3.5", "master-pages", "" ]
I'm using CodeIgniter, and will likely use their template library as I want to keep things extremely simple to use. The content for the template variables will come from the database, but I want the business admins to know what content areas are available. Basically the names of the parameters when they choose a specific template. For instance, Joomla uses an extra XML file that defines each area, whereas Wordpress uses comments within a page template to inform the system that the PHP file is a template. I like the Joomla approach because you don't have to parse the PHP file to find the areas, but I like the Wordpress approach because you don't have an extra XML file associated with every template. Are there other approaches that I'm missing?
I think the nicest way would be to add a small hack to the template parser class. The code looks quite readable and clean in system/libraries/Parser.php. You could insert a hook in that class that can be used to keep track of the variables. I don't know, if it works, but here's a snippet: ``` class CI_Parser { var $varCallback; function setVarCallback($callbackFunction) { $this->varCallback = $callbackFunction; } ... function _parse_single(...) { $callback = $this->varCallback; $callback($key); } ... //Somewhere in your code function storeVarName($variableName) { // Persist the variable name wherever you want here } $this->parser->setVarCallback('storeVarName'); ```
You could do this directly in the controller: ``` // in the controller print_r($data); $this->load->view("main", $data); ``` Or a little more rudimentary, but you could pass to the template a PHP `array` of variables (or an `object`): ``` // in the controller $data = array(); $data["namespace"] = array( "title" => "My website", "posts" => array("hi", "something else") ); $this->load->view("main", $data); ``` And then in the view, have a flag to `print_r` the `namespace` to show all the vars available, so that business admins know exactly what to use. ``` // in the view if(isset($namespace["showAllVars"])) print_r($namespace); ```
Templates in PHP, and the best way to notify the application that one exists?
[ "", "php", "templates", "codeigniter", "" ]
How would I test a property of a type to see if it is a specified type? EDIT: My goal is to examine an assembly to see if any of the types in that assembly contain properties that are MyType (or inherited from MyType). Here is the track I've gone down... ``` AssemblyName n = new AssemblyName(); n.CodeBase = "file://" + dllName; Assembly a = AppDomain.CurrentDomain.Load(n); foreach (Type t in a.GetTypes()) foreach (PropertyInfo pi in t.GetProperties()) if ( pi.PropertyType is MyType ) // warning CS0184 Console.WriteLine("Found a property that is MyType"); ``` This compiles with warning CS0184: The given expression is never of the provided ('MyType') type
What type are you interested in? The return type of the method/property/event etc? If so, I don't think there's anything in `MemberInfo` to let you get at it directly - you'll need to cast and use `MethodInfo.ReturnType`, `PropertyInfo.PropertyType`, `FieldInfo.FieldType`, `EventInfo.EventHandlerType` and any others I've forgotten. (Remember that types themselves can be members. Not sure what you'll want to do with them!) EDIT: If you're interested in whether a specific Type represents either MyType or some subclass, then use [Type.IsAssignableFrom](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx): ``` if (typeof(MyType).IsAssignableFrom(type)) ``` EDIT: Now that we know you want properties, it's easy - use GetProperties instead of GetMembers. I like doing reflection with LINQ: ``` var query = from type in assembly.GetTypes() from property in type.GetProperties() where typeof(MyType).IsAssignableFrom(property.PropertyType) select new { Type=type, Property=property }; foreach (var entry in query) { Console.WriteLine(entry); } ``` If you're not a fan of LINQ: ``` foreach (Type t in a.GetTypes()) foreach (PropertyInfo pi in t.GetProperties()) if (typeof(MyType).IsAssignableFrom(pi.PropertyType)) Console.WriteLine("Found a property that is MyType"); ``` Note that you might want to specify binding flags to get non-public properties etc.
Ok, maybe I'm missing something stupid, but shouldn't it be: ``` if ( pi.PropertyType == typeof(MyType )) ``` ???
How can I determine property types using reflection?
[ "", "c#", ".net", "reflection", "" ]
One of the ncie things about PHP is that if you do an include/require it works off the directory where the file is (or rather the URI of the request). That means that if you want to include further file you don't need to know from where the original script is running. All you need to know is where the current script is. Now I want to load a text file and process it. file\_get\_contents() seems an obvioius way of loading it. The problem is I don't have that same luxury. I either need to specify the file path absolutely, which I don't want to do, or I have to know the location relative to the file that initiated the call, which I don't like either. Require/include don't seem to work with non-PHP files and that would essentially echo the contents anyway (yes I know I could wrap that in an ob\_start(), etc). Suggestions?
You can get the directory associated with the current file using ``` dirname(__FILE__) ``` So you could do something like this: ``` file_get_contents(dirname(__FILE__) . '/foo.txt') ```
Define a constant with your desired path to the file, wherever you'd normally put configuration settings. Keeps it simple and customizable.
Loading a file in PHP without knowing the underlying file system
[ "", "php", "" ]
I wonder if there is some neat way to intercept xml request send during java webservice method invocation and xml given in response? I don't want to print those xmls to standard output but to "catch" them in some string.
Yes, normally you use a soap proxy like [soapUI](http://www.soapui.org/). Simply point your webservice client at the proxy and the proxy at the real service.
Fiddler or SoapUI will let you see and even CHANGE the request/response in route.
How to intercept xml response and request during web service invocation?
[ "", "java", "jaxb", "jax-ws", "" ]
I'm writing a javascript function and in "compact" javascript design fashion, the type/length of arguments changes the behaviour of the function. One possible type of the argument is a jQuery object, for which I would like very special logic. What is the best way to test if an object is an instance of jQuery?
Depends on the inner workings of jQuery, but I'd go with ``` obj instanceof jQuery ``` It's the most 'JavaScript way' of doing it. Keep in mind that it will fail when passing objects between window/frame boundaries! Tomalak's suggestion ``` 'jquery' in obj ``` should still work in this case, so you should use it if you expect to do multi-window data exchange. I wouldn't recommend it as a general solution, as just looking for a property named `'jquery'` isn't very reliable. The `in` operator will also throw an error if `obj` is a primitive. If this behaviour is undesired, you might consider using one of these tests instead: ``` obj && obj.jquery 'jquery' in Object(obj) ``` I find the second one more appealing, but the first one will likely be faster. Checking ``` Object(obj).hasOwnProperty('jquery') ``` will fail, as jQuery objects only inherit the property from their prototype. I'd also discourage using the `constructor` property for type checking in JavaScript - it might work reliably for jQuery, but as `constructor` is just a property of the object pointed to by the constructor function's `prototype` property at instantiation time, there are lots of ways to mess with such tests... --- As a side note: jQuery itself checks for `obj && obj.jquery`. It does not use `instanceof` even once. Instead, it uses a combination of `typeof`, duck-typing and `toString.call()` for type checking, which should work where `instanceof` will fail. Also, `hasOwnProperty()` is never used as well. I'm not sure what this says about the code quality of the jQuery library ;)
One of the following: ``` obj instanceof jQuery obj && obj.constructor == jQuery obj && obj.jquery ``` instanceof [is recommended](http://markmail.org/message/62a7ximsf7txfhb3)
What's the correct/proper way to test if an object is a jQuery object in javascript?
[ "", "javascript", "jquery", "scripting", "" ]
I have a case in which I have to read an input file in the C'tor, but sometimes this file doesn't exist. This object is usually held statically, so its C'tor is called while loading the dll. I can't catch the exception I throw if the file doesn't exist because it's too early, and my executable crashes in an ugly way. I know it's bad practice to throw exceptions out of a C'tor, but I can't go on if the file doesn't exist, so I have to. Is there a way to catch the exception while loading the dll, and if not, is there any better solution for this scenario? Thanks, Gal
I assume the static object has the file scope (it is outside any function/class definition). You may consider moving it to an accessor function and accessing it only via that function, like this: ``` class Object; Object& getObject() { static Object object; return object; } ``` The static instance of *Object* will be initialized upon the first calling of the *getObject()* method. If the *Object*'s constructor throws, you can easily catch the exception. Just you need to remember wrapping every call of *getObject()* into a try/catch block (or suffer from the exception bubbling up the stack chain); that may be a bit inconvenient, but on the other hand you may decide to wrap just the logically "first" call, if you know which one it is in the program logic flow.
Throwing exceptions out of a constructor is not necessarily a bad practice. In fact, RAII usually requires you to do this sort of things, because objects have an internal invariant that must be satisfied, and if the constructor can't initialize the object and leave it in a valid state, then it's the only way to go. Throwing exceptions from a destructor, on the other hand, **is** a bad practice (and also a dangerous one). But throwing them from a constructor should be OK.
Throwing/catching exceptions from C'tor of a static object in C++
[ "", "c++", "exception", "dll", "static", "constructor", "" ]
What is the best way to stop bots, malicious users, etc. from executing php scripts too fast? Is it ok if I use the `usleep()` or `sleep()` functions to simply do "nothing" for a while (just before the desired code executes), or is that plain stupid and there are better ways for this? Example: ``` function login() { //enter login code here } function logout() { //enter logout code here } ``` If I just put, say, `usleep(3000000)` before the login and logout codes, is that ok, or are there better, wiser ways of achieving what I want to achieve? **edit:** Based on the suggestions below, does then `usleep` or `sleep` only cause the processor to disengage from the current script being executed by the current user, or does it cause it to disengage from the entire service? i.e. If one user+script invokes a `sleep`/`usleep`, will all concurrent users+scripts be delayed too?
The way most web servers work (Apache for example) is to maintain a collection of worker threads. When a PHP script is executed, one thread runs the PHP script. When your script does `sleep(100)`, the script takes 100 seconds to execute.. That means your worker thread is tied up for 100 seconds. The problem is, you have a very finite number of worker-threads - say you have 10 threads, and 10 people login - now your web-server cannot serve any further responses.. The best way to rate-limit logins (or other actions) is to use some kind of fast in-memory storage thing ([memcached](http://www.danga.com/memcached/) is perfect for this), but that requires running separate process and is pretty complicated (you might do this if you run something like Facebook..). Simpler, you could have a database table that stores `user_id` or `ip_address`, `first_failed` and `failure_counter`. Every time you get a failed login, you (in pseudo code) would do: ``` if (first_failed in last hour) and (failure_counter > threshold): return error_403("Too many authentication failures, please wait") elseif first_failed in last hour: increment failure_counter else: reset first_failed to current time increment failure_counter ``` Maybe not the most efficient, and there is better ways, but it should stop brute-forcing pretty well. Using memcached is basically the same, but the database is replaced with memcached (which is quicker)
> to stop bots, malicious users, etc. > from executing php scripts too fast? I would first ask what you are really trying to prevent? If it is denial-of-service attacks, then I'd have to say there is nothing you can do if you are limited by what you can add to PHP scripts. The state of the art is so much beyond what we as programmers can protect against. Start looking at sysadmin tools designed for this purpose. Or are you trying to limit your service so that real people can access it but bots cannot? If so, I'd look at some "captcha" techniques. Or are you trying to prevent users from polling your site every second looking for new content? If so, I'd investigate providing an RSS feed or some other way of notifying them so they don't eat up your bandwidth. Or is it something else? In general, I'd say neither sleep() nor usleep() is a good way.
Delaying execution of PHP script
[ "", "php", "delayed-execution", "" ]
In PHP I'm trying to match each character as its own group. Which would mimic the `str_split()`. I tried: ``` $string = '123abc456def'; preg_match_all('/(.)*/', $string, $array); // $array = array(2) { // [0]=> array(2) { // [0]=> string(12) "123abc456def" // [1]=> string(0) "" } // [1]=> array(2) { [0]=> string(1) "f" [1]=> string(0) "" } } ``` I was expecting something like: ``` //$array = array(2) { // [0]=> string(12) "123abc456def", // [1]=> array(12) { // [0]=> string(1) "1", [1]=> string(1) "2" // ... // [10]=> string(1) "e", [11]=> string(1) "f" } } ``` The reason I want to use the regular expression instead of a `str_split()` is because the regex will be the basis of another regex.
The \* outside the parens means you want to repeat the capturing group. (This means you will only capture the last iteration.) Try a global match of any single character, like this: ``` preg_match_all('/(.)/', $subject, $result, PREG_PATTERN_ORDER); $result = $result[0]; ```
Try this: ``` preg_match_all('/./s', $str, $matches) ``` This does also match line break characters.
Using a regular expression to match each individual character as it's own group?
[ "", "php", "regex", "pcre", "" ]
When I add this to my where clause: ``` DueDate <= getDate() AND DueDate IS NOT null ``` I get a nice little failure that says: Could not create child: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.EvaluateException: The expression contains undefined function call getDate(). Any idea what I'm doing wrong? --- **Update** Code in use: ``` private string getFilter(int mode) { String filter = ""; if ((ALL_WORK_ORDERS & mode) == 0) { if ((mode & OUTSTANDING_WORK_ORDERS) == OUTSTANDING_WORK_ORDERS) { filter += "DueDate <= getDate() AND DueDate IS NOT null OR"; } if ((mode & COMPLETED_WORK_ORDERS) == COMPLETED_WORK_ORDERS) { filter += " FinishedDate IS NOT null"; } } filter = filter.Trim(); if (filter.EndsWith("OR")) { filter = filter.Remove(filter.Length - 2); } return filter; } ``` And it is getting used here: ``` tblWorkOrderBindingSource.Filter = getFilter(mode); ``` In the table, DueDate is type datetime. **Side note:** I can run ``` SELECT [ID] ,[WorkDesc] ,[DueDate] FROM [RentalEase].[dbo].[tblWorkOrder] WHERE [DueDate] <= getDate() AND [DueDate] IS NOT null ``` in the MS SQL Server Management Studio Express without a problem. --- ## Final Solution ``` private string getFilter(int mode) { String filter = ""; if ((ALL_WORK_ORDERS & mode) == 0) { if ((mode & OUTSTANDING_WORK_ORDERS) == OUTSTANDING_WORK_ORDERS) { filter += "DueDate <= #" + DateTime.Now.ToShortDateString() + "# AND DueDate IS NOT null AND FinishedDate IS null OR"; } if ((mode & COMPLETED_WORK_ORDERS) == COMPLETED_WORK_ORDERS) { filter += " FinishedDate IS NOT null"; } } filter = filter.Trim(); if (filter.EndsWith("OR")) { filter = filter.Remove(filter.Length - 2); } return filter; } ```
The exception is pretty clear on what is wrong here. You are specifying a method, getdate, which can't be used in a filter expression. See the documentation on the Expression property on the DataColumn class for what is valid and what is not: <http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx> That being said, instead of getdate, you need to concatenate the date into the filter (call the static Now property on the DateTime structure to get the current date). The link above will show you how to format dates properly (you can't just do it as indicated in Kelly's answer, although that answer is most of the way there).
have you tried ``` filter += "DueDate <= #" + DateTime.Now + "# AND DueDate is not Null" ```
SQL Server Date Functions
[ "", "c#", "sql-server", ".net-3.5", "bindingsource", "" ]
I'm developing an editor plugin for eclipse. It works fine on files within eclipse projects, but when an external file is opened via the "File -> Open File" menu (which works file with, e.g. Java files), I get a page displaying nothing but a horizontal blue line and the word "ERROR". The Error Log of eclipse is empty, as is the log file in the .metadata directory. What could cause this? How can I diagnose the error when I have no error message that tells me where to look? There doesn't seem to be a way to get more detailed logging from eclipse. **Edit:** I've found that the source of the problem is close to what jamesh mentioned, but not a ClassCastException - there simply is no `IDocument` instance for the text viewer to display because `StorageDocumentProvider.createDocument()` returns null. The reason for this is that it only knows how to create documents for instances of `org.eclipse.ui.IStorageEditorInput`, but in this case it gets an instance of `org.eclipse.ui.ide.FileStoreEditorInput`, which does not implement that interface, but instead implements `org.eclipse.ui.IURIEditorInput`
I had the same probleam and finally found solution working for me. You have to provide 2 different document providers - first extending **FileDocumentProvider** for files inside your workbench, and second extending **TextFileDocumentProvider** for other resources outside your workspace. Then you register the right provider acording to the input in your editors **doSetInput** method like this: ``` private IDocumentProvider createDocumentProvider(IEditorInput input) { if(input instanceof IFileEditorInput){ return new XMLTextDocumentProvider(); } else if(input instanceof IStorageEditorInput){ return new XMLFileDocumentProvider(); } else { return new XMLTextDocumentProvider(); } } @Override protected final void doSetInput(IEditorInput input) throws CoreException { setDocumentProvider(createDocumentProvider(input)); super.doSetInput(input); } ``` then in your new document provider (extending TextFileDocumentProvider) insert somethnig like this: ``` protected FileInfo createFileInfo(Object element) throws CoreException { FileInfo info = super.createFileInfo(element); if(info==null){ info = createEmptyFileInfo(); } IDocument document = info.fTextFileBuffer.getDocument(); if (document != null) { /* register your partitioner and other things here same way as in your fisrt document provider */ } return info; } ``` This works for me :) Finally I have to mention, that I'm not so clever and that I copied this solution from project Amateras (Opensource HTML editor plugin for eclipse)
I'm a little away from the source code at the moment, though I suspect the problem is a `ClassCastException`: * For a workspace file, the `IEditorInput` is `org.eclipse.ui.IFileEditorInput`. * For a local non-workspace file, the `IEditorInput` is `org.eclipse.ui.IStorageEditorInput` The difference is in how you get the contents from the `IEditorInput`. The JDT does an explicit `instanceof` check to make the switch. I don't think that the `getAdapter(Class clazz)` will return a `java.io.InputStream` if you offer it. I don't quite understand why they do it like this, but it feels ugly. **Edit:** A more general point about debugging eclipse apps - it's really very useful to try and assemble all your logs into one place (i.e. the console). To do this, make sure you use the command line options `-console` and `-consoleLog`. The latter has helped save countless hours of time. If you haven't already, learn the most basic things about how to use the console (`ss` and `start` are my most often used). This will save some more time diagnosing a certain class of problem.
Eclipse editor plugin: "ERROR" when opening file outside project
[ "", "java", "eclipse-plugin", "eclipse-pde", "" ]
I am looking for an online resource to learn the Spring MVC stack. Can someone point me in the right direction?
I have used this tutorial to start. I found it very helpful. <http://static.springframework.org/docs/Spring-MVC-step-by-step/>
Pick up a copy of [Spring in Action](http://www.manning.com/walls3/) from Manning Publications. Fantastic book with lots of great examples, theory and practical deployment tips.
Resource for learning Spring MVC
[ "", "java", "spring-mvc", "" ]
In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example: Original URL: > <http://server/myapp.php?id=10> Resulting URL: > <http://server/myapp.php?id=10>**&enabled=true** Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.
A basic implementation which you'll need to adapt would look something like this: ``` function insertParam(key, value) { key = encodeURIComponent(key); value = encodeURIComponent(value); // kvp looks like ['key1=value1', 'key2=value2', ...] var kvp = document.location.search.substr(1).split('&'); let i=0; for(; i<kvp.length; i++){ if (kvp[i].startsWith(key + '=')) { let pair = kvp[i].split('='); pair[1] = value; kvp[i] = pair.join('='); break; } } if(i >= kvp.length){ kvp[kvp.length] = [key,value].join('='); } // can return this or... let params = kvp.join('&'); // reload page with new params document.location.search = params; } ``` This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match --- the slow regex method I benchmarked against for completions sake (approx +150% slower) ``` function insertParam2(key,value) { key = encodeURIComponent(key); value = encodeURIComponent(value); var s = document.location.search; var kvp = key+"="+value; var r = new RegExp("(&|\\?)"+key+"=[^\&]*"); s = s.replace(r,"$1"+kvp); if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;}; //again, do what you will here document.location.search = s; } ```
You can use one of these: * <https://developer.mozilla.org/en-US/docs/Web/API/URL> * <https://developer.mozilla.org/en/docs/Web/API/URLSearchParams> Example: ``` var url = new URL("http://foo.bar/?x=1&y=2"); // If your expected result is "http://foo.bar/?x=1&y=2&x=42" url.searchParams.append('x', 42); // If your expected result is "http://foo.bar/?x=42&y=2" url.searchParams.set('x', 42); ``` You can use [url.href](https://developer.mozilla.org/en-US/docs/Web/API/URL/href) or [url.toString()](https://developer.mozilla.org/en-US/docs/Web/API/URL/toString) to get the full URL
Adding a parameter to the URL with JavaScript
[ "", "javascript", "url", "parsing", "parameters", "query-string", "" ]
How do I get just the children of an XElement? I am currently using the XElement.Descendants() function, which returns all levels of XElements, rather than just the child nodes. What I would really like is an IEnumerable of just the children.
The immediate child elements of one [XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) are accessible by calling the [`Element()`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx) or [`Elements()`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.elements.aspx) functions. Use the overloads with a name to access specific elements, or without to access all child elements. There are also similar methods like [`Attribute()`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.attribute.aspx) and [`Attributes()`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.attributes.aspx) that you might find useful.
XElement.Nodes() should get you what you want. If you just want the XElement child nodes then you might need to restrict it (depending on your XML) with: ``` XElement.Nodes().OfType<XElement>() ```
Children of XElement
[ "", "c#", "xml", "linq-to-xml", "xelement", "" ]
``` namespace GenericsTest { public class AGenericClass<T> { public class NestedNonGenericClass { } } } ``` In the example above, should `NestedNonGenericClass` be considered a generic class? The reflection API says it's a generic class, and even hands me the template parameters of the containing class as the template parameters of the nested class. ``` Type nestedClass = typeof(AGenericClass<int>.NestedNonGenericClass); Console.Out.WriteLine("IsGeneric: {0}\tHasGenericArguments: {1}", nestedClass.IsGenericType, nestedClass.GetGenericArguments().Length > 0); ``` This prints out: > IsGeneric: True HasGenericArguments: > True I don't completely agree with this behaviour. Even if the compiler generates a generic type for `NestedNonGenericClass`, I'd like to know if it's a generic because it was declared so, or because it's container is generic. So, my question is: Firstly, do you think it's okay to consider a nested class generic because it's container was generic? Why / Why not? Secondly, do you happen to know some other API that can help me identify only the classes that were declared generic? P.S: I could not find anything related to this in the ECMA specs for generics (or probably I just glossed over it). --EDIT-- To add a little more context, I'm working on a sort of Code Generator. And I'm using the reflection API to determine whether a type is generic. I ran into an issue with `Dictionary<TKey, TValue>.KeyCollection`. For `KeyCollection`, the reflection API says that it's generic and hands me over `TKey` and `TValue` which were declared in the container. So, the generator ends up generating `Dictionary<TKey, TValue>.KeyCollection<Tkey, TValue>` The only way I could solve this was by matching up the nested class' template parameters against the container's and eliminating all those that match. But I was wondering if there's a better approach.
In short, yes - a type inherits the type arguments from any types that contain it: this is the key to things like `List<T>.Enumerator` and many other scenarios, etc - it is critical that they share the `T` from the outer class (not just any `T`). The ECMA ref is §25.1: > Any class nested inside a generic > class declaration or a generic struct > declaration (§25.2) is itself a > generic class declaration, since type > parameters for the containing type > shall be supplied to create a > constructed type.
Yes, your nested class absolutely is generic, because T is bound to a type (this is known as a **closed generic**) within the scope of any instance of the nested class. ``` using System; using System.Collections.Generic; public class AGenericClass<T> { public class NestedNonGenericClass { public void DoSomething() { Console.WriteLine("typeof(T) == " + typeof(T)); } } } public class MyClass { public static void Main() { var c = new AGenericClass<int>.NestedNonGenericClass(); var d = new AGenericClass<DateTime>.NestedNonGenericClass(); c.DoSomething(); d.DoSomething(); Console.ReadKey(false); } } ``` The same `DoSomething()` method is producing different output depending on how the generic type was closed - so yes, the inner class is definitely exhibiting generic behaviour.
C#: Should a nested class in a generic class be considered generic?
[ "", "c#", "generics", "reflection", "" ]
We are writing a feature to send a reminder email to customers in x number of days and just wondered if it was possible to delay the sending of the emails similar to how you can in Outlook (New Mail > Options button > Do not deliver before) in C#. Does anyone know of a way of doing this?
One possibility is to create a service that runs on a scheduled task processing 'pending' mail. You might store the pending mail in a SQL Database. (Dave details this) This article looks promissing if you would like to avoid a 'real' service <http://www.codeproject.com/KB/aspnet/ASPNETService.aspx>
If you want to submit the email to an SMTP server to hold for a number of days, the server would have to support this feature. I would recommend against doing it that way, however. If you had a problem with missing emails it could be hard to track down. Here's what I would do: 1. Schedule the emails in *your* system by making a table entry. 2. Include a "SendDate" column in the table where you can set a date in the future 3. Write a Windows service that wakes up once every 15 minutes (for example) and sends the emails in that table where SendDate < currentDate
Delaying the sending of emails in C#
[ "", "c#", ".net", "asp.net", "email", "" ]
I want to develop a small OpenPGP client and I'm searching for a Java library for OpenPGP. Are there any (open source) recommendations for this approach? [Cryptix.org](http://www.cryptix.org/) does not seem alive anymore...
I found the [BouncyCastle](http://www.bouncycastle.org) library, for Java and C#. I haven't any experiences with it. I will try it and report here. It provides: 1. A lightweight cryptography API for Java and C#. 2. A provider for the Java Cryptography Extension and the Java Cryptography Architecture. 3. A clean room implementation of the JCE 1.2.1. 4. A library for reading and writing encoded ASN.1 objects. 5. A light weight client-side TLS API. 6. Generators for Version 1 and Version 3 X.509 certificates, Version 2 CRLs, and PKCS12 files. 7. Generators for Version 2 X.509 attribute certificates. 8. Generators/Processors for S/MIME and CMS (PKCS7/RFC 3852). 9. Generators/Processors for OCSP (RFC 2560). 10. Generators/Processors for TSP (RFC 3161). 11. Generators/Processors for OpenPGP (RFC 4880). 12. A signed jar version suitable for JDK 1.4-1.6 and the Sun JCE. (from BouncyCastle.org)
There is a commercial library on top of BouncyCastle: <http://www.didisoft.com/> which greatly simplifies the BouncyCastle API. I have not tried it just found it mentioned on jGuru. I think it's safe to go with BouncyCastle alone. Their library is under development and they provider openpgp examples...
Recommendations for Java + OpenPGP?
[ "", "java", "cryptography", "pgp", "gnupg", "openpgp", "" ]
I need to make a rather complex query, and I need help bad. Below is an example I made. Basically, I need a query that will return one row for each **case\_id** where the type is **support**, status **start**, and date meaning the very first one created (so that in the example below, only the 2/1/2009 John's case gets returned, not the 3/1/2009). The search needs to be dynamic to the point of being able to return all similar rows with different case\_id's etc from a table with thousands of rows. There's more after that but I don't know all the details yet, and I think I can figure it out if you guys (an gals) can help me out here. :) ``` ID | Case_ID | Name | Date | Status | Type    48 | 450 | John | 6/1/2009 | Fixed | Support 47 | 450 | John | 4/1/2009 | Moved | Support 46 | 451 | Sarah | 3/1/2009 | | 45 | 432 | John | 3/1/2009 | Fixed | Critical 44 | 450 | John | 3/1/2009 | Start | Support 42 | 450 | John | 2/1/2009 | Start | Support 41 | 440 | Ben | 2/1/2009 | | 40 | 432 | John | 1/1/2009 | Start | Critical ... ``` Thanks a bunch! Edit: To answer some people's questions, I'm using SQL Server 2005. And the date is just plain date, not string. Ok so now I got further in the problem. I ended up with Bliek's solution which worked like a charm. But now I ran into the problem that sometimes the status never starts, as it's solved immediately. I need to include this in as well. But only for a certain time period. I imagine I'm going to have to check for the case table referenced by FK Case\_ID here. So I'd need a way to check for each Case\_ID created in the CaseTable within the past month, and then run a search for these in the same table and same manner as posted above, returning only the first result as before. How can I use the other table like that? As usual I'll try to find the answer myself while waiting, thanks again! Edit 2: Seems this is the answer. I don't have access to the full DB yet so I can't fully test it, but it seems to be working with the dummy tables I created, to continue from Bliek's code's WHERE clause: ``` WHERE RowNumber = 1 AND Case_ID IN (SELECT Case_ID FROM CaseTable WHERE (Date BETWEEN '2007/11/1' AND '2007/11/30')) ``` The date's screwed again but you get the idea I'm sure. Thanks for the help everyone! I'll get back if there're more problems, but I think with this info I can improvise my way through most of the SQL problems I currently have to deal with. :)
In SQL Server 2005 and beyond I would use Common Table Expressions (CTE). This offers lots of possibilities like so: ``` With ResultTable (RowNumber ,ID ,Case_ID ,Name ,Date ,Status ,Type) AS ( SELECT Row_Number() OVER (PARTITION BY Case_ID ORDER BY Date ASC) ,ID ,Case_ID ,Name ,Date ,Status ,Type FROM CaseTable WHERE Type = 'Support' AND Status = 'Start' ) SELECT ID ,Case_ID ,Name ,Date ,Status ,Type FROM ResultTable WHERE RowNumber = 1 ```
Maybe something like: ``` select Case_ID, Name, MIN(date), Status, Type from table where type = 'Support' and status = 'Start' group by Case_ID, Name, Status, Type ``` EDIT: You haven't provided a lot of details about what you really want, so I'd suggest that you read all the answers and choose one that suits your problem best. So far I'd say that Tomalak's answer is closest to what you're looking for...
Need a Complex SQL Query
[ "", "sql", "dynamic", "" ]
I'd like to generate an image file showing some mathematical expression, taking a String like "(x+a)^n=∑\_(k=0)^n" as input and getting a more (human) readable image file as output. AFAIK stuff like that is used in Wikipedia for example. Are there maybe any java libraries that do that? Or maybe I use the wrong approach. What would you do if the requirement was to enable pasting of formulas from MS Word into an HTML-document? I'd ask the user to just make a screenshot himself, but that would be the lazy way^^ Edit: Thanks for the answers so far, but I really do not control the input. What I get is some messy Word-style formula, not clean latex-formatted one. Edit2: <http://www.panschk.de/text.tex> Looks a bit like LaTeX doesn't it? That's what I get when I do `clipboard.getContents(RTFTransfer.getInstance())` after having pasted a formula from Word07.
My colleague found a surprisingly simple solution for this very specific problem: When you copy formulas from Word2007, they are also stored as "HTML" in the Clipboard. As representing formulas in HTML isn't easy neither, Word just creates a temporary image file on the fly and embeds it into the HTML-code. You can then simply take the temporary formula-image and copy it somewhere else. Problem solved;)
First and foremost you should familiarize yourself with [TeX](http://en.wikipedia.org/wiki/TeX) (and [LaTeX](http://en.wikipedia.org/wiki/LaTeX)) - a famous typesetting system created by Donald Knuth. Typesetting mathematical formulae is an advanced topic with many opinions and much attention to detail - therefore use [something that builds upon TeX](http://schmidt.devlib.org/java/libraries-dvi.html). That way you are sure to get it right ;-) **Edit:** Take a look at [texvc](http://en.wikipedia.org/wiki/Texvc) It can output to PNG, HTML, MathML. Check out the [README](http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/math/README?view=markup) **Edit #2** Convert that messy [Word-stuff to TeX](http://www.tug.org/utilities/texconv/pctotex.html) or MathML?
Generate Images for formulas in Java
[ "", "java", "image", "formula", "" ]
I wonder if there is a counterpart to `java.util.LinkedHashMap` in .NET? (ie. the elements are (re)ordered automatically if I access an element. (boolean accessOrder) ).
A bit of Googling seems to show that there is no built in C# equivalent for LinkedHashMap, but there are some third party options available.
Just to clarify a bit for readers: LinkedHashMap only behaves that way when built with one particular constructor overload. Normally the elements are maintained in insert order. (This feels a little odd to me, but never mind.) I don't believe there's any such class in .NET. It wouldn't be too hard to build one, using a linked list of elements and a dictionary from key to linked list node. Access would then consist of fetching the linked list node, moving it to the head, and returning the value. I'd be happy to implement it tonight or tomorrow if you want - although probably not with full unit tests etc. (Fully testing a collection is a time-consuming business!)
LinkedHashMap in .NET
[ "", "java", ".net", ".net-3.5", "linkedhashmap", "" ]
Before I call: ``` $('myObject').show(); ``` I want to know if it is currently hidden or visible.
You can test this with the css() function: ``` if ($('myObject').css('display') == 'none') { $('myObject').show(); } ``` EDIT: Wasn't aware of how cool the :hidden selector is. My suggestion is still useful for testing other attributes, but Alex's suggestion is nicer in this case.
There's 2 ways to do it, that I know of: ``` if ($('#something').is(':hidden')) { } ``` or ``` if ($('#something').is(':visible')) { } ``` They should both work. You can also do something like this: ``` $('#something:hidden').show(); $('#something:visible').hide(); ``` Which will only call .show() if the item is already hidden, or only call .hide() if the item is already visible.
In jQuery, how can I tell if the current object is hidden or not?
[ "", "javascript", "jquery", "css", "" ]
I'm a Java rookie and I was wondering, if I have the following typical Java code ``` public class MyApp { public static void main(String[] args) { try { // do stuff } catch { // handle errors } finally { // clean up connections etc. } } } ``` does the JVM guarantee that the finally block will always be run? To understand where I'm coming from, I'm used to C/C++ programs that might just crash if you dereference a NULL pointer and you can't have any code to be run after that. But as I understand Java and the whole GC / managed memory business in general, there's no such thing as a null pointer dereferencing, everything is a catchable expection, so there's not really a way for my program to crash that could make it skip the finally, or is there? For example, in Python, I usually do ``` try: # do stuff except AnExceptionIKnewMightHappen: # react in an appropriate way except: # log that weird error I had not known could happen ``` and I have never had any app die without passing through my code. Of course, if the OS for some reason kills the process (or if something kills the whole system, like pulling the plug) there's not much Java can do. Also, from PHP I know non-catchable errors that you can't protect against, even though the interpreter was still there after it happened (at least it is able to output a proper message). **Edit:** Just for clarity (it wasn't really misunderstood by anyone), let me add that I was looking for things *inside my code* that could lead to the finally being bypassed. So pointing to System.exit was a helpful reminder, even though I can't see why I would want to do something like that. The JVM exiting is a rather obvious way and I'd count that as an external cause. The note pointing out that you also have to remember the possibilty of threads exiting while the JVM and the app keep running was very helpful, because even though it also seems obvious to me now, I hadn't thought of it.
Basically yes, except for the note [listed here](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) (emphasis mine): > If the JVM exits while the try or catch code is being executed, > then the finally block **may not** execute. Likewise, if the thread > executing the try or catch code is interrupted or killed, the finally > block **may not** execute even though the application as a whole > continues.
It is not guaranteed: ``` public class Main { public static void main(String args[]) { try { System.out.println("try"); System.exit(0); } catch (Exception e) { System.out.println("exception"); } finally { System.out.println("finally"); } } } ``` Run that.
In Java, is the "finally" block guaranteed to be called (in the main method)?
[ "", "java", "error-handling", "finally", "" ]
Don't ask why, but is there any way to suppress a failed linking error? Such as: undefined reference to BLANK This is in GCC 3.4.6
No, because they are errors and not warnings. By definition this means that the function was referenced someplace but not defined... that's not something you can just ignore.
It's not the compiler, but the linker. The best way to "suppress" this would be to pass in the library name with the compile command: > gcc try.cc -lstdc++ or > g++ try.cc -lfltk for instance.
Suppressing Linking Errors in G++ 3.4.6
[ "", "c++", "gcc", "g++", "linker", "" ]
The .NET framework provides a few handy general-use delegates for common tasks, such as [`Predicate<T>`](http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx) and [`EventHandler<T>`](http://msdn.microsoft.com/en-us/library/system.eventhandler(VS.71).aspx). Is there a built-in delegate for the equivalent of CompareTo()? The signature might be something like this: ``` delegate int Comparison<T>(T x, T y); ``` This is to implement sorting in such a way that I can provide a lambda expression for the actual sort routine (ListView.ListViewItemSorter, specifically), so any other approaches welcome.
You even got the names right :) See [`System.Comparison<T>`](http://msdn.microsoft.com/en-us/library/tfakywbh.aspx)
Look for: [`System.Collections.Generic.Comparer<T>`](http://msdn.microsoft.com/en-us/library/cfttsh47.aspx)
Is there an existing delegate in the .NET Framework for comparison?
[ "", "c#", ".net", "sorting", "delegates", "" ]
How do I create a GUID/UUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
> The [uuid module](https://docs.python.org/3/library/uuid.html) provides immutable UUID objects (the UUID class) and the functions [`uuid1()`](https://docs.python.org/3/library/uuid.html#uuid.uuid1), [`uuid3()`](https://docs.python.org/3/library/uuid.html#uuid.uuid3), [`uuid4()`](https://docs.python.org/3/library/uuid.html#uuid.uuid4), [`uuid5()`](https://docs.python.org/3/library/uuid.html#uuid.uuid5) for generating version 1, 3, 4, and 5 UUIDs as specified in [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122). > If all you want is a unique ID, you should probably call `uuid1()` or `uuid4()`. > > > **Note that `uuid1()` may compromise privacy since it creates a UUID containing the computer’s network address.** > > `uuid4()` creates a random UUID. UUID versions 6 and 7 - *new Universally Unique Identifier (UUID) formats for use in modern applications and databases* [(**draft**) rfc](https://uuid6.github.io/uuid6-ietf-draft/) - are available from <https://pypi.org/project/uuid6/> Docs: * [Python 2](https://docs.python.org/2/library/uuid.html) * [Python 3](https://docs.python.org/3/library/uuid.html) Examples (for both Python 2 and 3): ``` >>> import uuid >>> # make a random UUID >>> uuid.uuid4() UUID('bd65600d-8669-4903-8a14-af88203add38') >>> # Convert a UUID to a string of hex digits in standard form >>> str(uuid.uuid4()) 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0' >>> # Convert a UUID to a 32-character hexadecimal string >>> uuid.uuid4().hex '9fe2c4e93f654fdbb24c02b15259716c' ```
If you're using Python 2.5 or later, the [**uuid module**](https://docs.python.org/2/library/uuid.html#module-uuid "uuid module") is already included with the Python standard distribution. Ex: ``` >>> import uuid >>> uuid.uuid4() UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14') ```
How to create a GUID/UUID in Python
[ "", "python", "uuid", "guid", "uniqueidentifier", "" ]
Background: I am using ASP.NET 2.0 (with C#) and the code below is embedded in a DataGrid control. I have the following in my .aspx file: ``` <ASP:TEMPLATECOLUMN HeaderText="Includes CRS Statement?"> <ITEMTEMPLATE> <asp:RadioButtonList id="rblSCIncludesCRSStatement" runat="server" RepeatDirection="Horizontal" SelectedIndex='<%# Convert.ToInt32(DataBinder.Eval(Container, "DataItem.CRS_Included")) %>' DataValueField="CRS_Included" RepeatLayout="Flow"> <asp:ListItem value="true" selected="true">Yes</asp:ListItem> <asp:ListItem value="false">No</asp:ListItem> </asp:RadioButtonList> </ITEMTEMPLATE> </ASP:TEMPLATECOLUMN> <ASP:BOUNDCOLUMN visible="false" HeaderText="IncludesCRSStatement" DataField="CRS_Included"></ASP:BOUNDCOLUMN> ``` It is supposed to bind the boolean value CRS\_Included with the RadioButtonList. It works, but in reverse order. Yes is turned to no, no is turned to yes, and the only way I can see to fix it is swap the order of the ListItems, which would be counterintuitive (Radio buttons shouldn't start like No/Yes, it needs to be Yes/No). Does anyone know a quick way (preferably using .NET functions) to swap the 0 for 1, 1 for 0 and fix the problem seamlessly? Or, is there a better way to write the SelectedIndex code? Any help is appreciated :-)
``` SelectedIndex='<%# 1 - Convert.ToInt32(...) %> ``` 1 - 0 = 1; 1 - 1 = 0. Cases swapped :) EDIT: There may well be a better way of handling the more general question - this was just the simple approach of solving the 1/0 swap :)
Why not use the SelectedValue property rather than SelectedIndex.?
ASP.NET - Easy way to swap a boolean?
[ "", "c#", "asp.net", "datagrid", "" ]
I'm doing some class clean to organize the functions in cs file in alphabetical order. I'm using Visual Studio 2008. When writing them, I just put them arbitrarily, but it now looks quite messy. Is there some easy way to organize them automatically? Better to have a tool because there're quite a lot files to clean up.
Why bother organizing in alpha order? The IDE provides a drop down list in order for you to use if you wish to access them in that manner. Instead the source file should contain them in a meaningful order (what is meaningful is rather subjective) either by the specifics of their tasks or by some sensible convention if nothing else exists (such as by visibility, or placing properties together). Auto layout rules are a nightmare for source repositories since they put in needless mass movements that frustrate your ability to identify real change, as such they should be avoided unless the rules comply with one of the following: * They **never** change and you can apply it from the beginning of your project * They change very rarely and changing will affect at most a single line movement (like bracketing structure) * They change rarely and the effect is simply on white space within a line If the answer is at all beyond 'rarely' you don't want to use it full stop, efficient browsing of historical changes is more useful.
Have you tried [Regionerate](http://www.rauchy.net/regionerate/)?
How to quickly organize functions in source code (c#) to order by alphabetical order?
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
What I want is something similar to STL vector when it comes to access complexity, reallocation on resize, etc. I want it to support arbitrary index range, for example there could be elements indexed from -2 to +7 or from +5 to +10. I want to be able to push\_front efficiently. Also I want two-way resize... I know I could write something like this myself, but if there is an already written library that supports this please tell me.
Deque is very much like a vector in that it supports random access and efficient insertion at the end and it also supports efficient insertion at the beginning. Map supports access based on arbitrary keys, you can have any range you want, or even a sparsely populated array. Iteration over the collection is slow. Unordered map (tr1) is similar to map except it supports better iteration. As a general rule of thumb, use a vector (in your case adapt it to the behaviour you want) and only change when you have evidence that the vector is causing slowness.
It seems the only difference between what you want and a vector is the offset you require for accessing elements, which you take care if by overloading operator [] or something. Unless I didn't understand what you meant by two-way resize.
STL-like vector with arbitrary index range
[ "", "c++", "stl", "vector", "deque", "" ]
What is the most preferred and easiest way to do pagination in ASP.NET MVC? I.e. what is the easiest way to break up a list into several browsable pages. As an example lets say I get a list of elements from a database/gateway/repository like this: ``` public ActionResult ListMyItems() { List<Item> list = ItemDB.GetListOfItems(); ViewData["ItemList"] = list; return View(); } ``` For simplicity's sake I'd like to specify just a page number for my action as parameter. Like this: ``` public ActionResult ListMyItems(int page) { //... } ```
Well, what is the data source? Your action could take a few defaulted arguments, i.e. ``` ActionResult Search(string query, int startIndex, int pageSize) {...} ``` defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20: ``` routes.MapRoute("Search", "Search/{query}/{startIndex}", new { controller = "Home", action = "Search", startIndex = 0, pageSize = 20 }); ``` To split the feed, you can use LINQ quite easily: ``` var page = source.Skip(startIndex).Take(pageSize); ``` (or do a multiplication if you use "pageNumber" rather than "startIndex") With LINQ-toSQL, EF, etc - this should "compose" down to the database, too. You should then be able to use action-links to the next page (etc): ``` <%=Html.ActionLink("next page", "Search", new { query, startIndex = startIndex + pageSize, pageSize }) %> ```
I wanted to cover a simple way of doing this with the front end too: **Controller:** ``` public ActionResult Index(int page = 0) { const int PageSize = 3; // you can always do something more elegant to set this var count = this.dataSource.Count(); var data = this.dataSource.Skip(page * PageSize).Take(PageSize).ToList(); this.ViewBag.MaxPage = (count / PageSize) - (count % PageSize == 0 ? 1 : 0); this.ViewBag.Page = page; return this.View(data); } ``` **View:** ``` @* rest of file with view *@ @if (ViewBag.Page > 0) { <a href="@Url.Action("Index", new { page = ViewBag.Page - 1 })" class="btn btn-default"> &laquo; Prev </a> } @if (ViewBag.Page < ViewBag.MaxPage) { <a href="@Url.Action("Index", new { page = ViewBag.Page + 1 })" class="btn btn-default"> Next &raquo; </a> } ```
How do I do pagination in ASP.NET MVC?
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
``` <form action="/cgi-bin/Lib.exe" method=POST name="checks"> <input type=checkbox name="user1" value="'$NAME'"> <input type=checkbox name="user2" value="'$NAME'"> <input type=checkbox name="user3" value="'$NAME'"> <input type="button" value="User 1" onclick="somefunction()"> ``` For example, if I selected checkbox `user2` I would want the javascript function to pop up saying "you are not user 1..." (all input check boxes are under same form name). After validation of specific check box name I will do `document.checks.submit();` Thanks.
I'd propose few improvements to sktrdie's reply. This will avoid submitting form on errors. ``` <form action="".... onsubmit="return somefunction(this);"> function somefunction(f) { var user1 = f.user1; var user2 = f.user2; // etc.. if(user2.checked) { alert("you are not user1"); return false; } return true; } ``` Note #1: this example is very simple and not-so-flexible, so additional reading on forms validation would be good idea. Say, on [w3schools](http://www.w3schools.com/jS/js_form_validation.asp) Note #2: do not forget to implement server-side validation along with this. JS checks can be easily avoided.
``` <form onsubmit="somefunction(this);" ... function somefunction(f) { var user1 = f.user1; var user2 = f.user2; // etc.. if(user2.checked) alert("you are not user1"); } ```
Validate specific input, Javascript
[ "", "javascript", "validation", "forms", "" ]