qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
74,092
<p>I have a function in Python which is iterating over the attributes returned from <code>dir(obj)</code>, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use <code>callable()</code> for this, but I don't want to include classes. The best I've come up with so far is:</p> <pre><code>isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)) </code></pre> <p>Is there a more future-proof way to do this check?</p> <p><strong>Edit:</strong> I misspoke before when I said: &quot;Normally you could use <code>callable()</code> for this, but I don't want to disqualify classes.&quot; I actually <em>do</em> want to disqualify classes. I want to match <em>only</em> functions, not classes.</p>
[ { "answer_id": 74138, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<pre><code>if hasattr(obj, '__call__'): pass\n</code></pre>\n\n<p>This also fits in better with Python's \"duck typing\" philosop...
2008/09/16
[ "https://Stackoverflow.com/questions/74092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156/" ]
I have a function in Python which is iterating over the attributes returned from `dir(obj)`, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use `callable()` for this, but I don't want to include classes. The best I've come up with so far is: ``` isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)) ``` Is there a more future-proof way to do this check? **Edit:** I misspoke before when I said: "Normally you could use `callable()` for this, but I don't want to disqualify classes." I actually *do* want to disqualify classes. I want to match *only* functions, not classes.
The inspect module has exactly what you want: ``` inspect.isroutine( obj ) ``` FYI, the code is: ``` def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) ```
74,113
<p>It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?</p>
[ { "answer_id": 74255, "author": "wxs", "author_id": 12981, "author_profile": "https://Stackoverflow.com/users/12981", "pm_score": 7, "selected": true, "text": "<p>You need to use the <code>UIImagePickerController</code> class, basically:</p>\n\n<pre><code>UIImagePickerController *picker ...
2008/09/16
[ "https://Stackoverflow.com/questions/74113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5338/" ]
It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?
You need to use the `UIImagePickerController` class, basically: ``` UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = pickerDelegate picker.sourceType = UIImagePickerControllerSourceTypeCamera ``` The `pickerDelegate` object above needs to implement the following method: ``` - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ``` The dictionary `info` will contain entries for the original, and the edited image, keyed with `UIImagePickerControllerOriginalImage` and `UIImagePickerControllerEditedImage` respectively. (see <https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate> and <https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey> for more details)
74,148
<p>How do you convert between hexadecimal numbers and decimal numbers in C#?</p>
[ { "answer_id": 74183, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<pre><code>String stringrep = myintvar.ToString(\"X\");\n\nint num = int.Parse(\"FF\", System.Globalization.NumberStyles.HexN...
2008/09/16
[ "https://Stackoverflow.com/questions/74148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
How do you convert between hexadecimal numbers and decimal numbers in C#?
To convert from decimal to hex do... ``` string hexValue = decValue.ToString("X"); ``` To convert from hex to decimal do either... ``` int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); ``` or ``` int decValue = Convert.ToInt32(hexValue, 16); ```
74,162
<p>I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:</p> <pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1); </code></pre> <p>I tried but get a syntax error message.</p> <p>What would you do if you want to do this?</p>
[ { "answer_id": 74196, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 3, "selected": false, "text": "<p>Remove <code>VALUES</code> from your SQL.</p>\n" }, { "answer_id": 74204, "author": "pilsetnieks",...
2008/09/16
[ "https://Stackoverflow.com/questions/74162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1); ``` I tried but get a syntax error message. What would you do if you want to do this?
No "VALUES", no parenthesis: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1; ```
74,171
<p>I maintain a Java Swing application.</p> <p>For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features.</p> <p>The code is largely the same, except for 3-4 classes that uses Java 6 features.</p> <p>I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code?</p> <p>I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.</p>
[ { "answer_id": 74202, "author": "chessguy", "author_id": 1908025, "author_profile": "https://Stackoverflow.com/users/1908025", "pm_score": 2, "selected": false, "text": "<p>I think the best approach here is probably to use build scripts. You can have all your code in one location, and by...
2008/09/16
[ "https://Stackoverflow.com/questions/74171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12944/" ]
I maintain a Java Swing application. For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features. The code is largely the same, except for 3-4 classes that uses Java 6 features. I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code? I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.
Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class. Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement will not be included in the compilation. You can make a static variable in one of your classes to determine which version you want to run: ``` public static final boolean COMPILED_IN_JAVA_6 = false; ``` And then have the affected classes check that static variable and put the different sections of code in a simple if statement ``` if (VersionUtil.COMPILED_IN_JAVA_6) { // Java 6 stuff goes here } else { // Java 1.5 stuff goes here } ``` Then when you want to compile the other version you just have to change that one variable and recompile. It might make the java file larger but it will consolidate your code and eliminate any code duplication that you have. Your editor may complain about unreachable code or whatever but the compiler should blissfully ignore it.
74,188
<p>I've created a ListBox to display items in groups, where the groups are wrapped right to left when they can no longer fit within the height of the ListBox's panel. So, the groups would appear similar to this in the listbox, where each group's height is arbitrary (group 1, for instance, is twice as tall as group 2):</p> <pre><code>[ 1 ][ 3 ][ 5 ] [ ][ 4 ][ 6 ] [ 2 ][ ] </code></pre> <p>The following XAML works correctly in that it performs the wrapping, and allows the horizontal scroll bar to appear when the items run off the right side of the ListBox.</p> <pre><code>&lt;ListBox&gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Vertical"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;ListBox.GroupStyle&gt; &lt;ItemsPanelTemplate&gt; &lt;WrapPanel Orientation="Vertical" Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ScrollContentPresenter}}}"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.GroupStyle&gt; &lt;/ListBox&gt; </code></pre> <p>The problem occurs when a group of items is longer than the height of the WrapPanel. Instead of allowing the vertical scroll bar to appear to view the cutoff item group, the items in that group are simply clipped. I'm assuming that this is a side effect of the Height binding in the WrapPanel - the scrollbar thinks it does not have to enabled.</p> <p>Is there any way to enable the scrollbar, or another way around this issue that I'm not seeing?</p>
[ { "answer_id": 74235, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 0, "selected": false, "text": "<p>I would think that you are correct that it has to do with the binding. What happens when you remove the binding? With th...
2008/09/16
[ "https://Stackoverflow.com/questions/74188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've created a ListBox to display items in groups, where the groups are wrapped right to left when they can no longer fit within the height of the ListBox's panel. So, the groups would appear similar to this in the listbox, where each group's height is arbitrary (group 1, for instance, is twice as tall as group 2): ``` [ 1 ][ 3 ][ 5 ] [ ][ 4 ][ 6 ] [ 2 ][ ] ``` The following XAML works correctly in that it performs the wrapping, and allows the horizontal scroll bar to appear when the items run off the right side of the ListBox. ``` <ListBox> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Vertical"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.GroupStyle> <ItemsPanelTemplate> <WrapPanel Orientation="Vertical" Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ScrollContentPresenter}}}"/> </ItemsPanelTemplate> </ListBox.GroupStyle> </ListBox> ``` The problem occurs when a group of items is longer than the height of the WrapPanel. Instead of allowing the vertical scroll bar to appear to view the cutoff item group, the items in that group are simply clipped. I'm assuming that this is a side effect of the Height binding in the WrapPanel - the scrollbar thinks it does not have to enabled. Is there any way to enable the scrollbar, or another way around this issue that I'm not seeing?
By setting the Height property on the WrapPanel to the height of the ScrollContentPresenter, it will never scroll vertically. However, if you remove that Binding, it will never wrap, since in the layout pass, it has infinite height to layout in. I would suggest creating your own panel class to get the behavior you want. Have a separate dependency property that you can bind the desired height to, so you can use that to calculate the target height in the measure and arrange steps. If any one child is taller than the desired height, use that child's height as the target height to calculate the wrapping. Here is an example panel to do this: ``` public class SmartWrapPanel : WrapPanel { /// <summary> /// Identifies the DesiredHeight dependency property /// </summary> public static readonly DependencyProperty DesiredHeightProperty = DependencyProperty.Register( "DesiredHeight", typeof(double), typeof(SmartWrapPanel), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets the height to attempt to be. If any child is taller than this, will use the child's height. /// </summary> public double DesiredHeight { get { return (double)GetValue(DesiredHeightProperty); } set { SetValue(DesiredHeightProperty, value); } } protected override Size MeasureOverride(Size constraint) { Size ret = base.MeasureOverride(constraint); double h = ret.Height; if (!Double.IsNaN(DesiredHeight)) { h = DesiredHeight; foreach (UIElement child in Children) { if (child.DesiredSize.Height > h) h = child.DesiredSize.Height; } } return new Size(ret.Width, h); } protected override System.Windows.Size ArrangeOverride(Size finalSize) { double h = finalSize.Height; if (!Double.IsNaN(DesiredHeight)) { h = DesiredHeight; foreach (UIElement child in Children) { if (child.DesiredSize.Height > h) h = child.DesiredSize.Height; } } return base.ArrangeOverride(new Size(finalSize.Width, h)); } } ```
74,206
<p>I have been playing with this for a while, but the closest I have gotten is a button that opens the <code>Paste Special</code> dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text. </p> <p>So often I am doing a <code>copy-paste</code> from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.</p>
[ { "answer_id": 74237, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 4, "selected": true, "text": "<p>Make the button call the macro:</p>\n\n<pre><code>public sub PasteSpecialUnformatted()\n selection.pastespecial datatype:=...
2008/09/16
[ "https://Stackoverflow.com/questions/74206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30018/" ]
I have been playing with this for a while, but the closest I have gotten is a button that opens the `Paste Special` dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text. So often I am doing a `copy-paste` from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.
Make the button call the macro: ``` public sub PasteSpecialUnformatted() selection.pastespecial datatype:=wdpastetext end sub ```
74,218
<p>Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it?</p> <p>** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).</p> <p>** Rails signals registered. HUP => reload (without restart). It might not work well.</p>
[ { "answer_id": 74241, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 2, "selected": false, "text": "<p>For example,</p>\n\n<pre><code>killall -USR2 mongrel_rails\n</code></pre>\n" }, { "answer_id": 74998, "au...
2008/09/16
[ "https://Stackoverflow.com/questions/74218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it? \*\* Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart). \*\* Rails signals registered. HUP => reload (without restart). It might not work well.
You can add the -c option if the config for your app's cluster is elsewhere: ``` mongrel_rails cluster::restart -c /path/to/config ```
74,248
<p>On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day <em>after</em> the day specified by that object. I can use &lt;jsp:scriptlet&gt; to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.</p> <p>Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?</p>
[ { "answer_id": 74274, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 2, "selected": false, "text": "<p>While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Cal...
2008/09/16
[ "https://Stackoverflow.com/questions/74248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041950/" ]
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day *after* the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me. Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?
I'm not a fan of putting java code in your jsp. I'd use a static method and a taglib to accomplish this. Just my idea though. There are many ways to solve this problem. ``` public static Date addDay(Date date){ //TODO you may want to check for a null date and handle it. Calendar cal = Calendar.getInstance(); cal.setTime (date); cal.add (Calendar.DATE, 1); return cal.getTime(); } ``` functions.tld ``` <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>functions library</description> <display-name>functions</display-name> <tlib-version>1.1</tlib-version> <short-name>xfn</short-name> <uri>http://yourdomain/functions.tld</uri> <function> <description> Adds 1 day to a date. </description> <name>addDay</name> <function-class>Functions</function-class> <function-signature>java.util.Date addDay(java.util.Date)</function-signature> <example> ${xfn:addDay(date)} </example> </function> </taglib> ```
74,266
<p>I have an ext combobox which uses a store to suggest values to a user as they type. </p> <p>An example of which can be found here: <a href="http://extjs.com/deploy/ext/examples/form/combos.html" rel="nofollow noreferrer">combobox example</a></p> <p>Is there a way of making it so the <strong>suggested text list</strong> is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.</p>
[ { "answer_id": 74680, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 0, "selected": false, "text": "<p>So clarify, you want the selected text to render somewhere besides directly below the text input. Correct?</p>\n\n<p>ComboB...
2008/09/16
[ "https://Stackoverflow.com/questions/74266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193/" ]
I have an ext combobox which uses a store to suggest values to a user as they type. An example of which can be found here: [combobox example](http://extjs.com/deploy/ext/examples/form/combos.html) Is there a way of making it so the **suggested text list** is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.
You can use plugin for this, since you can call or even override private methods from within the plugin: ``` var suggested_text_plugin = { init: function(o) { o.onTypeAhead = function() { // Original code from the sources goes here: if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } // Your code to display newValue in DOM ......myDom.getEl().update(newValue); }; } }; // in combobox code: var cb = new Ext.form.ComboBox({ .... plugins: suggested_text_plugin, .... }); ``` I think it's even possible to create a whole chain of methods, calling original method before or after yours, but I haven't tried this yet. Also, please don't push me hard for using non-standard plugin definition and invocation methodics (undocumented). It's just my way of seeing things. EDIT: I think the method chain could be implemented something like that (untested): ``` .... o.origTypeAhead = new Function(this.onTypeAhead.toSource()); // or just o.origTypeAhead = this.onTypeAhead; .... o.onTypeAhead = function() { // Call original this.origTypeAhead(); // Display value into your DOM element ...myDom.... }; ```
74,267
<p>I'm trying to script the shutdown of my VM Servers in a .bat. if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out.</p> <pre><code>c: cd "c:\Program Files\VMWare\VmWare Server" vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0 vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start </code></pre>
[ { "answer_id": 74304, "author": "Jen A", "author_id": 12979, "author_profile": "https://Stackoverflow.com/users/12979", "pm_score": 2, "selected": false, "text": "<p>Have you tried using \"start (cmd)\" for each command you are executing?</p>\n" }, { "answer_id": 74314, "auth...
2008/09/16
[ "https://Stackoverflow.com/questions/74267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
I'm trying to script the shutdown of my VM Servers in a .bat. if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out. ``` c: cd "c:\Program Files\VMWare\VmWare Server" vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0 vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start ```
Run it inside another command instance with `CMD /C` ``` CMD /C vmware-cmd C:\... ``` This should keep the original BAT files running.
74,350
<p>I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive.</p> <p>As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action.</p> <p>I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this:</p> <pre><code> if (!m_bHighlighted) { pDC-&gt;FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour); } else { pDC-&gt;FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour); } </code></pre> <p>However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect.</p> <p>Is there any way I can get around this?</p>
[ { "answer_id": 74501, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 0, "selected": false, "text": "<p>It almost looks like the CStatic doesn't know that it needs to repaint itself, so the background color of the draggable objec...
2008/09/16
[ "https://Stackoverflow.com/questions/74350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1169/" ]
I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive. As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action. I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this: ``` if (!m_bHighlighted) { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour); } else { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour); } ``` However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect. Is there any way I can get around this?
Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks. Thankfully this time the answer was fairly straightforward.... ``` ImageList_DragShowNolock(FALSE); m_pDragDropTargetWnd->SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&dragDropPoint)); ImageList_DragShowNolock(TRUE); ``` This turns off the drawing of the dragged image, then sends a message to the window being entered to repaint in a highlighted state, then finally redraws the drag image over the top. Seems to have done the trick.
74,372
<p>I am involved in the process of porting a system containing several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. I have come across the following difference in the way ksh behaves on the two systems:</p> <pre><code>#!/bin/ksh flag=false echo "a\nb" | while read x do flag=true done echo "flag = ${flag}" exit 0 </code></pre> <p>On AIX, Solaris and HPUX the output is "flag = true" on Linux the output is "flag = false".</p> <p>My questions are:</p> <ul> <li>Is there an environment variable that I can set to get Linux's ksh to behave like the other Os's'? Failing that:</li> <li>Is there an option on Linux's ksh to get the required behavior? Failing that:</li> <li>Is there a ksh implementation available for Linux with the desired behavior?</li> </ul> <p>Other notes:</p> <ul> <li>On AIX, Solaris and HPUX ksh is a variant of ksh88.</li> <li>On Linux, ksh is the public domain ksh (pdksh)</li> <li>On AIX, Solaris and HPUX dtksh and ksh93 (where I have them installed) are consistent with ksh</li> <li>The Windows NT systems I have access to: Cygwin and MKS NT, are consistent with Linux.</li> <li>On AIX, Solaris and Linux, bash is consistent, giving the incorrect (from my perspective) result of "flag = false".</li> </ul> <p>The following table summarizes the systems the problem:</p> <pre><code>uname -s uname -r which ksh ksh version flag = ======== ======== ========= =========== ====== Linux 2.6.9-55.0.0.0.2.ELsmp /bin/ksh PD KSH v5.2.14 99/07/13.2 false AIX 3 /bin/ksh Version M-11/16/88f true // AIX 5.3 /bin/ksh93 Version M-12/28/93e true SunOS 5.8, 5.9 and 5.10 /bin/ksh Version M-11/16/88i true /usr/dt/bin/dtksh Version M-12/28/93d true HP-UX B.11.11 and B.11.23 /bin/ksh Version 11/16/88 true /usr/dt/bin/dtksh Version M-12/28/93d true CYGWIN_NT-5.1 1.5.25(0.156/4/2) /bin/ksh PD KSH v5.2.14 99/07/13.2 false Windows_NT 5 .../mksnt/ksh.exe Version 8.7.0 build 1859... false // MKS </code></pre> <h1>Update</h1> <p>After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash.</p> <pre><code>#!/bin/ksh echo "a\nb" &gt; junk flag=false while read x do flag=true done &lt; junk echo "flag = ${flag}" exit 0 </code></pre> <p>Thanks to jj33 for the previously accepted answer.</p>
[ { "answer_id": 74421, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<p>I don't know of any particular option to force ksh to be compatible with a particular older version. That said, perhaps yo...
2008/09/16
[ "https://Stackoverflow.com/questions/74372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13029/" ]
I am involved in the process of porting a system containing several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. I have come across the following difference in the way ksh behaves on the two systems: ``` #!/bin/ksh flag=false echo "a\nb" | while read x do flag=true done echo "flag = ${flag}" exit 0 ``` On AIX, Solaris and HPUX the output is "flag = true" on Linux the output is "flag = false". My questions are: * Is there an environment variable that I can set to get Linux's ksh to behave like the other Os's'? Failing that: * Is there an option on Linux's ksh to get the required behavior? Failing that: * Is there a ksh implementation available for Linux with the desired behavior? Other notes: * On AIX, Solaris and HPUX ksh is a variant of ksh88. * On Linux, ksh is the public domain ksh (pdksh) * On AIX, Solaris and HPUX dtksh and ksh93 (where I have them installed) are consistent with ksh * The Windows NT systems I have access to: Cygwin and MKS NT, are consistent with Linux. * On AIX, Solaris and Linux, bash is consistent, giving the incorrect (from my perspective) result of "flag = false". The following table summarizes the systems the problem: ``` uname -s uname -r which ksh ksh version flag = ======== ======== ========= =========== ====== Linux 2.6.9-55.0.0.0.2.ELsmp /bin/ksh PD KSH v5.2.14 99/07/13.2 false AIX 3 /bin/ksh Version M-11/16/88f true // AIX 5.3 /bin/ksh93 Version M-12/28/93e true SunOS 5.8, 5.9 and 5.10 /bin/ksh Version M-11/16/88i true /usr/dt/bin/dtksh Version M-12/28/93d true HP-UX B.11.11 and B.11.23 /bin/ksh Version 11/16/88 true /usr/dt/bin/dtksh Version M-12/28/93d true CYGWIN_NT-5.1 1.5.25(0.156/4/2) /bin/ksh PD KSH v5.2.14 99/07/13.2 false Windows_NT 5 .../mksnt/ksh.exe Version 8.7.0 build 1859... false // MKS ``` Update ====== After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash. ``` #!/bin/ksh echo "a\nb" > junk flag=false while read x do flag=true done < junk echo "flag = ${flag}" exit 0 ``` Thanks to jj33 for the previously accepted answer.
After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash. ``` #!/bin/ksh echo "a\nb" > junk flag=false while read x do flag=true done < junk echo "flag = ${flag}" exit 0 ``` Thanks to jj33 for the previous accepted answer.
74,385
<p>I need to convert a value which is in a <code>DateTime</code> variable into a <code>varchar</code> variable formatted as <code>yyyy-mm-dd</code> format (without time part).</p> <p>How do I do that?</p>
[ { "answer_id": 74394, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 8, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>CONVERT(varchar(10), [MyDateTimecolumn], 20)\n</code></pre>\n\n<p>For a full da...
2008/09/16
[ "https://Stackoverflow.com/questions/74385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7604/" ]
I need to convert a value which is in a `DateTime` variable into a `varchar` variable formatted as `yyyy-mm-dd` format (without time part). How do I do that?
With Microsoft Sql Server: ``` -- -- Create test case -- DECLARE @myDateTime DATETIME SET @myDateTime = '2008-05-03' -- -- Convert string -- SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10) ```
74,430
<p>I am trying to use the <code>import random</code> statement in python, but it doesn't appear to have any methods in it to use.</p> <p>Am I missing something?</p>
[ { "answer_id": 74445, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 2, "selected": false, "text": "<p>I think you need to give some more information. It's not really possible to answer why it's not working based on the info...
2008/09/16
[ "https://Stackoverflow.com/questions/74430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13050/" ]
I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: ``` >>> import random >>> print random.__file__ ``` That will show you exactly which file is being imported.
74,451
<p>Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the <em>actual</em> name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?</p> <p>Some ways I know, all of which seem quite backwards:</p> <ol> <li>Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself.</li> <li>Get filename from handle (as in <a href="http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx" rel="noreferrer">MSDN example</a>). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files.</li> </ol> <p>Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files").</p> <p>I'm looking for a native solution (not .NET one).</p>
[ { "answer_id": 74563, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 2, "selected": false, "text": "<p>Okay, this is VBScript, but even so I'd suggest using the Scripting.FileSystemObject object</p>\n\n<pre><code>Dim fso\nSet...
2008/09/16
[ "https://Stackoverflow.com/questions/74451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6799/" ]
Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the *actual* name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)? Some ways I know, all of which seem quite backwards: 1. Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself. 2. Get filename from handle (as in [MSDN example](http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx)). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files. Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files"). I'm looking for a native solution (not .NET one).
And hereby I answer my own question, based on [original answer from *cspirz*](https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows#74588). Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point. It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar\_t; that is an exercise for the reader :) ``` std::wstring GetActualPathName( const wchar_t* path ) { // This is quite involved, but the meat is SHGetFileInfo const wchar_t kSeparator = L'\\'; // copy input string because we'll be temporary modifying it in place size_t length = wcslen(path); wchar_t buffer[MAX_PATH]; memcpy( buffer, path, (length+1) * sizeof(path[0]) ); size_t i = 0; std::wstring result; // for network paths (\\server\share\RestOfPath), getting the display // name mangles it into unusable form (e.g. "\\server\share" turns // into "share on server (server)"). So detect this case and just skip // up to two path components if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator ) { int skippedCount = 0; i = 2; // start after '\\' while( i < length && skippedCount < 2 ) { if( buffer[i] == kSeparator ) ++skippedCount; ++i; } result.append( buffer, i ); } // for drive names, just add it uppercased else if( length >= 2 && buffer[1] == L':' ) { result += towupper(buffer[0]); result += L':'; if( length >= 3 && buffer[2] == kSeparator ) { result += kSeparator; i = 3; // start after drive, colon and separator } else { i = 2; // start after drive and colon } } size_t lastComponentStart = i; bool addSeparator = false; while( i < length ) { // skip until path separator while( i < length && buffer[i] != kSeparator ) ++i; if( addSeparator ) result += kSeparator; // if we found path separator, get real filename of this // last path name component bool foundSeparator = (i < length); buffer[i] = 0; SHFILEINFOW info; // nuke the path separator so that we get real name of current path component info.szDisplayName[0] = 0; if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) ) { result += info.szDisplayName; } else { // most likely file does not exist. // So just append original path name component. result.append( buffer + lastComponentStart, i - lastComponentStart ); } // restore path separator that we might have nuked before if( foundSeparator ) buffer[i] = kSeparator; ++i; lastComponentStart = i; addSeparator = true; } return result; } ``` Again, thanks to cspirz for pointing me to SHGetFileInfo.
74,461
<p>I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this?</p> <p>In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way? </p> <p>Included is my code. </p> <p>The Page:</p> <pre><code>&lt;UserControl x:Class="WebServicesApp.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"&gt; &lt;Grid x:Name="LayoutRoot" Background="White"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5"&gt; &lt;ContentControl VerticalAlignment="Center" HorizontalAlignment="Center"&gt; &lt;StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5"&gt; &lt;TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" /&gt; &lt;TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/&gt; &lt;Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True" HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"&gt; &lt;data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False" AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged"&gt; &lt;data:DataGrid.Columns&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /&gt; &lt;!--Width="150"--&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /&gt; &lt;!--Width="500"--&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" /&gt; &lt;/data:DataGrid.Columns&gt; &lt;/data:DataGrid&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed"&gt; &lt;Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" /&gt; &lt;Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000"&gt; &lt;StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" &gt; &lt;ContentControl&gt; &lt;StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal"&gt; &lt;TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" /&gt; &lt;TextBox x:Name="EmailPopupTextBox" Width="200" /&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;ContentControl&gt; &lt;StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0"&gt; &lt;TextBlock Text="Don't send when update was done by:" /&gt; &lt;StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" &gt; &lt;TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" /&gt; &lt;Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" &gt; &lt;Rectangle Fill="White" /&gt; &lt;Border Background="White"&gt; &lt;ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" /&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25"&gt; &lt;Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/&gt; &lt;/Button&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;TextBlock Text="Where Clause Condition:" /&gt; &lt;TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" /&gt; &lt;ContentControl&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" /&gt; &lt;Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" /&gt; &lt;Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" /&gt; &lt;/StackPanel&gt; &lt;TextBlock x:Name="TestContitionResults" Visibility="Collapsed" /&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>And the call that occurs when the grid's selection is changed:</p> <pre><code>Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If mFirstTime Then mFirstTime = False Else Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing If IncidentGrid.SelectedItem IsNot Nothing Then selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) EmailPopupTextBox.Text = selectedGridItem.Address SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID WhereClauseTextBox.Text = selectedGridItem.whereClause IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem) End If If IncidentGrid.SelectedIndex &gt; -1 Then EditPersonPopupGrid.Visibility = Windows.Visibility.Visible Else EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed End If End If End Sub </code></pre> <p>Sorry if my code is atrocious, I'm still learning Silverlight.</p>
[ { "answer_id": 74877, "author": "Senkwe", "author_id": 6419, "author_profile": "https://Stackoverflow.com/users/6419", "pm_score": 3, "selected": true, "text": "<p>That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the <strong>SelectionChan...
2008/09/16
[ "https://Stackoverflow.com/questions/74461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12413/" ]
I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this? In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way? Included is my code. The Page: ``` <UserControl x:Class="WebServicesApp.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5"> <ContentControl VerticalAlignment="Center" HorizontalAlignment="Center"> <StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5"> <TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" /> <TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/> <Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/> </StackPanel> </ContentControl> <Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True" HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"> <data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False" AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged"> <data:DataGrid.Columns> <data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /> <!--Width="150"--> <data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /> <!--Width="500"--> <data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" /> </data:DataGrid.Columns> </data:DataGrid> </Grid> </StackPanel> <Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed"> <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" /> <Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000"> <StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" > <ContentControl> <StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal"> <TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" /> <TextBox x:Name="EmailPopupTextBox" Width="200" /> </StackPanel> </ContentControl> <ContentControl> <StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0"> <TextBlock Text="Don't send when update was done by:" /> <StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" > <TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" /> <Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" > <Rectangle Fill="White" /> <Border Background="White"> <ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" /> </Border> </Grid> </StackPanel> <Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25"> <Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/> </Button> </StackPanel> </ContentControl> <TextBlock Text="Where Clause Condition:" /> <TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" /> <ContentControl> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" /> <Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" /> <Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" /> </StackPanel> <TextBlock x:Name="TestContitionResults" Visibility="Collapsed" /> </StackPanel> </ContentControl> </StackPanel> </Border> </Grid> </Grid> ``` And the call that occurs when the grid's selection is changed: ``` Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If mFirstTime Then mFirstTime = False Else Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing If IncidentGrid.SelectedItem IsNot Nothing Then selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) EmailPopupTextBox.Text = selectedGridItem.Address SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID WhereClauseTextBox.Text = selectedGridItem.whereClause IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem) End If If IncidentGrid.SelectedIndex > -1 Then EditPersonPopupGrid.Visibility = Windows.Visibility.Visible Else EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed End If End If End Sub ``` Sorry if my code is atrocious, I'm still learning Silverlight.
That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the **SelectionChanged** event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item. I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's **SelectedItem** property will be **null** Here's some sample code that at least lives with the issue. Your **SelectionChanged** logic can go in the **if** clause. ``` public partial class Page : UserControl { private Person _currentSelectedPerson; public Page() { InitializeComponent(); List<Person> persons = new List<Person>(); persons.Add(new Person() { Age = 5, Name = "Tom" }); persons.Add(new Person() { Age = 3, Name = "Lisa" }); persons.Add(new Person() { Age = 4, Name = "Sam" }); dg.ItemsSource = persons; } private void SelectionChanged(object sender, EventArgs e) { DataGrid grid = sender as DataGrid; if (grid.SelectedItem != null) { _currentSelectedPerson = grid.SelectedItem as Person; } else { grid.SelectedItem = _currentSelectedPerson; } } } public class Person { public string Name { get; set; } public int Age { get; set; } } ```
74,466
<p>I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon?</p> <pre><code>notifyIcon = new NotifyIcon(); notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded </code></pre>
[ { "answer_id": 74671, "author": "user13125", "author_id": 13125, "author_profile": "https://Stackoverflow.com/users/13125", "pm_score": 8, "selected": true, "text": "<p>Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After ...
2008/09/16
[ "https://Stackoverflow.com/questions/74466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon? ``` notifyIcon = new NotifyIcon(); notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded ```
Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this: ``` System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon(); Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream; icon.Icon = new System.Drawing.Icon( iconStream ); ```
74,471
<p>I have a function that takes, amongst others, a parameter declared as <em>int privateCount</em>. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds!</p> <p>How can a C# compiler allow this, where <em>str</em> is a string?</p> <p><code>str += privateCount +</code> ...</p>
[ { "answer_id": 74495, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 5, "selected": true, "text": "<p>The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:</p>...
2008/09/16
[ "https://Stackoverflow.com/questions/74471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I have a function that takes, amongst others, a parameter declared as *int privateCount*. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds! How can a C# compiler allow this, where *str* is a string? `str += privateCount +` ...
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus: ``` string x = "123" + 45; ``` Gets compiled to: ``` String.Concat("123", 45); ``` Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it. Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op\_Addition) but is handled by the compiler.
74,514
<p>Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this:</p> <pre><code>public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not equal because in C# this cannot be null. if( ReferenceEquals( obj, null ) ) return false; // Compare data to evaluate equality return _data.Equals( obj._data ); } public override bool Equals( object obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null or is of a different types the objects are not equal. if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() ) return false; // Use type-safe equality comparison return Equals( (MyClass)obj ); } public override int GetHashCode() { // Use data's hash code as our hashcode return _data.GetHashCode(); } </code></pre> <p>I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?</p>
[ { "answer_id": 74540, "author": "Peter Ritchie", "author_id": 5620, "author_profile": "https://Stackoverflow.com/users/5620", "pm_score": 0, "selected": false, "text": "<p>It depends on whether you're writing a value type or a reference type. For a sortable value type, I recommend this:...
2008/09/16
[ "https://Stackoverflow.com/questions/74514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12851/" ]
Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this: ``` public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not equal because in C# this cannot be null. if( ReferenceEquals( obj, null ) ) return false; // Compare data to evaluate equality return _data.Equals( obj._data ); } public override bool Equals( object obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null or is of a different types the objects are not equal. if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() ) return false; // Use type-safe equality comparison return Equals( (MyClass)obj ); } public override int GetHashCode() { // Use data's hash code as our hashcode return _data.GetHashCode(); } ``` I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?
I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to override GetHashCode. More info here: <http://gregbeech.com/blog/implementing-object-equality-in-dotnet>
74,570
<p>I'm maintaining <a href="http://perl-begin.org/" rel="nofollow noreferrer">the Perl Beginners' Site</a> and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's <a href="http://www.shlomifish.org/Files/files/images/Computer/Screenshots/perl-begin-bad-artif.png" rel="nofollow noreferrer">an image</a> highlighting the undesired effect.</p> <p>How can I fix the CSS to remedy this problem?</p>
[ { "answer_id": 74610, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<p>It's the <code>background-image</code> on the body showing through. Quick fix (edit style.css or add elsewhere):</p>\n\n<pre><c...
2008/09/16
[ "https://Stackoverflow.com/questions/74570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7709/" ]
I'm maintaining [the Perl Beginners' Site](http://perl-begin.org/) and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's [an image](http://www.shlomifish.org/Files/files/images/Computer/Screenshots/perl-begin-bad-artif.png) highlighting the undesired effect. How can I fix the CSS to remedy this problem?
It's the `background-image` on the body showing through. Quick fix (edit style.css or add elsewhere): ``` #page-container { background-color: white; } ```
74,612
<p>I have a table inside a div. I want the table to occupy the entire width of the div tag.</p> <p>In the CSS, I've set the <code>width</code> of the table to <code>100%</code>. Unfortunately, when the div has some <code>margin</code> on it, the table ends up wider than the div it's in.</p> <p>I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible!</p> <p>I'm using the following DOCTYPE...</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; </code></pre> <hr> <p><strong>Edit</strong>: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).</p>
[ { "answer_id": 74715, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": false, "text": "<p>The following works for me in Firefox and IE7... a guideline, though is: if you set width on an element, don't set margin o...
2008/09/16
[ "https://Stackoverflow.com/questions/74612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475/" ]
I have a table inside a div. I want the table to occupy the entire width of the div tag. In the CSS, I've set the `width` of the table to `100%`. Unfortunately, when the div has some `margin` on it, the table ends up wider than the div it's in. I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible! I'm using the following DOCTYPE... ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` --- **Edit**: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).
Add the below CSS to your `<table>`: ``` table-layout: fixed; width: 100%; ```
74,616
<p>example:</p> <pre><code>public static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items) { items.Keys.Each(key =&gt; { if (items[key] **is IEnumerable&lt;?&gt;**) { /* do something */ } else { /* do something else */ } } </code></pre> <p>Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable&lt;> implements IEnumerable? </p>
[ { "answer_id": 74648, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<pre><code>if (typeof(IEnumerable).IsAssignableFrom(typeof(V))) {\n</code></pre>\n" }, { "answer_id": 74772, ...
2008/09/16
[ "https://Stackoverflow.com/questions/74616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12934/" ]
example: ``` public static void DoSomething<K,V>(IDictionary<K,V> items) { items.Keys.Each(key => { if (items[key] **is IEnumerable<?>**) { /* do something */ } else { /* do something else */ } } ``` Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?
[The previously accepted answer](https://stackoverflow.com/a/74648/1968) is nice but it is wrong. Thankfully, the error is a small one. Checking for `IEnumerable` is not enough if you really want to know about the generic version of the interface; there are a lot of classes that implement only the nongeneric interface. I'll give the answer in a minute. First, though, I'd like to point out that the accepted answer is overly complicated, since the following code would achieve the same under the given circumstances: ``` if (items[key] is IEnumerable) ``` This does even more because it works for each item separately (and not on their common subclass, `V`). Now, for the correct solution. This is a bit more complicated because we have to take the generic type `IEnumerable`1` (that is, the type `IEnumerable<>` with one type parameter) and inject the right generic argument: ``` static bool IsGenericEnumerable(Type t) { var genArgs = t.GetGenericArguments(); if (genArgs.Length == 1 && typeof(IEnumerable<>).MakeGenericType(genArgs).IsAssignableFrom(t)) return true; else return t.BaseType != null && IsGenericEnumerable(t.BaseType); } ``` You can test the correctness of this code easily: ``` var xs = new List<string>(); var ys = new System.Collections.ArrayList(); Console.WriteLine(IsGenericEnumerable(xs.GetType())); Console.WriteLine(IsGenericEnumerable(ys.GetType())); ``` yields: ``` True False ``` Don't be overly concerned by the fact that this uses reflection. While it's true that this adds runtime overhead, so does the use of the `is` operator. Of course the above code is awfully constrained and could be expanded into a more generally applicable method, `IsAssignableToGenericType`. The following implementation is slightly incorrect1 and I’ll leave it here *for historic purposes only*. **Do not use it**. Instead, [James has provided an excellent, correct implementation in his answer.](https://stackoverflow.com/a/1075059/1968) ``` public static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interfaceTypes = givenType.GetInterfaces(); foreach (var it in interfaceTypes) if (it.IsGenericType) if (it.GetGenericTypeDefinition() == genericType) return true; Type baseType = givenType.BaseType; if (baseType == null) return false; return baseType.IsGenericType && baseType.GetGenericTypeDefinition() == genericType || IsAssignableToGenericType(baseType, genericType); } ``` 1 It fails when the `genericType` is the same as `givenType`; for the same reason, it fails for nullable types, i.e. ``` IsAssignableToGenericType(typeof(List<int>), typeof(List<>)) == false IsAssignableToGenericType(typeof(int?), typeof(Nullable<>)) == false ``` I’ve created a [gist with a comprehensive suite of test cases](https://gist.github.com/4174727).
74,620
<p>Can't understand why the following takes place:</p> <pre><code>String date = "06-04-2007 07:05"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date myDate = fmt.parse(date); System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007 long timestamp = myDate.getTime(); System.out.println(timestamp); //1180955100000 -- where are the milliseconds? // on the other hand... myDate = new Date(); System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008 timestamp = myDate.getTime(); System.out.println(timestamp); //1221584564703 -- why, oh, why? </code></pre>
[ { "answer_id": 74652, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": true, "text": "<p>What milliseconds? You are providing only minutes information in the first example, whereas your second example gra...
2008/09/16
[ "https://Stackoverflow.com/questions/74620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
Can't understand why the following takes place: ``` String date = "06-04-2007 07:05"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date myDate = fmt.parse(date); System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007 long timestamp = myDate.getTime(); System.out.println(timestamp); //1180955100000 -- where are the milliseconds? // on the other hand... myDate = new Date(); System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008 timestamp = myDate.getTime(); System.out.println(timestamp); //1221584564703 -- why, oh, why? ```
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for? ``` String date = "06-04-2007 07:05:00.999"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S"); Date myDate = fmt.parse(date); System.out.println(myDate); long timestamp = myDate.getTime(); System.out.println(timestamp); ```
74,649
<p>What is the syntax to declare a type for my compare-function generator in code like the following?</p> <pre><code>var colName:String = ""; // actually assigned in a loop gc.sortCompareFunction = function() : ??WHAT_GOES_HERE?? { var tmp:String = colName; return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); }; }(); </code></pre>
[ { "answer_id": 74743, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 2, "selected": true, "text": "<p>Isn't \"Function\" a data type?</p>\n" }, { "answer_id": 125763, "author": "Brian Hodge", "author_id": 2062...
2008/09/16
[ "https://Stackoverflow.com/questions/74649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
What is the syntax to declare a type for my compare-function generator in code like the following? ``` var colName:String = ""; // actually assigned in a loop gc.sortCompareFunction = function() : ??WHAT_GOES_HERE?? { var tmp:String = colName; return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); }; }(); ```
Isn't "Function" a data type?
74,674
<p>I need to check CPU and memory usage for the server in java, anyone know how it could be done?</p>
[ { "answer_id": 74720, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>If you are using Tomcat, check out <a href=\"https://code.google.com/p/psi-probe/\" rel=\"nofollow noreferrer\">Psi Pr...
2008/09/16
[ "https://Stackoverflow.com/questions/74674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13123/" ]
I need to check CPU and memory usage for the server in java, anyone know how it could be done?
If you are looking specifically for memory in JVM: ``` Runtime runtime = Runtime.getRuntime(); NumberFormat format = NumberFormat.getInstance(); StringBuilder sb = new StringBuilder(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>"); sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>"); sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>"); sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>"); ``` However, these should be taken only as an estimate...
74,723
<p>This problem has been afflicting me for quite a while and it's been really annoying.</p> <p>Every time I login after a reboot/power cycle the explorer takes some time to show up. I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference. The result is always the same: Some of the icons do not show up even if the applications have started.</p> <p>I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort?</p> <hr> <p>Apparently, it looks like Jon was right and it's not possible to do it.</p> <p>I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code):</p> <pre><code>procedure Refresh; var hSysTray: THandle; begin hSysTray := GetSystrayHandle; SendMessage(hSysTray, WM_PAINT, 0, 0); end; function GetSystrayHandle: THandle; var hTray, hNotify, hSysPager: THandle; begin hTray := FindWindow('Shell_TrayWnd', ''); if hTray = 0 then begin Result := hTray; exit; end; hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', ''); if hNotify = 0 then begin Result := hNotify; exit; end; hSyspager := FindWindowEx(hNotify, 0, 'SysPager', ''); if hSyspager = 0 then begin Result := hSyspager; exit; end; Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area'); end;</code></pre> <p>But to no avail.</p> <p>I've even tried with <pre><code>InvalidateRect()</code></pre> and still no show.</p> <p>Any other suggestions?</p>
[ { "answer_id": 74769, "author": "Jonathan Sayce", "author_id": 13153, "author_profile": "https://Stackoverflow.com/users/13153", "pm_score": 2, "selected": false, "text": "<p>As far as I know that isn't possible Gustavo - it's up to each application to put its notifyicon in the systray, ...
2008/09/16
[ "https://Stackoverflow.com/questions/74723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
This problem has been afflicting me for quite a while and it's been really annoying. Every time I login after a reboot/power cycle the explorer takes some time to show up. I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference. The result is always the same: Some of the icons do not show up even if the applications have started. I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort? --- Apparently, it looks like Jon was right and it's not possible to do it. I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code): ``` procedure Refresh; var hSysTray: THandle; begin hSysTray := GetSystrayHandle; SendMessage(hSysTray, WM_PAINT, 0, 0); end; function GetSystrayHandle: THandle; var hTray, hNotify, hSysPager: THandle; begin hTray := FindWindow('Shell_TrayWnd', ''); if hTray = 0 then begin Result := hTray; exit; end; hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', ''); if hNotify = 0 then begin Result := hNotify; exit; end; hSyspager := FindWindowEx(hNotify, 0, 'SysPager', ''); if hSyspager = 0 then begin Result := hSyspager; exit; end; Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area'); end; ``` But to no avail. I've even tried with ``` InvalidateRect() ``` and still no show. Any other suggestions?
Take a look at this blog entry: [REFRESHING THE TASKBAR NOTIFICATION AREA](http://malwareanalysis.com/CommunityServer/blogs/geffner/archive/2008/02/15/985.aspx). I am using this code to refresh the system tray to get rid of orphaned icons and it works perfectly. The blog entry is very informative and gives a great explanation of the steps the author performed to discover his solution. ``` #define FW(x,y) FindWindowEx(x, NULL, y, L"") void RefreshTaskbarNotificationArea() { HWND hNotificationArea; RECT r; GetClientRect( hNotificationArea = FindWindowEx( FW(FW(FW(NULL, L"Shell_TrayWnd"), L"TrayNotifyWnd"), L"SysPager"), NULL, L"ToolbarWindow32", // L"Notification Area"), // Windows XP L"User Promoted Notification Area"), // Windows 7 and up &r); for (LONG x = 0; x < r.right; x += 5) for (LONG y = 0; y < r.bottom; y += 5) SendMessage( hNotificationArea, WM_MOUSEMOVE, 0, (y << 16) + x); } ```
74,782
<p>What's the difference between eruby and erb? What considerations would drive me to choose one or the other?</p> <p>My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this:</p> <pre><code>hostname sample-router &lt;%= r = String.new; [ ["GigabitEthernet1/1", "10.5.16.1"], ["GigabitEthernet1/2", "10.5.17.1"], ["GigabitEthernet1/3", "10.5.18.1"] ].each { |tuple| r &lt;&lt; "interface #{tuple[0]}\n" r &lt;&lt; " ip address #{tuple[1]} netmask 255.255.255.0\n" } r.chomp %&gt; logging 10.5.16.26 </code></pre> <p>which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output:</p> <pre><code>hostname sample-router interface GigabitEthernet1/1 ip address 10.5.16.1 netmask 255.255.255.0 interface GigabitEthernet1/2 ip address 10.5.17.1 netmask 255.255.255.0 interface GigabitEthernet1/3 ip address 10.5.18.1 netmask 255.255.255.0 logging 10.5.16.26 </code></pre>
[ { "answer_id": 74807, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 3, "selected": false, "text": "<p>Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster.</p>\n\n<...
2008/09/16
[ "https://Stackoverflow.com/questions/74782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13157/" ]
What's the difference between eruby and erb? What considerations would drive me to choose one or the other? My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this: ``` hostname sample-router <%= r = String.new; [ ["GigabitEthernet1/1", "10.5.16.1"], ["GigabitEthernet1/2", "10.5.17.1"], ["GigabitEthernet1/3", "10.5.18.1"] ].each { |tuple| r << "interface #{tuple[0]}\n" r << " ip address #{tuple[1]} netmask 255.255.255.0\n" } r.chomp %> logging 10.5.16.26 ``` which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output: ``` hostname sample-router interface GigabitEthernet1/1 ip address 10.5.16.1 netmask 255.255.255.0 interface GigabitEthernet1/2 ip address 10.5.17.1 netmask 255.255.255.0 interface GigabitEthernet1/3 ip address 10.5.18.1 netmask 255.255.255.0 logging 10.5.16.26 ```
Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster. erubis (a third one) is pure ruby, and faster than both the ones listed above. But I doubt the speed of that is the bottleneck for you, so just use erb. It's part of Ruby Standard Library.
74,829
<p>What should I type on the Mac OS X terminal to run a script as root?</p>
[ { "answer_id": 74830, "author": "Bob Wintemberg", "author_id": 12999, "author_profile": "https://Stackoverflow.com/users/12999", "pm_score": 2, "selected": false, "text": "<p>sudo ./<em>scriptname</em></p>\n" }, { "answer_id": 74833, "author": "dF.", "author_id": 3002, ...
2008/09/16
[ "https://Stackoverflow.com/questions/74829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
What should I type on the Mac OS X terminal to run a script as root?
As in any unix-based environment, you can use the [`sudo`](http://xkcd.com/149/) command: ``` $ sudo script-name ``` It will ask for your password (your own, not a separate `root` password).
74,847
<p>Typically I use <code>E_ALL</code> to see anything that PHP might say about my code to try and improve it.</p> <p>I just noticed a error constant <code>E_STRICT</code>, but have never used or heard about it, is this a good setting to use for development? The manual says:</p> <blockquote> <p>Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. </p> </blockquote> <p>So I'm wondering if I'm using the best <code>error_reporting</code> level with <code>E_ALL</code> or would that along with <code>E_STRICT</code> be the best? Or is there any other combination I've yet to learn?</p>
[ { "answer_id": 74864, "author": "Tim Boland", "author_id": 70, "author_profile": "https://Stackoverflow.com/users/70", "pm_score": -1, "selected": false, "text": "<p>ini_set(\"display_errors\",\"2\");\nERROR_REPORTING(E_ALL);</p>\n" }, { "answer_id": 74907, "author": "Daniel ...
2008/09/16
[ "https://Stackoverflow.com/questions/74847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
Typically I use `E_ALL` to see anything that PHP might say about my code to try and improve it. I just noticed a error constant `E_STRICT`, but have never used or heard about it, is this a good setting to use for development? The manual says: > > Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. > > > So I'm wondering if I'm using the best `error_reporting` level with `E_ALL` or would that along with `E_STRICT` be the best? Or is there any other combination I've yet to learn?
In PHP 5, the things covered by `E_STRICT` are not covered by `E_ALL`, so to get the most information, you need to combine them: ``` error_reporting(E_ALL | E_STRICT); ``` In PHP 5.4, `E_STRICT` will be included in `E_ALL`, so you can use just `E_ALL`. You can also use ``` error_reporting(-1); ``` which will always enable *all* errors. Which is more semantically correct as: ``` error_reporting(~0); ```
74,880
<p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:</p> <pre><code> SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } </code></pre> <p>Then, when WorkerMethod() is complete, run this:</p> <p><pre><code> void SomeOtherMethod() // Also member of AClass{} { ... } </pre></code></p> <p>Can anyone please give an example of that? </p>
[ { "answer_id": 74917, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>Check out BackgroundWorker.</p>\n" }, { "answer_id": 74948, "author": "Isak Savo", "author_id": 8521, ...
2008/09/16
[ "https://Stackoverflow.com/questions/74880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10505/" ]
Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#: ``` SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } ``` Then, when WorkerMethod() is complete, run this: ``` void SomeOtherMethod() // Also member of AClass{} { ... } ``` Can anyone please give an example of that?
The [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class was added to .NET 2.0 for this exact purpose. In a nutshell you do: ``` BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { myBClass.DoHardWork(); } worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod); worker.RunWorkerAsync(); ``` You can also add fancy stuff like cancellation and progress reporting if you want :)
74,883
<p>I cannot seem to compile mod_dontdothat on Windows. Has anybody managed to achieve this?</p> <p>Edit:</p> <p>I've tried compiling the file according to the readme on the site and I've tried to add extra libs to reduce the link errors. Ive got the following installed:</p> <ol> <li>Apache 2.2.9</li> <li>Visual Studio 2008</li> <li>ActivePerl</li> <li>apxs-win32 from ApacheLounge</li> <li>Subversion libs and headers</li> </ol> <p>I run the following command line:</p> <pre> C:\Program Files\Apache Software Foundation\Apache2.2\bin>apxs -c -I ..\include\ svn_config.h -L ..\lib -L C:\Progra~1\Micros~1.0\VC\lib -l apr-1.lib -l aprutil- 1.lib -l svn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l l ibsvn_subr-1.lib -l mod_dav.lib mod_dontdothat.c </pre> <p>Then I get the following errors:</p> <pre> cl /nologo /MD /W3 /O2 /D WIN32 /D _WINDOWS /D NDEBUG -I"C:\PROGRA~1\APACHE~ 1\Apache2.2\include" /I"..\include\svn_config.h" /c /Fomod_dontdothat.lo mod_d ontdothat.c mod_dontdothat.c link kernel32.lib /nologo /subsystem:windows /dll /machine:I386 /libpath:"C:\PRO GRA~1\APACHE~1\Apache2.2\lib" /out:mod_dontdothat.so /libpath:"..\lib" /libpat h:"C:\Progra~1\Micros~1.0\VC\lib" apr-1.lib aprutil-1.lib svn_subr-1.lib libapr -1.lib libaprutil-1.lib libhttpd.lib libsvn_subr-1.lib mod_dav.lib mod_dontdot hat.lo Creating library mod_dontdothat.lib and object mod_dontdothat.exp mod_dontdothat.lo : error LNK2019: unresolved external symbol _dav_svn_split_uri @32 referenced in function _is_this_legal svn_subr-1.lib(io.obj) : error LNK2001: unresolved external symbol __imp__libint l_dgettext svn_subr-1.lib(subst.obj) : error LNK2001: unresolved external symbol __imp__lib intl_dgettext svn_subr-1.lib(config_auth.obj) : error LNK2001: unresolved external symbol __im p__libintl_dgettext svn_subr-1.lib(time.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(nls.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(dso.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(prompt.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(error.obj) : error LNK2019: unresolved external symbol __imp__lib intl_dgettext referenced in function _print_error svn_subr-1.lib(config.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(cmdline.obj) : error LNK2001: unresolved external symbol __imp__l ibintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2019: unresolved external symbol __imp__libin tl_sprintf referenced in function _fuzzy_escape svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_sprintf svn_subr-1.lib(cmdline.obj) : error LNK2019: unresolved external symbol __imp__l ibintl_fprintf referenced in function _svn_cmdline_init svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathA@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathW@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegCloseKey@4 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumKeyExA@32 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegOpenKeyExA@20 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegQueryValueExA@24 referenced in function _parse_section svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumValueA@32 referenced in function _parse_section svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoUninitialize@0 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoInitializeEx@8 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoCreateInstance@20 referenced in function _get_page_id_from_name svn_subr-1.lib(nls.obj) : error LNK2019: unresolved external symbol __imp__libin tl_bindtextdomain referenced in function _svn_nls_init svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflate referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateI nit_ referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflate referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateI nit_ referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateE nd referenced in function _close_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateE nd referenced in function _close_handler_gz mod_dontdothat.so : fatal error LNK1120: 21 unresolved externals apxs:Error: Command failed with rc=6291456 . </pre> <p>I'm not too much of a C guru, so any help in finding these unresolved external symbols will be much appreciated!</p>
[ { "answer_id": 77964, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 1, "selected": false, "text": "<p>Thanks for revising the question.</p>\n\n<p>It looks like a definite linker issue. I see that the first undefined sym...
2008/09/16
[ "https://Stackoverflow.com/questions/74883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822/" ]
I cannot seem to compile mod\_dontdothat on Windows. Has anybody managed to achieve this? Edit: I've tried compiling the file according to the readme on the site and I've tried to add extra libs to reduce the link errors. Ive got the following installed: 1. Apache 2.2.9 2. Visual Studio 2008 3. ActivePerl 4. apxs-win32 from ApacheLounge 5. Subversion libs and headers I run the following command line: ``` C:\Program Files\Apache Software Foundation\Apache2.2\bin>apxs -c -I ..\include\ svn_config.h -L ..\lib -L C:\Progra~1\Micros~1.0\VC\lib -l apr-1.lib -l aprutil- 1.lib -l svn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l l ibsvn_subr-1.lib -l mod_dav.lib mod_dontdothat.c ``` Then I get the following errors: ``` cl /nologo /MD /W3 /O2 /D WIN32 /D _WINDOWS /D NDEBUG -I"C:\PROGRA~1\APACHE~ 1\Apache2.2\include" /I"..\include\svn_config.h" /c /Fomod_dontdothat.lo mod_d ontdothat.c mod_dontdothat.c link kernel32.lib /nologo /subsystem:windows /dll /machine:I386 /libpath:"C:\PRO GRA~1\APACHE~1\Apache2.2\lib" /out:mod_dontdothat.so /libpath:"..\lib" /libpat h:"C:\Progra~1\Micros~1.0\VC\lib" apr-1.lib aprutil-1.lib svn_subr-1.lib libapr -1.lib libaprutil-1.lib libhttpd.lib libsvn_subr-1.lib mod_dav.lib mod_dontdot hat.lo Creating library mod_dontdothat.lib and object mod_dontdothat.exp mod_dontdothat.lo : error LNK2019: unresolved external symbol _dav_svn_split_uri @32 referenced in function _is_this_legal svn_subr-1.lib(io.obj) : error LNK2001: unresolved external symbol __imp__libint l_dgettext svn_subr-1.lib(subst.obj) : error LNK2001: unresolved external symbol __imp__lib intl_dgettext svn_subr-1.lib(config_auth.obj) : error LNK2001: unresolved external symbol __im p__libintl_dgettext svn_subr-1.lib(time.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(nls.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(dso.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(prompt.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(error.obj) : error LNK2019: unresolved external symbol __imp__lib intl_dgettext referenced in function _print_error svn_subr-1.lib(config.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(cmdline.obj) : error LNK2001: unresolved external symbol __imp__l ibintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2019: unresolved external symbol __imp__libin tl_sprintf referenced in function _fuzzy_escape svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_sprintf svn_subr-1.lib(cmdline.obj) : error LNK2019: unresolved external symbol __imp__l ibintl_fprintf referenced in function _svn_cmdline_init svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathA@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathW@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegCloseKey@4 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumKeyExA@32 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegOpenKeyExA@20 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegQueryValueExA@24 referenced in function _parse_section svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumValueA@32 referenced in function _parse_section svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoUninitialize@0 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoInitializeEx@8 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoCreateInstance@20 referenced in function _get_page_id_from_name svn_subr-1.lib(nls.obj) : error LNK2019: unresolved external symbol __imp__libin tl_bindtextdomain referenced in function _svn_nls_init svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflate referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateI nit_ referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflate referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateI nit_ referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateE nd referenced in function _close_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateE nd referenced in function _close_handler_gz mod_dontdothat.so : fatal error LNK1120: 21 unresolved externals apxs:Error: Command failed with rc=6291456 . ``` I'm not too much of a C guru, so any help in finding these unresolved external symbols will be much appreciated!
I managed to compile the module. Prerequisites: * Apache 2.2.11 * [apxs-win32](http://www.apachelounge.com/download/apxs_win32.zip) from www.apachelounge.com * Visual Studio 2005 * [Active Perl 5.8.8](http://www.activestate.com/activeperl/) (you need perl for apxs-win32 installation) Here is a step-by-step guide. Download these packages: * <http://subversion.tigris.org/files/documents/15/44595/svn-win32-1.5.5_dev.zip> (we need the libraries and header files from this package) * <http://subversion.tigris.org/downloads/subversion-1.5.5.zip> (we will be using the `mod_dav_svn` sources to compile a static lib) Unpack the dev package to `c:\temp\svn` and the other package to `c:\temp\svn-src` and the `mod_dontdothat` files to `C:\Temp\dontdothat`. One of the dependencies of `mod_dontdothat` module is `mod_dav_svn` module. Unfortunately you'll find the `mod_dav_svn` binary only as a shared library (DLL). You cannot link against a DLL. So the first step is to build a static `mod_dav_svn` library: ``` cd C:\Temp\svn-src\subversion\mod_dav_svn apxs -c -I ..\include -L C:\Temp\svn\lib -l libsvn_delta-1.lib -l libsvn_diff-1.lib -l libsvn_fs-1.lib -l libsvn_fs_base-1.lib -l libsvn_fs_fs-1.lib -l libsvn_fs_util-1.lib -l libsvn_repos-1.lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -n mod_dav_svn mod_dav_svn.c activity.c authz.c deadprops.c liveprops.c lock.c merge.c mirror.c repos.c util.c version.c reports\dated-rev.c reports\file-revs.c reports\get-locations.c reports\get-location-segments.c reports\get-locks.c reports\log.c reports\mergeinfo.c reports\replay.c reports\update.c ``` The apxs call will print the commands it executes. The last command is a link call which builds the DLL. Copy it replace "link" by "lib", remove the "/dll" param, and change the "out" param file name to "`libmod_dav_svn.lib`". You should get something similar to: ``` lib kernel32.lib /nologo /subsystem:windows /machine:I386 /libpath:"C:\PROGRA~1\APACHE~1\Apache2.2\lib" /out:libmod_dav_svn.lib /libpath:"C:\Temp\svn\lib" libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_fs_util-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libapr-1.lib libaprutil-1.lib libhttpd.lib mod_dav.lib xml.lib reports\update.lo reports\replay.lo reports\mergeinfo.lo reports\log.lo reports\get-locks.lo reports\get-location-segments.lo reports\get-locations.lo reports\file-revs.lo reports\dated-rev.lo version.lo util.lo repos.lo mirror.lo merge.lo lock.lo liveprops.lo deadprops.lo authz.lo activity.lo mod_dav_svn.lo ``` You will get some link warnings. You can ignore them. Copy the `libmod_dav_svn.lib` to the `mod_dontdothat` directory. Now start the compilation process for `mod_dontdothat`: ``` C:\Temp\dontdothat apxs -c -I C:\Temp\svn\include -L C:\Temp\svn\lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -l libmod_dav_svn.lib mod_dontdothat.c apxs -i -n dontdothat mod_dontdothat.so ``` This should do the trick.
74,886
<p>I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).</p> <p>So I need to do something like:</p> <pre><code>sudo mv backup/gem/foo gem/ sudo mv backup/doc/foo doc/ sudo mv backup/specification/foo.gemspec specification/ </code></pre> <p>replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?</p>
[ { "answer_id": 74920, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 4, "selected": true, "text": "<p>Put the following into a file named <code>gemmove</code>:</p>\n<pre><code>#!/bin/bash\n\nif [ &quot;x$1&quot; == x ]; then\n e...
2008/09/16
[ "https://Stackoverflow.com/questions/74886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10071/" ]
I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one). So I need to do something like: ``` sudo mv backup/gem/foo gem/ sudo mv backup/doc/foo doc/ sudo mv backup/specification/foo.gemspec specification/ ``` replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?
Put the following into a file named `gemmove`: ``` #!/bin/bash if [ "x$1" == x ]; then echo "Must have an arg" exit 1 fi for d in gem doc specification ; do mv "backup/$d/$1" "$d" done ``` then do ``` chmod a+x gemmove ``` and then call `sudo /path/to/gemmove foo` to move the foo gem from the backup dirs into the real ones
74,902
<p>I installed Mono on my iMac last night and I immidiately had a change of heart! I don't think Mono is ready for prime time. </p> <p>The Mono website says to run the following script to uninstall:</p> <pre><code>#!/bin/sh -x #This script removes Mono from an OS X System. It must be run as root rm -r /Library/Frameworks/Mono.framework rm -r /Library/Receipts/MonoFramework-SVN.pkg cd /usr/bin for i in `ls -al | grep Mono | awk '{print $9}'`; do rm ${i} done </code></pre> <p>Has anyone had to uninstall Mono? Was it as straight forward as running the above script or do I have to do more? How messy was it? Any pointers are appreciated.</p>
[ { "answer_id": 74919, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 0, "selected": false, "text": "<p>Mono doesn't contain a lot of fluff, so just running those commands will be fine. It's as simple as deleting all the d...
2008/09/16
[ "https://Stackoverflow.com/questions/74902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
I installed Mono on my iMac last night and I immidiately had a change of heart! I don't think Mono is ready for prime time. The Mono website says to run the following script to uninstall: ``` #!/bin/sh -x #This script removes Mono from an OS X System. It must be run as root rm -r /Library/Frameworks/Mono.framework rm -r /Library/Receipts/MonoFramework-SVN.pkg cd /usr/bin for i in `ls -al | grep Mono | awk '{print $9}'`; do rm ${i} done ``` Has anyone had to uninstall Mono? Was it as straight forward as running the above script or do I have to do more? How messy was it? Any pointers are appreciated.
The above script simply deletes everything related to Mono on your system -- and since the developers wrote it, I'm sure they didn't miss anything :) Unlike some other operating systems made by software companies that rhyme with "Macrosoft", uninstalling software in OS X is as simple as deleting the files, 99% of the time.. no registry or anything like that. So, long story short, yes, that script is probably the only thing you need to do.
74,928
<p>I'm trying to figure out the best way to parse a GE Logician MEL trace file to make it easier to read.</p> <p>It has segments like </p> <pre>>{!gDYNAMIC_3205_1215032915_810 = (clYN)} execute>GDYNAMIC_3205_1215032915_810 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" >{!gDYNAMIC_3205_1215032893_294 = (clYN)} execute>GDYNAMIC_3205_1215032893_294 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" </pre> <p>and</p> <pre>>{IF (STR(F3205_1220646638_285, F3205_1220646638_301) == "") THEN "" ELSE (\par\tab fnHeadingFormat("Depression") + CFMT(F3205_1220646638_285, "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") + CFMT(F3205_1220646638_301, "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") ) ENDIF} execute>call STR("No", "No") results>"NoNo" execute>"NoNo" == "" results>FALSE execute>if FALSE results>FALSE execute>call FNHEADINGFORMAT("Depression") execute>call CFMT("Depression", "B,2") results>"\fs24\b Depression\b0\fs20 " execute>"\r\n" + "\fs24\b Depression\b0\fs20 " results>"\r\n\fs24\b Depression\b0\fs20 " execute>"\r\n\fs24\b Depression\b0\fs20 " + "\r\n" results>"\r\n\fs24\b Depression\b0\fs20 \r\n" results>return "\r\n\fs24\b Depression\b0\fs20 \r\n" execute>call CFMT("No", "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") results>"\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n" + "\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>call CFMT("No", "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") results>"\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " + "\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par \b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " </pre> <p>I could grovel through doing it procedurally, but after all the regexps I've worked with, I find it hard to believe there's nothing out there that will let me define the rules for parsing the file in a similar manner. Am I wrong?</p>
[ { "answer_id": 74942, "author": "metadave", "author_id": 7237, "author_profile": "https://Stackoverflow.com/users/7237", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.antlr.org\" rel=\"nofollow noreferrer\">Antlr</a> would do the trick.</p>\n" }, { "answer_id...
2008/09/16
[ "https://Stackoverflow.com/questions/74928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2531/" ]
I'm trying to figure out the best way to parse a GE Logician MEL trace file to make it easier to read. It has segments like ``` >{!gDYNAMIC_3205_1215032915_810 = (clYN)} execute>GDYNAMIC_3205_1215032915_810 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" >{!gDYNAMIC_3205_1215032893_294 = (clYN)} execute>GDYNAMIC_3205_1215032893_294 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" ``` and ``` >{IF (STR(F3205_1220646638_285, F3205_1220646638_301) == "") THEN "" ELSE (\par\tab fnHeadingFormat("Depression") + CFMT(F3205_1220646638_285, "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") + CFMT(F3205_1220646638_301, "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") ) ENDIF} execute>call STR("No", "No") results>"NoNo" execute>"NoNo" == "" results>FALSE execute>if FALSE results>FALSE execute>call FNHEADINGFORMAT("Depression") execute>call CFMT("Depression", "B,2") results>"\fs24\b Depression\b0\fs20 " execute>"\r\n" + "\fs24\b Depression\b0\fs20 " results>"\r\n\fs24\b Depression\b0\fs20 " execute>"\r\n\fs24\b Depression\b0\fs20 " + "\r\n" results>"\r\n\fs24\b Depression\b0\fs20 \r\n" results>return "\r\n\fs24\b Depression\b0\fs20 \r\n" execute>call CFMT("No", "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") results>"\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n" + "\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>call CFMT("No", "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") results>"\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " + "\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par \b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " ``` I could grovel through doing it procedurally, but after all the regexps I've worked with, I find it hard to believe there's nothing out there that will let me define the rules for parsing the file in a similar manner. Am I wrong?
Make a grammar using ANTLR. If you're using C, lex/yacc are native. ANTLR creates native parsers in Java, Python and .NET. Your output looks like a repl; try asking the vendor for a spec on the input language.
74,951
<p>Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself. What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image.</p> <p><strong>So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?</strong></p>
[ { "answer_id": 75541, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution:</p>\n\n...
2008/09/16
[ "https://Stackoverflow.com/questions/74951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself. What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image. **So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?**
It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution: The list: ``` <List> <mouseDown>onListMouseDown(event)</mouseDown> </Tree> ``` The mouse down handler: ``` private function onMouseDown( event : MouseEvent ) : void { var list : List = List(event.currentTarget); // the data of the clicked row, change the name of the class to your own var item : MyDataType = MyDataType(list.selectedItem); var source : DragSource = new DragSource(); // MyAwsomeDragFormat is the key that you will retrieve the data by in the // component that handles the drop source.addData(item, "MyAwsomeDragFormat"); // this is the component that will be shown as the drag proxy image var dragView : UIComponent = new Image(); // set the source of the image to a bigger version here dragView.source = getABiggerImage(item); // get hold of the renderer of the clicked row, to use as the drag initiator var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex)); DragManager.doDrag( rowRenderer, source, event, dragView ); } ``` That will start the drag when the user clicks an item in the list. Notice that I don't set `dragEnabled` and the other drag-related properties on the list since I handle all that myself. It can be useful to add this to the beginning of the event handler: ``` if ( event.target is ScrollThumb || event.target is Button ) { return; } ``` Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.
74,957
<p>In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in <code>$arrayOfStringsNotInterestedIn</code>.</p> <p>What is the syntax for this?</p> <pre><code> Get-Content $filename | Foreach-Object {$_} </code></pre>
[ { "answer_id": 75034, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 4, "selected": false, "text": "<p>You can use the -notmatch operator to get the lines that don't have the characters you are interested in. </p>\n\n<pre...
2008/09/16
[ "https://Stackoverflow.com/questions/74957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in `$arrayOfStringsNotInterestedIn`. What is the syntax for this? ``` Get-Content $filename | Foreach-Object {$_} ```
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains: ``` Get-Content $FileName | foreach-object { ` if ($arrayofStringsNotInterestedIn -notcontains $_) { $) } ``` or better (IMO) ``` Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_} ```
74,960
<p>I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious:</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"&gt; &lt;soapenv:Body&gt; &lt;ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface"&gt; &lt;newKeys&gt; &lt;value&gt;1234&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys&gt; &lt;value&gt;2345&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys&gt; &lt;value&gt;3456&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/&gt; &lt;newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/&gt; &lt;errors&gt;Error1&lt;/errors&gt; &lt;errors&gt;Error2&lt;/errors&gt; &lt;/ns1:CreateEntityTypesResponse&gt; &lt;/soapenv:Body&gt; &lt;/soapenv:Envelope&gt; </code></pre> <p>I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once.</p> <p>I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.</p>
[ { "answer_id": 75128, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 3, "selected": false, "text": "<h3>Using WSDL2Java</h3>\n\n<p>If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates f...
2008/09/16
[ "https://Stackoverflow.com/questions/74960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13224/" ]
I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious: ``` <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"> <soapenv:Body> <ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface"> <newKeys> <value>1234</value> </newKeys> <newKeys> <value>2345</value> </newKeys> <newKeys> <value>3456</value> </newKeys> <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <errors>Error1</errors> <errors>Error2</errors> </ns1:CreateEntityTypesResponse> </soapenv:Body> </soapenv:Envelope> ``` I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once. I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.
### Using WSDL2Java If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates for you. However you can try to change the skeleton in this section: ``` // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope( getFactory(_operationClient.getOptions().getSoapVersionURI()), methodName, optimizeContent(new javax.xml.namespace.QName ("http://tempuri.org/","methodName"))); //adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); ``` To add the namespace to the envelope add these lines somewhere in there: ``` OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()). createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi"); env.declareNamespace(xsi); ``` ### Hand-coded If you are "hand-coding" the service you might do something like this: ``` SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope envelope = fac.getDefaultEnvelope(); OMNamespace xsi = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi"); envelope.declareNamespace(xsi); OMNamespace methodNs = fac.createOMNamespace("http://somedomain.com/wsinterface", "ns1"); OMElement method = fac.createOMElement("CreateEntityTypesResponse", methodNs); //add the newkeys and errors as OMElements here... ``` ### Exposing service in aar If you are creating a service inside an aar you may be able to influence the SOAP message produced by using the target namespace or schema namespace properties (see [this article](http://wso2.org/library/2060)). Hope that helps.
75,011
<p>In a VB6 application, I have a <code>Dictionary</code> whose keys are <code>String</code>s and values are instances of a custom class. If I call <code>RemoveAll()</code> on the <code>Dictionary</code>, will it first free the custom objects? Or do I explicitly need to do this myself?</p> <pre><code>Dim d as Scripting.Dictionary d("a") = New clsCustom d("b") = New clsCustom ' Are these two lines necessary? Set d("a") = Nothing Set d("b") = Nothing d.RemoveAll </code></pre>
[ { "answer_id": 75066, "author": "Neil C. Obremski", "author_id": 9642, "author_profile": "https://Stackoverflow.com/users/9642", "pm_score": 3, "selected": true, "text": "<p>Yes, all objects in the <code>Dictionary</code> will be released after a call to <code>RemoveAll()</code>. From a...
2008/09/16
[ "https://Stackoverflow.com/questions/75011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863/" ]
In a VB6 application, I have a `Dictionary` whose keys are `String`s and values are instances of a custom class. If I call `RemoveAll()` on the `Dictionary`, will it first free the custom objects? Or do I explicitly need to do this myself? ``` Dim d as Scripting.Dictionary d("a") = New clsCustom d("b") = New clsCustom ' Are these two lines necessary? Set d("a") = Nothing Set d("b") = Nothing d.RemoveAll ```
Yes, all objects in the `Dictionary` will be released after a call to `RemoveAll()`. From a performance (as in speed) standpoint I would say those lines setting the variables to `Nothing` are unnecessary, because the code has to first look them up based on the key names whereas `RemoveAll()` will enumerate and release everything in one loop.
75,052
<p>I have a flash player that has a set of songs loaded via an xml file.</p> <p>The files dont start getting stream until you pick one.</p> <p>If I quickly cycle through each of the 8 files, then flash starts trying to download each of the 8 files at the same time.</p> <p>I'm wondering if there is a way to clear the file that is being downloaded. So that bandwidth is not eaten up if someone decides to click on lots of track names.</p> <p>Something like mySound.clear would be great, or mySound.stopStreaming..</p> <p>Has anyone had this problem before?</p> <p>Regards,</p> <p>Chris</p>
[ { "answer_id": 75323, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 0, "selected": false, "text": "<p>If you do something like:</p>\n\n<p>MySoundObject = undefined;</p>\n\n<p>That should do it.</p>\n" }, { "answer_id":...
2008/09/16
[ "https://Stackoverflow.com/questions/75052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6822/" ]
I have a flash player that has a set of songs loaded via an xml file. The files dont start getting stream until you pick one. If I quickly cycle through each of the 8 files, then flash starts trying to download each of the 8 files at the same time. I'm wondering if there is a way to clear the file that is being downloaded. So that bandwidth is not eaten up if someone decides to click on lots of track names. Something like mySound.clear would be great, or mySound.stopStreaming.. Has anyone had this problem before? Regards, Chris
Check out [Sound.Close()](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()). From the docs: "*Closes the stream, causing any download of data to cease. No data may be read from the stream after the close() method is called.*" This is the [source code example](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()) from the linked docs: ``` package { import flash.display.Sprite; import flash.net.URLRequest; import flash.media.Sound; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.events.MouseEvent; import flash.errors.IOError; import flash.events.IOErrorEvent; public class Sound_closeExample extends Sprite { private var snd:Sound = new Sound(); private var button:TextField = new TextField(); private var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); public function Sound_closeExample() { button.x = 10; button.y = 10; button.text = "START"; button.border = true; button.background = true; button.selectable = false; button.autoSize = TextFieldAutoSize.LEFT; button.addEventListener(MouseEvent.CLICK, clickHandler); this.addChild(button); } private function clickHandler(e:MouseEvent):void { if(button.text == "START") { snd.load(req); snd.play(); snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); button.text = "STOP"; } else if(button.text == "STOP") { try { snd.close(); button.text = "Wait for loaded stream to finish."; } catch (error:IOError) { button.text = "Couldn't close stream " + error.message; } } } private function errorHandler(event:IOErrorEvent):void { button.text = "Couldn't load the file " + event.text; } } } ```
75,057
<p>What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?</p> <p>One idea I had (in python)</p> <pre><code>def validate_password(passwd): conditions_met = 0 conditions_total = 3 if len(passwd) &gt;= 6: if passwd.lower() != passwd: conditions_met += 1 if len([x for x in passwd if x.isdigit()]) &gt; 0: conditions_met += 1 if len([x for x in passwd if not x.isalnum()]) &gt; 0: conditions_met += 1 result = False print conditions_met if conditions_met &gt;= 2: result = True return result </code></pre>
[ { "answer_id": 75108, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": -1, "selected": false, "text": "<p>Password strength checkers, and if you have time+resources (its justified only if you are checking for more than...
2008/09/16
[ "https://Stackoverflow.com/questions/75057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13099/" ]
What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form? One idea I had (in python) ``` def validate_password(passwd): conditions_met = 0 conditions_total = 3 if len(passwd) >= 6: if passwd.lower() != passwd: conditions_met += 1 if len([x for x in passwd if x.isdigit()]) > 0: conditions_met += 1 if len([x for x in passwd if not x.isalnum()]) > 0: conditions_met += 1 result = False print conditions_met if conditions_met >= 2: result = True return result ```
**1: Eliminate often used passwords** Check the entered passwords against a list of often used passwords (see e.g. the top 100.000 passwords in the leaked LinkedIn password list: <http://www.adeptus-mechanicus.com/codex/linkhap/combo_not.zip>), make sure to include [leetspeek substitutions](http://www.gamehouse.com/blog/leet-speak-cheat-sheet/): A@, E3, B8, S5, etc. Remove parts of the password that hit against this list from the entered phrase, before going to part 2 below. **2: Don't force any rules on the user** The golden rule of passwords is that longer is better. Forget about forced use of caps, numbers, and symbols because (the vast majority of) users will: - Make the first letter a capital; - Put the number `1` at the end; - Put a `!` after that if a symbol is required. **Instead check password strength** For a decent starting point see: <http://www.passwordmeter.com/> I suggest as a minimum the following rules: ``` Additions (better passwords) ----------------------------- - Number of Characters Flat +(n*4) - Uppercase Letters Cond/Incr +((len-n)*2) - Lowercase Letters Cond/Incr +((len-n)*2) - Numbers Cond +(n*4) - Symbols Flat +(n*6) - Middle Numbers or Symbols Flat +(n*2) - Shannon Entropy Complex *EntropyScore Deductions (worse passwords) ----------------------------- - Letters Only Flat -n - Numbers Only Flat -(n*16) - Repeat Chars (Case Insensitive) Complex - - Consecutive Uppercase Letters Flat -(n*2) - Consecutive Lowercase Letters Flat -(n*2) - Consecutive Numbers Flat -(n*2) - Sequential Letters (3+) Flat -(n*3) - Sequential Numbers (3+) Flat -(n*3) - Sequential Symbols (3+) Flat -(n*3) - Repeated words Complex - - Only 1st char is uppercase Flat -n - Last (non symbol) char is number Flat -n - Only last char is symbol Flat -n ``` Just following [passwordmeter](http://www.passwordmeter.com/) is not enough, because sure enough its naive algorithm sees `Password1!` as good, whereas it is exceptionally weak. Make sure to disregard initial capital letters when scoring as well as trailing numbers and symbols (as per the last 3 rules). **Calculating Shannon entropy** See: [Fastest way to compute entropy in Python](https://stackoverflow.com/questions/15450192/fastest-way-to-compute-entropy-in-python) **3: Don't allow any passwords that are too weak** Rather than forcing the user to bend to self-defeating rules, allow anything that will give a high enough score. How high depends on your use case. **And most importantly** When you accept the password and store it in a database, [make sure to salt and hash it!](https://stackoverflow.com/questions/4578431/how-to-hash-and-salt-passwords).
75,076
<p>I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe%28v=vs.71%29.aspx" rel="noreferrer">StackFrame class</a> and then to reflect over a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo%28v=vs.71%29.aspx" rel="noreferrer">ParameterInfo</a> array. I've had success with reflection and properties, but this is proving a bit trickier.</p> <p>Is there an approach for achieving this?</p> <p>The code so far looks like this:</p> <pre><code>class Program { static void Main(string[] args) { A a = new A(); a.Go(1); } } public class A { internal void Go(int x) { B b = new B(); b.Go(4); } } public class B { internal void Go(int y) { Console.WriteLine(GetStackTrace()); } public static string GetStackTrace() { StringBuilder sb = new StringBuilder(); StackTrace st = new StackTrace(true); StackFrame[] frames = st.GetFrames(); foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name); ParameterInfo[] paramaters = method.GetParameters(); foreach (ParameterInfo paramater in paramaters) { sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString()); } sb.AppendLine(); } return sb.ToString(); } } </code></pre> <h2>The output looks like this:</h2> <pre><code>SfApp.B - GetStackTrace SfApp.B - Go y: Int32 y SfApp.A - Go x: Int32 x SfApp.Program - Main args: System.String[] args </code></pre> <h2>I'd like it to look more like this:</h2> <pre><code>SfApp.B - GetStackTrace SfApp.B - Go y: 4 SfApp.A - Go x: 1 SfApp.Program - Main </code></pre> <hr/> <p>Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.</p>
[ { "answer_id": 75297, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "<p>It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not th...
2008/09/16
[ "https://Stackoverflow.com/questions/75076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2422/" ]
I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the [StackFrame class](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe%28v=vs.71%29.aspx) and then to reflect over a [ParameterInfo](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo%28v=vs.71%29.aspx) array. I've had success with reflection and properties, but this is proving a bit trickier. Is there an approach for achieving this? The code so far looks like this: ``` class Program { static void Main(string[] args) { A a = new A(); a.Go(1); } } public class A { internal void Go(int x) { B b = new B(); b.Go(4); } } public class B { internal void Go(int y) { Console.WriteLine(GetStackTrace()); } public static string GetStackTrace() { StringBuilder sb = new StringBuilder(); StackTrace st = new StackTrace(true); StackFrame[] frames = st.GetFrames(); foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name); ParameterInfo[] paramaters = method.GetParameters(); foreach (ParameterInfo paramater in paramaters) { sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString()); } sb.AppendLine(); } return sb.ToString(); } } ``` The output looks like this: --------------------------- ``` SfApp.B - GetStackTrace SfApp.B - Go y: Int32 y SfApp.A - Go x: Int32 x SfApp.Program - Main args: System.String[] args ``` I'd like it to look more like this: ----------------------------------- ``` SfApp.B - GetStackTrace SfApp.B - Go y: 4 SfApp.A - Go x: 1 SfApp.Program - Main ``` --- Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.
It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not the actual value at the time of the callstack. Some suggest deriving your classes from [ContextBoundObject](http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx) and use [IMessageSink](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.imessagesink.aspx) to be notified off all method calls and the values of the parameters. This is normally used for [.NET Remoting](http://en.wikipedia.org/wiki/.NET_Remoting). Another suggestion might be to write a debugger. This is how the IDE gets its information. Microsoft has [Mdbg](http://blogs.msdn.com/jmstall/archive/2004/09/30/236281.aspx) of which you can get the source code. Or write a [CLR profiler](http://msdn.microsoft.com/en-us/magazine/cc300553.aspx).
75,123
<p>I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.</p> <p>Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.</p> <p>I need to write the values out to a fixed length data file.</p>
[ { "answer_id": 75178, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 9, "selected": true, "text": "<p>Aside from limiting the columns selected to reduce bandwidth and memory:</p>\n\n<pre><code>DataTable t;\nt.Columns.Remov...
2008/09/16
[ "https://Stackoverflow.com/questions/75123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data. Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need. I need to write the values out to a fixed length data file.
Aside from limiting the columns selected to reduce bandwidth and memory: ``` DataTable t; t.Columns.Remove("columnName"); t.Columns.RemoveAt(columnIndex); ```
75,127
<p>I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root...</p> <p>I tried an index file in the root that had the following:</p> <pre><code>&lt;?php chdir('punbb'); include('index.php'); </code></pre> <p>But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work.</p> <p>Here is what I would like to make happen:</p> <p>User enters: </p> <pre><code> http://guardthe.net </code></pre> <p>Browser displays: </p> <pre><code> http://guardthe.net/punbb/ </code></pre> <p>or</p> <pre><code> http://punbb.guardthe.net/ </code></pre> <p>Is this possible, or should I just move the code base back into the root?</p>
[ { "answer_id": 75144, "author": "user13270", "author_id": 13270, "author_profile": "https://Stackoverflow.com/users/13270", "pm_score": 1, "selected": false, "text": "<p>a PHP file with a 301 HTTP permenant redirect.</p>\n\n<p>Put the following into index.php in the root directory of gua...
2008/09/16
[ "https://Stackoverflow.com/questions/75127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root... I tried an index file in the root that had the following: ``` <?php chdir('punbb'); include('index.php'); ``` But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod\_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work. Here is what I would like to make happen: User enters: ``` http://guardthe.net ``` Browser displays: ``` http://guardthe.net/punbb/ ``` or ``` http://punbb.guardthe.net/ ``` Is this possible, or should I just move the code base back into the root?
Something like this in .htacces should do it: ``` RewriteEngine On RewriteRule ^/?$ /punbb/ [R=301,L] ``` The 301 return code is to mark the move as permanentm making it posible for the browser to update bookmarks.
75,134
<p>How do I have two effects in jQuery run in <code>sequence</code>, not simultaneously? Take this piece of code for example:</p> <pre><code>$("#show-projects").click(function() { $(".page:visible").fadeOut("normal"); $("#projects").fadeIn("normal"); }); </code></pre> <p>The <code>fadeOut</code> and the <code>fadeIn</code> run simultaneously, how do I make them run one after the other?</p>
[ { "answer_id": 75194, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 4, "selected": false, "text": "<p>What you want is a queue.</p>\n\n<p>Check out the reference page <a href=\"http://api.jquery.com/queue/\" rel=\"nofo...
2008/09/16
[ "https://Stackoverflow.com/questions/75134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6967/" ]
How do I have two effects in jQuery run in `sequence`, not simultaneously? Take this piece of code for example: ``` $("#show-projects").click(function() { $(".page:visible").fadeOut("normal"); $("#projects").fadeIn("normal"); }); ``` The `fadeOut` and the `fadeIn` run simultaneously, how do I make them run one after the other?
You can supply a callback to the effects functions that run after the effect has completed. ``` $("#show-projects").click(function() { $(".page:visible").fadeOut("normal", function() { $("#projects").fadeIn("normal"); }); }); ```
75,139
<p>Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element). </p>
[ { "answer_id": 75234, "author": "Chris Van Opstal", "author_id": 7264, "author_profile": "https://Stackoverflow.com/users/7264", "pm_score": 3, "selected": false, "text": "<p>You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat=\"server\") form tags...
2008/09/16
[ "https://Stackoverflow.com/questions/75139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).
You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags. You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example: ``` <body> <form action="http://www.google.com/cse" id="cse-search-box"> ... </form> <form runat="server" id="aspNetform"> ... </form> <body> ```
75,156
<p>This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed.</p> <p>With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script). </p> <p>Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself.</p> <p>Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??</p>
[ { "answer_id": 75875, "author": "arclight", "author_id": 13366, "author_profile": "https://Stackoverflow.com/users/13366", "pm_score": 1, "selected": false, "text": "<p>On a UNIX-style system, I would use a signal handler trapping ALRM events, then use the alarm function to start a timer...
2008/09/16
[ "https://Stackoverflow.com/questions/75156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13282/" ]
This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed. With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script). Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself. Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??
On a UNIX-style system, I would use a signal handler trapping ALRM events, then use the alarm function to start a timer before starting an action that I expected might timeout. If the action completed, I'd use alarm(0) to turn off the alarm and exit normally, otherwise the signal handler should pick it up to close everything up gracefully. I have not worked with perl on Windows in a while and while Windows is somewhat POSIXy, I cannot guarantee this will work; you'll have to check the perl documentation to see if or to what extent signals are supported on your platform. More detailed information on signal handling and this sort of self-destruct programming using alarm() can be found in the Perl Cookbook. Here's a brief example lifted from another post and modified a little: ``` eval { # Create signal handler and make it local so it falls out of scope # outside the eval block local $SIG{ALRM} = sub { print "Print this if we time out, then die.\n"; die "alarm\n"; }; # Set the alarm, take your chance running the routine, and turn off # the alarm if it completes. alarm(90); routine_that_might_take_a_while(); alarm(0); }; ```
75,175
<p>Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is <code>no</code> (<em>due to type erasure</em>), but I'd be interested if anyone can see something I'm missing:</p> <pre><code>class SomeContainer&lt;E&gt; { E createContents() { return what??? } } </code></pre> <p>EDIT: It turns out that <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Super Type Tokens</a> could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.</p> <p>I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Artima Article</a>.</p>
[ { "answer_id": 75201, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>As you said, you can't really do it because of type erasure. You can sort of do it using reflection, but it requi...
2008/09/16
[ "https://Stackoverflow.com/questions/75175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is `no` (*due to type erasure*), but I'd be interested if anyone can see something I'm missing: ``` class SomeContainer<E> { E createContents() { return what??? } } ``` EDIT: It turns out that [Super Type Tokens](http://www.artima.com/weblogs/viewpost.jsp?thread=208860) could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated. I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's [Artima Article](http://www.artima.com/weblogs/viewpost.jsp?thread=208860).
You are correct. You can't do `new E()`. But you can change it to ``` private static class SomeContainer<E> { E createContents(Class<E> clazz) { return clazz.newInstance(); } } ``` It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
75,180
<p>If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?</p>
[ { "answer_id": 75202, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 9, "selected": true, "text": "<p>Yes, simple.\nsay you have</p>\n\n<pre><code>char *a = new char[10];\n</code></pre>\n\n<p>writing in the debugger:</p>\n\n<p...
2008/09/16
[ "https://Stackoverflow.com/questions/75180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9530/" ]
If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?
Yes, simple. say you have ``` char *a = new char[10]; ``` writing in the debugger: ``` a,10 ``` would show you the content as if it were an array.
75,181
<p>Here's a very simple Prototype example.</p> <p>All it does is, on window load, an ajax call which sticks some html into a div.</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;scriptaculous/lib/prototype.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; Event.observe(window, 'load', function(){ new Ajax.Request('get-table.php', { method: 'get', onSuccess: function(response){ $('content').innerHTML = response.responseText; //At this call, the div has HTML in it click1(); }, onFailure: function(){ alert('Fail!'); } }); //At this call, the div is empty click1(); }); function click1(){if($('content').innerHTML){alert('Found content');}else{alert('Empty div');}} &lt;/script&gt; &lt;/head&gt; &lt;body&gt;&lt;div id=&quot;content&quot;&gt;&lt;/div&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>The thing that's confusing is the context in which Prototype understands that the div actually has stuff in it.</p> <p>If you look at the onSuccess part of the ajax call, you'll see that at that point $('content').innerHTML has stuff in it.</p> <p>However when I check $('content').innerHTML right after the ajax call, it appears to be empty.</p> <p>This has to be some fundamental misunderstanding on my part. Anyone care to explain it to me?</p> <hr /> <p><strong>Edit</strong><br /> I just want to clarify something. I realize that the Ajax call is asynchronous.</p> <p>Here's the actual order that things are being executed and why it's confusing to me:</p> <ol> <li>The page loads.</li> <li>The Ajax request to get-table.php is made.</li> <li>The call to click1() INSIDE onSuccess happens. I see an alert that the div has content.</li> <li>The call to click1() AFTER the Ajax call happens. I see an alert that the div is empty.</li> </ol> <p>So it's like the code is executing in the order it's written but the DOM is not updating in the same order.</p> <hr /> <p><strong>Edit 2</strong> So the short answer is that putting the code in onSuccess is the correct place.</p> <p>Another case to consider is the one where you do an Ajax call and then do another Ajax call from the onSuccess of the first call like this:</p> <pre class="lang-js prettyprint-override"><code>new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ doAnotherAjaxCall(); } }); function doAnotherAjaxCall(){ new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ //Anything that needs to happen AFTER the call to doAnotherAjaxCall() above //needs to happen here! } }); } </code></pre>
[ { "answer_id": 75228, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 4, "selected": true, "text": "<p>The first letter of AJAX stands for \"asynchronous\". This means that the AJAX call is performed in the background, i....
2008/09/16
[ "https://Stackoverflow.com/questions/75181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Here's a very simple Prototype example. All it does is, on window load, an ajax call which sticks some html into a div. ```html <html> <head> <script type="text/javascript" src="scriptaculous/lib/prototype.js"></script> <script type="text/javascript"> Event.observe(window, 'load', function(){ new Ajax.Request('get-table.php', { method: 'get', onSuccess: function(response){ $('content').innerHTML = response.responseText; //At this call, the div has HTML in it click1(); }, onFailure: function(){ alert('Fail!'); } }); //At this call, the div is empty click1(); }); function click1(){if($('content').innerHTML){alert('Found content');}else{alert('Empty div');}} </script> </head> <body><div id="content"></div></body> </html> ``` The thing that's confusing is the context in which Prototype understands that the div actually has stuff in it. If you look at the onSuccess part of the ajax call, you'll see that at that point $('content').innerHTML has stuff in it. However when I check $('content').innerHTML right after the ajax call, it appears to be empty. This has to be some fundamental misunderstanding on my part. Anyone care to explain it to me? --- **Edit** I just want to clarify something. I realize that the Ajax call is asynchronous. Here's the actual order that things are being executed and why it's confusing to me: 1. The page loads. 2. The Ajax request to get-table.php is made. 3. The call to click1() INSIDE onSuccess happens. I see an alert that the div has content. 4. The call to click1() AFTER the Ajax call happens. I see an alert that the div is empty. So it's like the code is executing in the order it's written but the DOM is not updating in the same order. --- **Edit 2** So the short answer is that putting the code in onSuccess is the correct place. Another case to consider is the one where you do an Ajax call and then do another Ajax call from the onSuccess of the first call like this: ```js new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ doAnotherAjaxCall(); } }); function doAnotherAjaxCall(){ new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ //Anything that needs to happen AFTER the call to doAnotherAjaxCall() above //needs to happen here! } }); } ```
The first letter of AJAX stands for "asynchronous". This means that the AJAX call is performed in the background, i.e. the AJAX request call *immediately returns*. This means that the code immediately after it is normally actually executed *before* the onSuccess handler gets called (and before the AJAX request has even finished). Taking into account your edited question: in some browsers (e.g. Firefox), alert boxes are not as modal as you might think. Asynchronous code may pop up an alert box even if another one is already open. In that case, the newer alert box (the one from the asynchronous code) gets displayed on top of the older one. This creates the illusion that the asynchronous code got executed first.
75,213
<p>In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:</p> <pre><code>::foo(); </code></pre>
[ { "answer_id": 75224, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 2, "selected": false, "text": "<p>referring to the global scope</p>\n" }, { "answer_id": 75249, "author": "Drealmer", "author_id": 12291, ...
2008/09/16
[ "https://Stackoverflow.com/questions/75213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1785/" ]
In C++, what is the purpose of the scope resolution operator when used without a scope? For instance: ``` ::foo(); ```
It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like: ``` void bar(); // this is a global function class foo { void some_func() { ::bar(); } // this function is calling the global bar() and not the class version void bar(); // this is a class member }; ``` If you need to call the global bar() function from within a class member function, you should use ::bar() to get to the global version of the function.
75,218
<p>How can I detect when an Exception has been thrown anywhere in my application?</p> <p>I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.</p> <p>I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.</p> <p>Any suggestions?</p>
[ { "answer_id": 75274, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 0, "selected": false, "text": "<p>In this case I think your best bet might be to write a custom classloader to handle all classloading in your application,...
2008/09/16
[ "https://Stackoverflow.com/questions/75218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
How can I detect when an Exception has been thrown anywhere in my application? I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive. I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple. Any suggestions?
You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there. In a desktop app there are two places to worry about this, in the [event-dispatch-thread](/questions/tagged/event-dispatch-thread "show questions tagged 'event-dispatch-thread'") (EDT) and outside of the EDT. Globaly you can register a class implementing `java.util.Thread.UncaughtExceptionHandler` and register it via `java.util.Thread.setDefaultUncaughtExceptionHandler`. This will get called if an exception winds down to the bottom of the stack and the thread hasn't had a handler set on the current thread instance on the thread or the ThreadGroup. The EDT has a different hook for handling exceptions. A system property `'sun.awt.exception.handler'` needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor. This class needs an instance method handle(`Throwable`) that does your work. The return type doesn't matter, and since a new instance is created every time, don't count on keeping state. So if you don't care what thread the exception occurred in a sample may look like this: ``` class ExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { handle(e); } public void handle(Throwable throwable) { try { // insert your e-mail code here } catch (Throwable t) { // don't let the exception get thrown out, will cause infinite looping! } } public static void registerExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName()); } } ``` Add this class into some random package, and then call the `registerExceptionHandler` method and you should be ready to go.
75,245
<p>Is it possible to reach the individual columns of table2 using HQL with a configuration like this?</p> <pre><code>&lt;hibernate-mapping&gt; &lt;class table="table1"&gt; &lt;set name="table2" table="table2" lazy="true" cascade="all"&gt; &lt;key column="result_id"/&gt; &lt;many-to-many column="group_id"/&gt; &lt;/set&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
[ { "answer_id": 75272, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>They're just properties of table1's table2 property.</p>\n\n<pre><code>select t1.table2.property1, t1.table2.property2, .....
2008/09/16
[ "https://Stackoverflow.com/questions/75245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to reach the individual columns of table2 using HQL with a configuration like this? ``` <hibernate-mapping> <class table="table1"> <set name="table2" table="table2" lazy="true" cascade="all"> <key column="result_id"/> <many-to-many column="group_id"/> </set> </class> </hibernate-mapping> ```
They're just properties of table1's table2 property. ``` select t1.table2.property1, t1.table2.property2, ... from table1 as t1 ``` You might have to join, like so ``` select t2.property1, t2.property2, ... from table1 as t1 inner join t1.table2 as t2 ``` Here's the relevant part of the [hibernate doc](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html#queryhql-select).
75,261
<p>I got this output when running <code>sudo cpan Scalar::Util::Numeric</code></p> <pre> jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric [sudo] password for jmm: CPAN: Storable loaded ok Going to read /home/jmm/.cpan/Metadata Database was generated on Tue, 09 Sep 2008 16:02:51 GMT CPAN: LWP::UserAgent loaded ok Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz Database was generated on Tue, 16 Sep 2008 16:02:50 GMT There's a new CPAN.pm version (v1.9205) available! [Current version is v1.7602] You might want to try install Bundle::CPAN reload cpan without quitting the current session. It should be a seamless upgrade while we are running... Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz Going to write /home/jmm/.cpan/Metadata Running install for module Scalar::Util::Numeric Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz CPAN: Digest::MD5 loaded ok Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok Scanning cache /home/jmm/.cpan/build for sizes Scalar-Util-Numeric-0.02/ Scalar-Util-Numeric-0.02/Changes Scalar-Util-Numeric-0.02/lib/ Scalar-Util-Numeric-0.02/lib/Scalar/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm Scalar-Util-Numeric-0.02/Makefile.PL Scalar-Util-Numeric-0.02/MANIFEST Scalar-Util-Numeric-0.02/META.yml Scalar-Util-Numeric-0.02/Numeric.xs Scalar-Util-Numeric-0.02/ppport.h Scalar-Util-Numeric-0.02/README Scalar-Util-Numeric-0.02/t/ Scalar-Util-Numeric-0.02/t/pod.t Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02 CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz Checking if your kit is complete... Looks good Writing Makefile for Scalar::Util::Numeric cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric) /usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11, from /usr/lib/perl/5.8/CORE/perl.h:1510, from Numeric.xs:2: /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2120, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2284, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’ /usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’ /usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’ /usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’ In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2747, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’ In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2756, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2759, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’ /usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’ /usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’ /usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:3881, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type In file included from /usr/lib/perl/5.8/CORE/perl.h:3883, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3950, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’ /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’ /usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’ /usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’ /usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’ /usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’ /usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’ /usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’ /usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3988, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’ /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’ /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’ /usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from Numeric.xs:4: ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’: Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:22: error: invalid type argument of ‘unary *’ Numeric.c:24: error: invalid type argument of ‘unary *’ Numeric.xs:16: error: invalid type argument of ‘unary *’ Numeric.xs:17: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’: Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:45: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘boot_Scalar__Util__Numeric’: Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ make: *** [Numeric.o] Error 1 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ </pre>
[ { "answer_id": 75320, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>It can't find basic system headers. Either your include path is seriously messed up, or the headers are not instal...
2008/09/16
[ "https://Stackoverflow.com/questions/75261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I got this output when running `sudo cpan Scalar::Util::Numeric` ``` jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric [sudo] password for jmm: CPAN: Storable loaded ok Going to read /home/jmm/.cpan/Metadata Database was generated on Tue, 09 Sep 2008 16:02:51 GMT CPAN: LWP::UserAgent loaded ok Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz Database was generated on Tue, 16 Sep 2008 16:02:50 GMT There's a new CPAN.pm version (v1.9205) available! [Current version is v1.7602] You might want to try install Bundle::CPAN reload cpan without quitting the current session. It should be a seamless upgrade while we are running... Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz Going to write /home/jmm/.cpan/Metadata Running install for module Scalar::Util::Numeric Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz CPAN: Digest::MD5 loaded ok Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok Scanning cache /home/jmm/.cpan/build for sizes Scalar-Util-Numeric-0.02/ Scalar-Util-Numeric-0.02/Changes Scalar-Util-Numeric-0.02/lib/ Scalar-Util-Numeric-0.02/lib/Scalar/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm Scalar-Util-Numeric-0.02/Makefile.PL Scalar-Util-Numeric-0.02/MANIFEST Scalar-Util-Numeric-0.02/META.yml Scalar-Util-Numeric-0.02/Numeric.xs Scalar-Util-Numeric-0.02/ppport.h Scalar-Util-Numeric-0.02/README Scalar-Util-Numeric-0.02/t/ Scalar-Util-Numeric-0.02/t/pod.t Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02 CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz Checking if your kit is complete... Looks good Writing Makefile for Scalar::Util::Numeric cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric) /usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11, from /usr/lib/perl/5.8/CORE/perl.h:1510, from Numeric.xs:2: /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2120, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2284, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’ /usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’ /usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’ /usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’ In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2747, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’ In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2756, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2759, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’ /usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’ /usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’ /usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:3881, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type In file included from /usr/lib/perl/5.8/CORE/perl.h:3883, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3950, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’ /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’ /usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’ /usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’ /usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’ /usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’ /usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’ /usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’ /usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3988, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’ /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’ /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’ /usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from Numeric.xs:4: ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’: Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:22: error: invalid type argument of ‘unary *’ Numeric.c:24: error: invalid type argument of ‘unary *’ Numeric.xs:16: error: invalid type argument of ‘unary *’ Numeric.xs:17: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’: Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:45: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘boot_Scalar__Util__Numeric’: Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ make: *** [Numeric.o] Error 1 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ ```
You're missing your C library development headers. You should install a package that has them. These are necessary to install this module because it has to compile some non-perl C code and needs to know more about your system. I can't tell what kind of operating system you're on, but it looks like linux. If it's debian, you should be able to use apt-get to install the 'libc6-dev' package. That will contain the headers you need to compile this module. On other types of linux there will be a similarly named package.
75,273
<p>I'm in an <strong>ASP.NET UserControl</strong>. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008:</p> <p>"Could not reformat the document. The original format was restored."</p> <p>"Could not complete the action."</p> <p>"The operation could not be completed. The parameter is incorrect."</p> <p>Anybody know what causes this?</p> <p><strong>Edit</strong>: OK, that is just...weird.</p> <p>The problem is here:</p> <pre><code>&lt;asp:TableCell&gt; &lt;asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" /&gt; &lt;/asp:TableCell&gt; </code></pre> <p>Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work.</p> <p>All I can figure is that this is some sort of really obscure, bizarre bug.</p>
[ { "answer_id": 75283, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "<p>There's probably some malformed markup somewhere in your document. Have you tried it on a fresh document?</p>\n" }, ...
2008/09/16
[ "https://Stackoverflow.com/questions/75273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
I'm in an **ASP.NET UserControl**. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008: "Could not reformat the document. The original format was restored." "Could not complete the action." "The operation could not be completed. The parameter is incorrect." Anybody know what causes this? **Edit**: OK, that is just...weird. The problem is here: ``` <asp:TableCell> <asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" /> </asp:TableCell> ``` Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work. All I can figure is that this is some sort of really obscure, bizarre bug.
There's probably some malformed markup somewhere in your document. Have you tried it on a fresh document?
75,282
<p>I'm handling the <code>onSelectIndexChanged</code> event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for <code>SelectedValue</code> and <code>SelectedIndex</code>. What am I doing wrong?</p> <p>Here is the DropDownList definition from the aspx file:</p> <pre><code>&lt;div style="margin: 0px; padding: 0px 1em 0px 0px;"&gt; &lt;span style="margin: 0px; padding: 0px; vertical-align: top;"&gt;Route:&lt;/span&gt; &lt;asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true"&gt; &lt;/asp:DropDownList&gt; &lt;asp:Literal ID="Literal1" runat="server"&gt;&lt;/asp:Literal&gt; &lt;/div&gt; </code></pre> <p>Here is the DropDownList <code>OnSelectedIndexChanged</code> event handler:</p> <pre><code>protected void index_changed(object sender, EventArgs e) { decimal d = Convert.ToDecimal( Select1.SelectedValue ); Literal1.Text = d.ToString(); } </code></pre>
[ { "answer_id": 75306, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>Do you have any code in page load that is by chance re-defaulting the value to the first value?</p>\n\n<p>When th...
2008/09/16
[ "https://Stackoverflow.com/questions/75282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
I'm handling the `onSelectIndexChanged` event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for `SelectedValue` and `SelectedIndex`. What am I doing wrong? Here is the DropDownList definition from the aspx file: ``` <div style="margin: 0px; padding: 0px 1em 0px 0px;"> <span style="margin: 0px; padding: 0px; vertical-align: top;">Route:</span> <asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true"> </asp:DropDownList> <asp:Literal ID="Literal1" runat="server"></asp:Literal> </div> ``` Here is the DropDownList `OnSelectedIndexChanged` event handler: ``` protected void index_changed(object sender, EventArgs e) { decimal d = Convert.ToDecimal( Select1.SelectedValue ); Literal1.Text = d.ToString(); } ```
Do you have any code in page load that is by chance re-defaulting the value to the first value? When the page reloads do you see the new value?
75,322
<p>I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined".</p> <p>It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page.</p> <p>This leads me to believe that it could be an IIS setting.</p> <p>Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing:</p> <pre><code>&lt;script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;amp;t=baeb8cc" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); //]]&gt; &lt;/script&gt; </code></pre>
[ { "answer_id": 75460, "author": "Compulsion", "author_id": 3675, "author_profile": "https://Stackoverflow.com/users/3675", "pm_score": 3, "selected": false, "text": "<p>Try setting your ScriptManager to this.</p>\n\n<pre><code>&lt;asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" ...
2008/09/16
[ "https://Stackoverflow.com/questions/75322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined". It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page. This leads me to believe that it could be an IIS setting. Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing: ``` <script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;t=baeb8cc" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); //]]> </script> ```
I fixed my problem by moving the `<script type="text/javascript"></script>` block containing the Sys.\* calls lower down (to the last item before the close of the body's `<asp:Content/>` section) in the HTML on the page. I originally had my the script block in the HEAD `<asp:Content/>` section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.
75,361
<p>I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.</p> <p>I want to get them numerically ordered and I've come up with</p> <pre><code>select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) </code></pre> <p>which is very very ugly.</p> <p>Better suggestions?</p>
[ { "answer_id": 75398, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or cr...
2008/09/16
[ "https://Stackoverflow.com/questions/75361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far. I want to get them numerically ordered and I've come up with ``` select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) ``` which is very very ugly. Better suggestions?
It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.
75,379
<p>The problem is simple, but I'm struggling a bit already.</p> <pre><code>Server server = new Server(8080); Context context = new Context(server, "/", Context.NO_SESSIONS); context.addServlet(MainPageView.class, "/"); context.addServlet(UserView.class, "/signup"); server.start(); </code></pre> <p>That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. </p> <p>Instantiation of some of these servlets requires heavy work on startup. Say &ndash; reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?</p>
[ { "answer_id": 75424, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 0, "selected": false, "text": "<p>Use the <code>Context.addServlet</code> overload that takes a <code>ServletHolder</code>. <code>ServletHolder</code...
2008/09/16
[ "https://Stackoverflow.com/questions/75379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105/" ]
The problem is simple, but I'm struggling a bit already. ``` Server server = new Server(8080); Context context = new Context(server, "/", Context.NO_SESSIONS); context.addServlet(MainPageView.class, "/"); context.addServlet(UserView.class, "/signup"); server.start(); ``` That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?
I'm not sure why using Guice make's Justin's option not work for you. What exactly is getting injected in? I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating. ``` Context context = new Context(server, "/", Context.NO_SESSIONS); ServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class); // Do this to force Jetty to instantiate the servlet mainPageViewHolder.getServlet(); context.addServlet(mainPageViewHolder, "/"); ```
75,385
<p>The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.</p> <p>Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.</p> <p>Thanks,</p> <pre><code>int foo(void) { unsigned int fooUnsigned = 0xffffffff; int fooSigned = fooUnsigned; // no warning if (fooSigned &lt; fooUnsigned) // warning { return 0; } return fooSigned; } </code></pre> <p>Update:</p> <p>Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;</p> <pre><code>#pragma warning (4 : 4365) </code></pre> <p>Which results in;</p> <pre><code>warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch </code></pre>
[ { "answer_id": 75596, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 4, "selected": true, "text": "<p>You need to enable warning 4365 to catch the assignment.</p>\n\n<p>That might be tricky - you need to enable ALL warnings ...
2008/09/16
[ "https://Stackoverflow.com/questions/75385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments. Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere. Thanks, ``` int foo(void) { unsigned int fooUnsigned = 0xffffffff; int fooSigned = fooUnsigned; // no warning if (fooSigned < fooUnsigned) // warning { return 0; } return fooSigned; } ``` Update: Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so; ``` #pragma warning (4 : 4365) ``` Which results in; ``` warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch ```
You need to enable warning 4365 to catch the assignment. That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
75,401
<p>User <a href="https://stackoverflow.com/users/1065/kokos">kokos</a> answered the wonderful <em><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></em> question by mentioning the <code>using</code> keyword. Can you elaborate on that? What are the uses of <code>using</code>?</p>
[ { "answer_id": 75419, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 2, "selected": false, "text": "<p>When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the ...
2008/09/16
[ "https://Stackoverflow.com/questions/75401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13332/" ]
User [kokos](https://stackoverflow.com/users/1065/kokos) answered the wonderful *[Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)* question by mentioning the `using` keyword. Can you elaborate on that? What are the uses of `using`?
The reason for the `using` statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens. As in *[Understanding the 'using' statement in C# (codeproject)](https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C)* and *[Using objects that implement IDisposable (microsoft)](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects)*, the C# compiler converts ``` using (MyResource myRes = new MyResource()) { myRes.DoSomething(); } ``` to ``` { // Limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes != null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); } } ``` C# 8 introduces a new syntax, named "[using declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations)": > > A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope. > > > So the equivalent code of above would be: ``` using var myRes = new MyResource(); myRes.DoSomething(); ``` And when control leaves the containing scope (usually a method, but it can also be a code block), `myRes` will be disposed.
75,440
<p>What method do I call to get the name of a class?</p>
[ { "answer_id": 75456, "author": "clahey", "author_id": 8453, "author_profile": "https://Stackoverflow.com/users/8453", "pm_score": 5, "selected": false, "text": "<p>It's not a method, it's a field. The field is called <code>__name__</code>. <code>class.__name__</code> will give the nam...
2008/09/16
[ "https://Stackoverflow.com/questions/75440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8453/" ]
What method do I call to get the name of a class?
``` In [1]: class Test: ...: pass ...: In [2]: Test.__name__ Out[2]: 'Test' ```
75,441
<p>As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?</p>
[ { "answer_id": 75481, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 4, "selected": true, "text": "<p>Use the &lt;<a href=\"http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html\" rel=\"noreferrer\">attrib...
2008/09/16
[ "https://Stackoverflow.com/questions/75441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8088/" ]
As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?
Use the <[attrib](http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html)> task. For example, to make the file "test.txt" read/write, you would use ``` <attrib file="test.txt" readonly="false"/> ```
75,489
<p>I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.<br><br> I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.<br> <br> Any advice?</p> <p>Thanks.</p>
[ { "answer_id": 75674, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 4, "selected": true, "text": "<p>The parseDate and formatDate tags work, but they work with Date objects.\nYou can call new java.util.Date(longvalue) to g...
2008/09/16
[ "https://Stackoverflow.com/questions/75489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP. I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work. Any advice? Thanks.
The parseDate and formatDate tags work, but they work with Date objects. You can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag. somewhere other than the jsp create your date object. ``` long longvalue = ...;//from database. java.util.Date dateValue = new java.util.Date(longvalue); request.setAttribute("dateValue", dateValue); ``` put it on the request and then you can access it in your tag like this. ``` <fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/> ```
75,495
<p>When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)</p> <p>The following code demonstrates the problem:</p> <pre><code>&lt;Window x:Class="ExampleApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:ExampleApplication3" Title="Example" Height="600" Width="600"&gt; &lt;Grid Background="LightGray"&gt; &lt;loc:UserControl1 /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays reasonably at design time but displays as a fixed size at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays as a dot at design time but expands to fill the parent <code>Window1</code> at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre>
[ { "answer_id": 75527, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 6, "selected": false, "text": "<p>For Blend, a little known trick is to add these attributes to your usercontrol or window:</p>\n\n<pre><code> xmlns:d=\"h...
2008/09/16
[ "https://Stackoverflow.com/questions/75495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.) The following code demonstrates the problem: ``` <Window x:Class="ExampleApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:ExampleApplication3" Title="Example" Height="600" Width="600"> <Grid Background="LightGray"> <loc:UserControl1 /> </Grid> </Window> ``` The following definition of `UserControl1` displays reasonably at design time but displays as a fixed size at run time: ``` <UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"> <Grid Background="LightCyan" /> </UserControl> ``` The following definition of `UserControl1` displays as a dot at design time but expands to fill the parent `Window1` at run time: ``` <UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid Background="LightCyan" /> </UserControl> ```
In Visual Studio add the Width and Height attribute to your UserControl XAML, but in the code-behind insert this ``` public UserControl1() { InitializeComponent(); if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { this.Width = double.NaN; ; this.Height = double.NaN; ; } } ``` This checks to see if the control is running in Design-mode. If not (i.e. runtime) it will set the Width and Height to NaN (Not a number) which is the value you set it to if you remove the Width and Height attributes in XAML. So at design-time you will have the preset width and height (including if you put the user control in a form) and at runtime it will dock depending on its parent container. Hope that helps.
75,500
<p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
[ { "answer_id": 75524, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<p>How about pdf2tiff? <a href=\"http://python.net/~gherman/pdf2tiff.html\" rel=\"nofollow noreferrer\">http://python.net/~gher...
2008/09/16
[ "https://Stackoverflow.com/questions/75500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal.
Use Imagemagick, or better yet, Ghostscript. <http://www.ibm.com/developerworks/library/l-graf2/#N101C2> has an example for imagemagick: ``` convert foo.pdf pages-%03d.tiff ``` <http://www.asmail.be/msg0055376363.html> has an example for ghostscript: ``` gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit ``` I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.
75,508
<p>I have 28,000 images I need to convert into a movie. I tried </p> <pre><code>mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi </code></pre> <p>But it seems to crap out at 7500 frames.</p> <p>The files are named webcam_2007-04-16_070804.jpg webcam_2007-04-16_071004.jpg webcam_2007-04-16_071204.jpg webcam_2007-04-16_071404.jpg Up to march 2008 or so.</p> <p>Is there another way I can pass the filenames to mencoder so it doesn't stop part way?</p> <pre><code>MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 28617 (114468) VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333 Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) ========================================================================== VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (640x480 fourcc=3234504d [MP42]) Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0] Flushing video frames. Writing index... Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames </code></pre>
[ { "answer_id": 75566, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>another alternative is to bypass mencoder and use ffmpeg directly</p>\n" }, { "answer_id": 75616, "author": "D...
2008/09/16
[ "https://Stackoverflow.com/questions/75508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11950/" ]
I have 28,000 images I need to convert into a movie. I tried ``` mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi ``` But it seems to crap out at 7500 frames. The files are named webcam\_2007-04-16\_070804.jpg webcam\_2007-04-16\_071004.jpg webcam\_2007-04-16\_071204.jpg webcam\_2007-04-16\_071404.jpg Up to march 2008 or so. Is there another way I can pass the filenames to mencoder so it doesn't stop part way? ``` MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 28617 (114468) VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333 Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) ========================================================================== VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (640x480 fourcc=3234504d [MP42]) Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0] Flushing video frames. Writing index... Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames ```
Shove the list of images in a file, one per line. Then use `mf://@filename`
75,538
<p>No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?</p>
[ { "answer_id": 75581, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 2, "selected": false, "text": "<p>I'm not sure about hidden, but there are some <a href=\"http://en.wikipedia.org/wiki/Duff%27s_device\" rel=\"nofollo...
2008/09/16
[ "https://Stackoverflow.com/questions/75538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?
You can put URIs into C++ source without error. For example: ``` void foo() { http://stackoverflow.com/ int bar = 4; ... } ```
75,608
<p>I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries.</p> <p>I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method.</p> <p>Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.</p>
[ { "answer_id": 75651, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataS...
2008/09/16
[ "https://Stackoverflow.com/questions/75608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries. I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method. Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.
Assuming cmd is your SqlCeCommand.... ``` using(var dr = cmd.ExecuteReader()) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); dt.Load(dr); ds.WriteXML(...); } ```
75,614
<p>The following question answers how to get large memory pages on Windows :<br> "<a href="https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows">how do i run my app with large pages in windows</a>".</p> <p>The problem I'm trying to solve is how do I configure it on Vista and 2008 Server.</p> <p>Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing.</p> <p>Anyone have a clue as to what else needs to be configured?</p> <p>Thanks, Staffan</p>
[ { "answer_id": 75651, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataS...
2008/09/16
[ "https://Stackoverflow.com/questions/75614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8782/" ]
The following question answers how to get large memory pages on Windows : "[how do i run my app with large pages in windows](https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows)". The problem I'm trying to solve is how do I configure it on Vista and 2008 Server. Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing. Anyone have a clue as to what else needs to be configured? Thanks, Staffan
Assuming cmd is your SqlCeCommand.... ``` using(var dr = cmd.ExecuteReader()) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); dt.Load(dr); ds.WriteXML(...); } ```
75,621
<p>I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned_data field unless I call <code>is_valid()</code>. But <code>is_valid()</code> always fails on unbound forms.</p> <p>It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML.</p> <p>For example, if I have:</p> <pre><code>if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>is_valid() will fail if this is a GET (since it's unbound), and if I do:</p> <pre><code>if request.method == 'GET': form = MyForm() do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>the first call to do_query triggers exceptions on form.cleaned_data, which is not a valid field because <code>is_valid()</code> has not been called. It seems like I have to do something like:</p> <pre><code>if request.method == 'GET': form = MyForm() do_query(form['start_date'].field.initial, form['end_date'].field.initial) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one.</p> <p>Does anyone see a cleaner way to do this?</p>
[ { "answer_id": 75815, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 0, "selected": false, "text": "<p>You can pass a dictionary of initial values to your form:</p>\n\n<pre><code>if request.method == \"GET\":\n # calcu...
2008/09/16
[ "https://Stackoverflow.com/questions/75621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8247/" ]
I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned\_data field unless I call `is_valid()`. But `is_valid()` always fails on unbound forms. It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML. For example, if I have: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` is\_valid() will fail if this is a GET (since it's unbound), and if I do: ``` if request.method == 'GET': form = MyForm() do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` the first call to do\_query triggers exceptions on form.cleaned\_data, which is not a valid field because `is_valid()` has not been called. It seems like I have to do something like: ``` if request.method == 'GET': form = MyForm() do_query(form['start_date'].field.initial, form['end_date'].field.initial) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one. Does anyone see a cleaner way to do this?
If you add this method to your form class: ``` def get_cleaned_or_initial(self, fieldname): if hasattr(self, 'cleaned_data'): return self.cleaned_data.get(fieldname) else: return self[fieldname].field.initial ``` you could then re-write your code as: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) form.is_valid() do_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date')) ```
75,626
<p>I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. </p> <p>For example I would like to accomplish this: </p> <pre><code>&lt;%@ taglib prefix="wf" uri="JspCustomTag" %&gt; &lt;% Object myObject = new Object(); %&gt; &lt;wf:my-tag obj=myObject /&gt; </code></pre> <p>I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.</p>
[ { "answer_id": 75745, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>Use expression language:</p>\n\n<pre>\n &lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</pre>\n" }, { "answer_...
2008/09/16
[ "https://Stackoverflow.com/questions/75626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13393/" ]
I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. For example I would like to accomplish this: ``` <%@ taglib prefix="wf" uri="JspCustomTag" %> <% Object myObject = new Object(); %> <wf:my-tag obj=myObject /> ``` I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.
A slightly different question that I looked for here: "How do you pass an object to a tag file?" Answer: Use the "type" attribute of the attribute directive: ``` <%@ attribute name="field" required="true" type="com.mycompany.MyClass" %> ``` The type [defaults to java.lang.String](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854), so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.
75,650
<p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p> <p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p> <p>A couple of questions:</p> <ul> <li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li> <li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li> </ul> <p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p> <p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
[ { "answer_id": 75745, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>Use expression language:</p>\n\n<pre>\n &lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</pre>\n" }, { "answer_...
2008/09/16
[ "https://Stackoverflow.com/questions/75650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine. What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone. A couple of questions: * Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it? * What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios? **Edit:** MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success? **Edit:** If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; [Executing different set of MSBuild tasks for each user?](https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user)
A slightly different question that I looked for here: "How do you pass an object to a tag file?" Answer: Use the "type" attribute of the attribute directive: ``` <%@ attribute name="field" required="true" type="com.mycompany.MyClass" %> ``` The type [defaults to java.lang.String](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854), so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.
75,675
<p>How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)? The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like</p> <pre><code>sqlite3 db .dump </code></pre> <p>but without dumping the schema and selecting which tables to dump.</p>
[ { "answer_id": 75694, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You could do a select on the tables inserting commas after each field to produce a csv, or use a GUI tool to return all the...
2008/09/16
[ "https://Stackoverflow.com/questions/75675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)? The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like ``` sqlite3 db .dump ``` but without dumping the schema and selecting which tables to dump.
You're not saying what you wish to do with the dumped file. To get a CSV file (which can be imported into almost everything) ``` .mode csv -- use '.separator SOME_STRING' for something other than a comma. .headers on .out file.csv select * from MyTable; ``` To get an SQL file (which can be reinserted into a different SQLite database) ``` .mode insert <target_table_name> .out file.sql select * from MyTable; ```
75,700
<p>I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application. <br><br>I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.<br><br> A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit. Anyone ever see an issue?</p> <hr> <p>In your config, would you have two transaction managers? Would you have txManager1 and txManager2?<br><br> That's what I have with JPA, two different Spring beans that are transaction managers.</p>
[ { "answer_id": 78479, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<p>I guess you have 2 choices</p>\n\n<p>If your use-cases never require updates to both databases within the same transaction,...
2008/09/16
[ "https://Stackoverflow.com/questions/75700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13143/" ]
I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application. I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback. A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit. Anyone ever see an issue? --- In your config, would you have two transaction managers? Would you have txManager1 and txManager2? That's what I have with JPA, two different Spring beans that are transaction managers.
I guess you have 2 choices If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple [TransactionProxyFactoryBean](http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.html) to define transaction boundaries, eg: ``` <bean id="firstRealService" class="com.acme.FirstServiceImpl"/> <bean id="firstService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="firstJpaTm"/> <property name="target" ref="firstRealService"/> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- similar for your second service --> ``` If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The [API](http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/jpa/JpaTransactionManager.html) states: > > This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions. > > > What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following: ``` <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManagerName" value="appserver/jndi/path" /> </bean> ``` If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet) As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using? The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element. Hope this helps
75,704
<p>I see that within MySQL there are <code>Cast()</code> and <code>Convert()</code> functions to create integers from values, but is there any way to check to see if a value is an integer? Something like <code>is_int()</code> in PHP is what I am looking for.</p>
[ { "answer_id": 75739, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 4, "selected": false, "text": "<p>Match it against a regular expression.</p>\n<p>c.f. <a href=\"http://forums.mysql.com/read.php?60,1907,38488#msg-38488\" rel...
2008/09/16
[ "https://Stackoverflow.com/questions/75704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8224/" ]
I see that within MySQL there are `Cast()` and `Convert()` functions to create integers from values, but is there any way to check to see if a value is an integer? Something like `is_int()` in PHP is what I am looking for.
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do ``` select field from table where field REGEXP '^-?[0-9]+$'; ``` this is reasonably fast. If your field is numeric, just test for ``` ceil(field) = field ``` instead.
75,705
<p>I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction?</p> <p>Thanks for your time.</p>
[ { "answer_id": 75846, "author": "Kearns", "author_id": 6500, "author_profile": "https://Stackoverflow.com/users/6500", "pm_score": 2, "selected": false, "text": "<p>FoxPro 2.0 files were exactly the same as dBase III files with an extra bit for any field that was of type \"memo\" (not su...
2008/09/16
[ "https://Stackoverflow.com/questions/75705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction? Thanks for your time.
Something like ... ? ``` ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=e:\My Documents\dBase;Extended Properties=dBase III" Dim dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString ) dBaseConnection.Open() ``` From: <http://bytes.com/forum/thread112085.html>
75,713
<p>I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties.</p> <p>Here's the class I'm using as a datasource:</p> <pre><code>public interface IPerson { string UserId { get; set; } string UserName { get; set; } string Email { get; set; } } public class Person : EntityBase, IPerson { public virtual string UserId { get; set; } public string UserName { get; set; } public virtual string Email { get; set; } } </code></pre> <p>Here's the XAML (an excerpt):</p> <pre><code>&lt;TextBox Name="userIdTextBox" Text="{Binding UserId}" /&gt; &lt;TextBox Name="userNameTextBox" Text="{Binding UserName}" /&gt; &lt;TextBox Name="emailTextBox" Text="{Binding Email}" /&gt; </code></pre> <p>Here's the code behind (again, an excerpt):</p> <pre><code>var person = PolicyInjection.Wrap&lt;IPerson&gt;(new Person()); person.UserId = "jdoe"; person.UserName = "John Doe"; person.Email = "jdoe@live.com"; this.DataContext = person; </code></pre> <p>Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block.</p> <p>I'm getting this error at runtime:</p> <pre><code>System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level) at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)' </code></pre>
[ { "answer_id": 77322, "author": "Robert Jeppesen", "author_id": 9436, "author_profile": "https://Stackoverflow.com/users/9436", "pm_score": 3, "selected": true, "text": "<p>I'm not familiar with entlib's policy injection, but I'm pretty sure that your problem lies there, and not in the f...
2008/09/16
[ "https://Stackoverflow.com/questions/75713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6542/" ]
I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties. Here's the class I'm using as a datasource: ``` public interface IPerson { string UserId { get; set; } string UserName { get; set; } string Email { get; set; } } public class Person : EntityBase, IPerson { public virtual string UserId { get; set; } public string UserName { get; set; } public virtual string Email { get; set; } } ``` Here's the XAML (an excerpt): ``` <TextBox Name="userIdTextBox" Text="{Binding UserId}" /> <TextBox Name="userNameTextBox" Text="{Binding UserName}" /> <TextBox Name="emailTextBox" Text="{Binding Email}" /> ``` Here's the code behind (again, an excerpt): ``` var person = PolicyInjection.Wrap<IPerson>(new Person()); person.UserId = "jdoe"; person.UserName = "John Doe"; person.Email = "jdoe@live.com"; this.DataContext = person; ``` Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block. I'm getting this error at runtime: ``` System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level) at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)' ```
I'm not familiar with entlib's policy injection, but I'm pretty sure that your problem lies there, and not in the fact that you're using an interface. If you were to replace ``` var person = PolicyInjection.Wrap<IPerson>(new Person()); ``` with ``` IPerson person = new Person(); ``` surely it would work?
75,714
<p>Note: I am using .Net 1.1, although I am not completely against answer that use higher versions.</p> <p>I am displaying some dynamically generated objects in a PropertyGrid. These objects have numeric, text, and enumeration properties. Currently I am having issues setting the default value for the enumerations so that they don't always appear bold in the list. The enumerations themselves are also dynamically generated and appear to work fine with the exception of the default value.</p> <p>First, I would like to show how I generate the enumerations in the case that it is causing the error. The first line uses a custom class to query the database. Simply replace this line with a DataAdapter or your preferred method of filling a DataSet with Database values. I am using the string values in column 1 to create my enumeration.</p> <pre><code>private Type GetNewObjectType(string field, ModuleBuilder module, DatabaseAccess da) //Query the database. System.Data.DataSet ds = da.QueryDB(query); EnumBuilder eb = module.DefineEnum(field, TypeAttributes.Public, typeof(int)); for(int i = 0; i &lt; ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][1] != DBNull.Value) { string text = Convert.ToString(ds.Tables[0].Rows[i][1]); eb.DefineLiteral(text, i); } } return eb.CreateType(); </code></pre> <p>Now on to how the type is created. This is largely based of the sample code provided <a href="http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx" rel="nofollow noreferrer">here</a>. Essentially, think of pFeature as a database row. We loop through the columns and use the column name as the new property name and use the column value as the default value; that is the goal at least.</p> <pre><code>// create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "tmpAssembly"; AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule"); // create a new type builder TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class); // Loop over the attributes that will be used as the properties names in out new type for(int i = 0; i &lt; pFeature.Fields.FieldCount; i++) { string propertyName = pFeature.Fields.get_Field(i).Name; object val = pFeature.get_Value(i); Type type = GetNewObjectType(propertyName, module, da); // Generate a private field FieldBuilder field = typeBuilder.DefineField("_" + propertyName, type, FieldAttributes.Private); // Generate a public property PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, type, new Type[0]); //Create the custom attribute to set the description. Type[] ctorParams = new Type[] { typeof(string) }; ConstructorInfo classCtorInfo = typeof(DescriptionAttribute).GetConstructor(ctorParams); CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { "This is the long description of this property." }); property.SetCustomAttribute(myCABuilder); //Set the default value. ctorParams = new Type[] { type }; classCtorInfo = typeof(DefaultValueAttribute).GetConstructor(ctorParams); if(type.IsEnum) { //val contains the text version of the enum. Parse it to the enumeration value. object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } else { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { val }); } property.SetCustomAttribute(myCABuilder); // The property set and property get methods require a special set of attributes: MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig; // Define the "get" accessor method for current private field. MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, type, Type.EmptyTypes); // Intermediate Language stuff... ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator(); currGetIL.Emit(OpCodes.Ldarg_0); currGetIL.Emit(OpCodes.Ldfld, field); currGetIL.Emit(OpCodes.Ret); // Define the "set" accessor method for current private field. MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { type }); // Again some Intermediate Language stuff... ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator(); currSetIL.Emit(OpCodes.Ldarg_0); currSetIL.Emit(OpCodes.Ldarg_1); currSetIL.Emit(OpCodes.Stfld, field); currSetIL.Emit(OpCodes.Ret); // Last, we must map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(currGetPropMthdBldr); property.SetSetMethod(currSetPropMthdBldr); } // Generate our type Type generatedType = typeBuilder.CreateType(); </code></pre> <p>Finally, we use that type to create an instance of it and load in the default values so we can later display it using the PropertiesGrid.</p> <pre><code>// Now we have our type. Let's create an instance from it: object generatedObject = Activator.CreateInstance(generatedType); // Loop over all the generated properties, and assign the default values PropertyInfo[] properties = generatedType.GetProperties(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(generatedType); for(int i = 0; i &lt; properties.Length; i++) { string field = properties[i].Name; DefaultValueAttribute dva = (DefaultValueAttribute)props[field].Attributes[typeof(DefaultValueAttribute)]; object o = dva.Value; Type pType = properties[i].PropertyType; if(pType.IsEnum) { o = Enum.Parse(pType, o.ToString(), true); } else { o = Convert.ChangeType(o, pType); } properties[i].SetValue(generatedObject, o, null); } return generatedObject; </code></pre> <p>However, this causes an error when we try to get the default value for an enumeration. The DefaultValueAttribute dva does not get set and thus causes an exception when we try to use it.</p> <p>If we change this code segment:</p> <pre><code> if(type.IsEnum) { object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } </code></pre> <p>to this:</p> <pre><code> if(type.IsEnum) { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { 0 }); } </code></pre> <p>There are no problems getting the DefaultValueAttribute dva; however, the field is then bolded in the PropertiesGrid because it does not match the default value.</p> <p>Can anyone figure out why I cannot get the DefaultValueAttribute when I set the default value to my generated enumeration? As you can probably guess, I am still new to Reflection, so this is all pretty new to me.</p> <p>Thanks.</p> <p>Update: In response to alabamasucks.blogspot, using ShouldSerialize would certainly solve my problem. I was able to create the method using a normal class; however, I am unsure on how to do this for a generated type. From what I can figure out, I would need to use MethodBuilder and generate the IL to check if the field is equal to the default value. Sounds simple enough. I want to represent this in IL code:</p> <pre><code>public bool ShouldSerializepropertyName() { return (field != val); } </code></pre> <p>I was able to get the IL code using ildasm.exe from similar code, but I have a couple of questions. How do I use the val variable in the IL code? In my example, I used a int with the value of 0.</p> <pre><code>IL_0000: ldc.i4.s 0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldarg.0 IL_0005: ldfld int32 TestNamespace.TestClass::field IL_000a: ceq IL_000c: ldc.i4.0 IL_000d: ceq IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret </code></pre> <p>This certainly can get tricky because IL has a different load command for each type. Currently, I use ints, doubles, strings, and enumerations, so the code will have to be adaptive based on the type. </p> <p>Does anyone have an idea how to do this? Or am I heading in the wrong direction?</p>
[ { "answer_id": 80194, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 2, "selected": false, "text": "<p>I'm not sure how to get the attribute to work, but there is another option that may be easier.</p>\n\n<p>In addition to c...
2008/09/16
[ "https://Stackoverflow.com/questions/75714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Note: I am using .Net 1.1, although I am not completely against answer that use higher versions. I am displaying some dynamically generated objects in a PropertyGrid. These objects have numeric, text, and enumeration properties. Currently I am having issues setting the default value for the enumerations so that they don't always appear bold in the list. The enumerations themselves are also dynamically generated and appear to work fine with the exception of the default value. First, I would like to show how I generate the enumerations in the case that it is causing the error. The first line uses a custom class to query the database. Simply replace this line with a DataAdapter or your preferred method of filling a DataSet with Database values. I am using the string values in column 1 to create my enumeration. ``` private Type GetNewObjectType(string field, ModuleBuilder module, DatabaseAccess da) //Query the database. System.Data.DataSet ds = da.QueryDB(query); EnumBuilder eb = module.DefineEnum(field, TypeAttributes.Public, typeof(int)); for(int i = 0; i < ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][1] != DBNull.Value) { string text = Convert.ToString(ds.Tables[0].Rows[i][1]); eb.DefineLiteral(text, i); } } return eb.CreateType(); ``` Now on to how the type is created. This is largely based of the sample code provided [here](http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx). Essentially, think of pFeature as a database row. We loop through the columns and use the column name as the new property name and use the column value as the default value; that is the goal at least. ``` // create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "tmpAssembly"; AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule"); // create a new type builder TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class); // Loop over the attributes that will be used as the properties names in out new type for(int i = 0; i < pFeature.Fields.FieldCount; i++) { string propertyName = pFeature.Fields.get_Field(i).Name; object val = pFeature.get_Value(i); Type type = GetNewObjectType(propertyName, module, da); // Generate a private field FieldBuilder field = typeBuilder.DefineField("_" + propertyName, type, FieldAttributes.Private); // Generate a public property PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, type, new Type[0]); //Create the custom attribute to set the description. Type[] ctorParams = new Type[] { typeof(string) }; ConstructorInfo classCtorInfo = typeof(DescriptionAttribute).GetConstructor(ctorParams); CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { "This is the long description of this property." }); property.SetCustomAttribute(myCABuilder); //Set the default value. ctorParams = new Type[] { type }; classCtorInfo = typeof(DefaultValueAttribute).GetConstructor(ctorParams); if(type.IsEnum) { //val contains the text version of the enum. Parse it to the enumeration value. object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } else { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { val }); } property.SetCustomAttribute(myCABuilder); // The property set and property get methods require a special set of attributes: MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig; // Define the "get" accessor method for current private field. MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, type, Type.EmptyTypes); // Intermediate Language stuff... ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator(); currGetIL.Emit(OpCodes.Ldarg_0); currGetIL.Emit(OpCodes.Ldfld, field); currGetIL.Emit(OpCodes.Ret); // Define the "set" accessor method for current private field. MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { type }); // Again some Intermediate Language stuff... ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator(); currSetIL.Emit(OpCodes.Ldarg_0); currSetIL.Emit(OpCodes.Ldarg_1); currSetIL.Emit(OpCodes.Stfld, field); currSetIL.Emit(OpCodes.Ret); // Last, we must map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(currGetPropMthdBldr); property.SetSetMethod(currSetPropMthdBldr); } // Generate our type Type generatedType = typeBuilder.CreateType(); ``` Finally, we use that type to create an instance of it and load in the default values so we can later display it using the PropertiesGrid. ``` // Now we have our type. Let's create an instance from it: object generatedObject = Activator.CreateInstance(generatedType); // Loop over all the generated properties, and assign the default values PropertyInfo[] properties = generatedType.GetProperties(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(generatedType); for(int i = 0; i < properties.Length; i++) { string field = properties[i].Name; DefaultValueAttribute dva = (DefaultValueAttribute)props[field].Attributes[typeof(DefaultValueAttribute)]; object o = dva.Value; Type pType = properties[i].PropertyType; if(pType.IsEnum) { o = Enum.Parse(pType, o.ToString(), true); } else { o = Convert.ChangeType(o, pType); } properties[i].SetValue(generatedObject, o, null); } return generatedObject; ``` However, this causes an error when we try to get the default value for an enumeration. The DefaultValueAttribute dva does not get set and thus causes an exception when we try to use it. If we change this code segment: ``` if(type.IsEnum) { object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } ``` to this: ``` if(type.IsEnum) { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { 0 }); } ``` There are no problems getting the DefaultValueAttribute dva; however, the field is then bolded in the PropertiesGrid because it does not match the default value. Can anyone figure out why I cannot get the DefaultValueAttribute when I set the default value to my generated enumeration? As you can probably guess, I am still new to Reflection, so this is all pretty new to me. Thanks. Update: In response to alabamasucks.blogspot, using ShouldSerialize would certainly solve my problem. I was able to create the method using a normal class; however, I am unsure on how to do this for a generated type. From what I can figure out, I would need to use MethodBuilder and generate the IL to check if the field is equal to the default value. Sounds simple enough. I want to represent this in IL code: ``` public bool ShouldSerializepropertyName() { return (field != val); } ``` I was able to get the IL code using ildasm.exe from similar code, but I have a couple of questions. How do I use the val variable in the IL code? In my example, I used a int with the value of 0. ``` IL_0000: ldc.i4.s 0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldarg.0 IL_0005: ldfld int32 TestNamespace.TestClass::field IL_000a: ceq IL_000c: ldc.i4.0 IL_000d: ceq IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret ``` This certainly can get tricky because IL has a different load command for each type. Currently, I use ints, doubles, strings, and enumerations, so the code will have to be adaptive based on the type. Does anyone have an idea how to do this? Or am I heading in the wrong direction?
I'm not sure how to get the attribute to work, but there is another option that may be easier. In addition to checking for the DefaultValueAttribute, the PropertyGrid also uses reflection to look for a method named "ShouldSerializeProperty Name", where [Property Name] is the name of the property in question. This method should return a boolean that is true if the property is set to a non-default value and false otherwise. It would probably be easier for you to use reflection to create a method that returns the correct value then to fix up the attribute.
75,722
<p>In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:</p> <pre><code>using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { // use sr, and have everything cleaned up when done. } } } </code></pre> <p>In C++, I'm used to being able to use destructors to do it like this:</p> <pre><code>{ FileStream fs("c:\file.txt", FileMode.Open); BufferedStream bs(fs); StreamReader sr(bs); // use sr, and have everything cleaned up when done. } </code></pre> <p>Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?</p>
[ { "answer_id": 75741, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": -1, "selected": false, "text": "<p>The using statement is syntactic sugar that converts to:</p>\n\n<pre><code> try\n {\n obj declaration\n ...
2008/09/16
[ "https://Stackoverflow.com/questions/75722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701/" ]
In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further: ``` using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { // use sr, and have everything cleaned up when done. } } } ``` In C++, I'm used to being able to use destructors to do it like this: ``` { FileStream fs("c:\file.txt", FileMode.Open); BufferedStream bs(fs); StreamReader sr(bs); // use sr, and have everything cleaned up when done. } ``` Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?
You don't have to nest with multiple usings: ``` using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { // all three get disposed when you're done } ```
75,746
<pre><code>EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), </code></pre> <p>I often find myself wanting to do things like this (<code>EmployeeNumber</code> is a <code>Nullable&lt;int&gt;</code> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that</p> <blockquote> <p>There is no implicit conversion between 'null' and 'int'</p> </blockquote> <p>even though both types would be valid in an assignment operation to a nullable int on their own.</p> <p>Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the <code>.Text</code> string if it's not null.</p> <p>As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...</p> <p>Does anyone know a more elegant solution?</p>
[ { "answer_id": 75795, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 2, "selected": false, "text": "<p>You can cast the output of Convert:</p>\n\n<pre><code>EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox....
2008/09/16
[ "https://Stackoverflow.com/questions/75746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), ``` I often find myself wanting to do things like this (`EmployeeNumber` is a `Nullable<int>` as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that > > There is no implicit conversion between 'null' and 'int' > > > even though both types would be valid in an assignment operation to a nullable int on their own. Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the `.Text` string if it's not null. As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block... Does anyone know a more elegant solution?
The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a `null` and an `Int32`, and the type can not be determined (there are real reasons it can't just assume `Nullable<Int32>`). If you really want to use it in this way, you must cast one of the values to `Nullable<Int32>` yourself, so C# can resolve the type: ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? (int?)null : Convert.ToInt32(employeeNumberTextBox.Text), ``` or ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : (int?)Convert.ToInt32(employeeNumberTextBox.Text), ```
75,752
<p>I'm building a quick csv from a mysql table with a query like:</p> <pre><code>select DATE(date),count(date) from table group by DATE(date) order by date asc; </code></pre> <p>and just dumping them to a file in perl over a:</p> <pre><code>while(my($date,$sum) = $sth-&gt;fetchrow) { print CSV "$date,$sum\n" } </code></pre> <p>There are date gaps in the data, though:</p> <pre><code>| 2008-08-05 | 4 | | 2008-08-07 | 23 | </code></pre> <p>I would like to pad the data to fill in the missing days with zero-count entries to end up with:</p> <pre><code>| 2008-08-05 | 4 | | 2008-08-06 | 0 | | 2008-08-07 | 23 | </code></pre> <p>I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. </p> <p>Any genius ideas/slaps in the face for why me am being so dumb?</p> <hr> <p>I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons:</p> <ul> <li>I know the date range I'll be looking for every time</li> <li>The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed</li> </ul> <p>The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!</p>
[ { "answer_id": 75807, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 3, "selected": false, "text": "<p>When I had to deal with this problem, to fill in missing dates I actually created a reference table that just contained all...
2008/09/16
[ "https://Stackoverflow.com/questions/75752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13196/" ]
I'm building a quick csv from a mysql table with a query like: ``` select DATE(date),count(date) from table group by DATE(date) order by date asc; ``` and just dumping them to a file in perl over a: ``` while(my($date,$sum) = $sth->fetchrow) { print CSV "$date,$sum\n" } ``` There are date gaps in the data, though: ``` | 2008-08-05 | 4 | | 2008-08-07 | 23 | ``` I would like to pad the data to fill in the missing days with zero-count entries to end up with: ``` | 2008-08-05 | 4 | | 2008-08-06 | 0 | | 2008-08-07 | 23 | ``` I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. Any genius ideas/slaps in the face for why me am being so dumb? --- I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons: * I know the date range I'll be looking for every time * The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!
When you need something like that on server side, you usually create a table which contains all possible dates between two points in time, and then left join this table with query results. Something like this: ```sql create procedure sp1(d1 date, d2 date) declare d datetime; create temporary table foo (d date not null); set d = d1 while d <= d2 do insert into foo (d) values (d) set d = date_add(d, interval 1 day) end while select foo.d, count(date) from foo left join table on foo.d = table.date group by foo.d order by foo.d asc; drop temporary table foo; end procedure ``` In this particular case it would be better to put a little check on the client side, if current date is not previos+1, put some addition strings.
75,759
<p>What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.</p>
[ { "answer_id": 75787, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 1, "selected": false, "text": "<p>Most people use symbols (that's the <code>:foo_bar</code> syntax). They're sort of unique opaque values. Symbols don'...
2008/09/16
[ "https://Stackoverflow.com/questions/75759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.
Two ways. Symbols (`:foo` notation) or constants (`FOO` notation). Symbols are appropriate when you want to enhance readability without littering code with literal strings. ``` postal_code[:minnesota] = "MN" postal_code[:new_york] = "NY" ``` Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that. ``` module Foo BAR = 1 BAZ = 2 BIZ = 4 end flags = Foo::BAR | Foo::BAZ # flags = 3 ``` Added 2021-01-17 If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there's a mashup of both approaches ``` COMMODITY_TYPE = { currency: 1, investment: 2, } def commodity_type_string(value) COMMODITY_TYPE.key(value) end COMMODITY_TYPE[:currency] ``` This approach inspired by andrew-grimm's answer <https://stackoverflow.com/a/5332950/13468> I'd also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language's enum that you care about
75,785
<p>Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.</p> <p>Related resources:</p> <ul> <li><a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a></li> <li><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/</a></li> </ul>
[ { "answer_id": 84987, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 8, "selected": true, "text": "<p><strong>Please Note:</strong> This question gathered a good amount of feedback, and some people below have made grea...
2008/09/16
[ "https://Stackoverflow.com/questions/75785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ]
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed. Related resources: * <http://www.codeproject.com/KB/dotnet/AppBar.aspx> * <http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/>
**Please Note:** This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also **created a [WpfAppBar project on github](https://github.com/PhilipRieck/WpfAppBar)**. Feel free to send pull requests. That same project also builds to a [WpfAppBar nuget package](https://www.nuget.org/packages/WpfAppBar/) --- I took the code from the first link provided in the question ( <http://www.codeproject.com/KB/dotnet/AppBar.aspx> ) and modified it to do two things: 1. Work with WPF 2. Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window. This approach doesn't create a base class. To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur. Make the window an appbar: ``` AppBarFunctions.SetAppBar( this, ABEdge.Right ); ``` Restore the window to a normal window: ``` AppBarFunctions.SetAppBar( this, ABEdge.None ); ``` Here's the full code to the file - **note** you'll want to change the namespace on line 7 to something apropriate. ``` using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace AppBarApplication { public enum ABEdge : int { Left = 0, Top, Right, Bottom, None } internal static class AppBarFunctions { [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public int cbSize; public IntPtr hWnd; public int uCallbackMessage; public int uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg : int { ABM_NEW = 0, ABM_REMOVE, ABM_QUERYPOS, ABM_SETPOS, ABM_GETSTATE, ABM_GETTASKBARPOS, ABM_ACTIVATE, ABM_GETAUTOHIDEBAR, ABM_SETAUTOHIDEBAR, ABM_WINDOWPOSCHANGED, ABM_SETSTATE } private enum ABNotify : int { ABN_STATECHANGE = 0, ABN_POSCHANGED, ABN_FULLSCREENAPP, ABN_WINDOWARRANGE } [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)] private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData); [DllImport("User32.dll", CharSet = CharSet.Auto)] private static extern int RegisterWindowMessage(string msg); private class RegisterInfo { public int CallbackId { get; set; } public bool IsRegistered { get; set; } public Window Window { get; set; } public ABEdge Edge { get; set; } public WindowStyle OriginalStyle { get; set; } public Point OriginalPosition { get; set; } public Size OriginalSize { get; set; } public ResizeMode OriginalResizeMode { get; set; } public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == CallbackId) { if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED) { ABSetPos(Edge, Window); handled = true; } } return IntPtr.Zero; } } private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo = new Dictionary<Window, RegisterInfo>(); private static RegisterInfo GetRegisterInfo(Window appbarWindow) { RegisterInfo reg; if( s_RegisteredWindowInfo.ContainsKey(appbarWindow)) { reg = s_RegisteredWindowInfo[appbarWindow]; } else { reg = new RegisterInfo() { CallbackId = 0, Window = appbarWindow, IsRegistered = false, Edge = ABEdge.Top, OriginalStyle = appbarWindow.WindowStyle, OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top), OriginalSize = new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight), OriginalResizeMode = appbarWindow.ResizeMode, }; s_RegisteredWindowInfo.Add(appbarWindow, reg); } return reg; } private static void RestoreWindow(Window appbarWindow) { RegisterInfo info = GetRegisterInfo(appbarWindow); appbarWindow.WindowStyle = info.OriginalStyle; appbarWindow.ResizeMode = info.OriginalResizeMode; appbarWindow.Topmost = false; Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, info.OriginalSize.Width, info.OriginalSize.Height); appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } public static void SetAppBar(Window appbarWindow, ABEdge edge) { RegisterInfo info = GetRegisterInfo(appbarWindow); info.Edge = edge; APPBARDATA abd = new APPBARDATA(); abd.cbSize = Marshal.SizeOf(abd); abd.hWnd = new WindowInteropHelper(appbarWindow).Handle; if( edge == ABEdge.None) { if( info.IsRegistered) { SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd); info.IsRegistered = false; } RestoreWindow(appbarWindow); return; } if (!info.IsRegistered) { info.IsRegistered = true; info.CallbackId = RegisterWindowMessage("AppBarMessage"); abd.uCallbackMessage = info.CallbackId; uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd); HwndSource source = HwndSource.FromHwnd(abd.hWnd); source.AddHook(new HwndSourceHook(info.WndProc)); } appbarWindow.WindowStyle = WindowStyle.None; appbarWindow.ResizeMode = ResizeMode.NoResize; appbarWindow.Topmost = true; ABSetPos(info.Edge, appbarWindow); } private delegate void ResizeDelegate(Window appbarWindow, Rect rect); private static void DoResize(Window appbarWindow, Rect rect) { appbarWindow.Width = rect.Width; appbarWindow.Height = rect.Height; appbarWindow.Top = rect.Top; appbarWindow.Left = rect.Left; } private static void ABSetPos(ABEdge edge, Window appbarWindow) { APPBARDATA barData = new APPBARDATA(); barData.cbSize = Marshal.SizeOf(barData); barData.hWnd = new WindowInteropHelper(appbarWindow).Handle; barData.uEdge = (int)edge; if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right) { barData.rc.top = 0; barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; if (barData.uEdge == (int)ABEdge.Left) { barData.rc.left = 0; barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth); } else { barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth); } } else { barData.rc.left = 0; barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; if (barData.uEdge == (int)ABEdge.Top) { barData.rc.top = 0; barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight); } else { barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight); } } SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData); SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData); Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top)); //This is done async, because WPF will send a resize after a new appbar is added. //if we size right away, WPFs resize comes last and overrides us. appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } } } ```
75,786
<p>(Eclipse 3.4, Ganymede)</p> <p>I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down.</p> <p>It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.)</p> <p>I have tried the following steps (without success):</p> <ul> <li>I selected <code>Targeted Runtimes</code> under the Project <code>Properties</code><br> The <code>Tomcat v5.5</code> option was disabled and The UI displayed this message:<br> <code>If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.</code> </li> <li>I then clicked on the <code>Uninstall Facets...</code> link.<br> Under the <code>Runtimes</code> tab, only <code>Tomcat 6</code> displayed.<br> For <code>Dynamic Web Module</code>, I selected version <code>2.4</code> in place of <code>2.5</code>.<br> Under the <code>Runtimes</code> tab, <code>Tomcat 5.5</code> now displayed.<br> However, the UI now displayed this message:<br> <code>Cannot change version of project facet Dynamic Web Module to 2.4.</code><br> The <code>Finish</code> button was disabled - so I reached a dead-end.</li> </ul> <p>I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project.</p> <p>As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy.</p> <p>Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened?</p> <p>Thanks<br> Pete</p>
[ { "answer_id": 76205, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 7, "selected": true, "text": "<p>This is kind of hacking eclipse and you can get into trouble doing this but this should work:</p>\n\n<p>Open the navigator ...
2008/09/16
[ "https://Stackoverflow.com/questions/75786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13360/" ]
(Eclipse 3.4, Ganymede) I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down. It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.) I have tried the following steps (without success): * I selected `Targeted Runtimes` under the Project `Properties` The `Tomcat v5.5` option was disabled and The UI displayed this message: `If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.` * I then clicked on the `Uninstall Facets...` link. Under the `Runtimes` tab, only `Tomcat 6` displayed. For `Dynamic Web Module`, I selected version `2.4` in place of `2.5`. Under the `Runtimes` tab, `Tomcat 5.5` now displayed. However, the UI now displayed this message: `Cannot change version of project facet Dynamic Web Module to 2.4.` The `Finish` button was disabled - so I reached a dead-end. I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project. As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy. Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened? Thanks Pete
This is kind of hacking eclipse and you can get into trouble doing this but this should work: Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: `org.eclipse.wst.common.project.facet.core.xml` you should see a line that says: `<installed facet="jst.web" version="2.5"/>` Change that to 2.4 and save. Just make sure that your project isn't using anything specific for 2.5 and you should be good. Also check your web.xml has the correct configuration: ``` <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> ```
75,809
<p>Given the case I made <strong>two independent changes</strong> in <em>one</em> file: eg. added a new method and changed another method.</p> <p>I often don't want to commit both changes as <strong>one</strong> commit, but as <strong>two</strong> independent commits.</p> <p>On a git repository I would use the <strong>Interactive Mode</strong> of <a href="http://linux.die.net/man/1/git-add" rel="noreferrer">git-add(1)</a> to split the <em>hunk</em> into smaller ones:</p> <pre><code> git add --patch </code></pre> <p>What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in)</p> <p><strong>Update:</strong><br/> In <a href="http://tomayko.com/writings/the-thing-about-git" rel="noreferrer">The Thing About Git</a>, Ryan calls it: <em>“The Tangled Working Copy Problem.”</em></p>
[ { "answer_id": 75881, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>I used to do this:</p>\n\n<ul>\n<li>In my editor (I use vim), edit the file so that only one of the changes appear</li>...
2008/09/16
[ "https://Stackoverflow.com/questions/75809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
Given the case I made **two independent changes** in *one* file: eg. added a new method and changed another method. I often don't want to commit both changes as **one** commit, but as **two** independent commits. On a git repository I would use the **Interactive Mode** of [git-add(1)](http://linux.die.net/man/1/git-add) to split the *hunk* into smaller ones: ``` git add --patch ``` What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in) **Update:** In [The Thing About Git](http://tomayko.com/writings/the-thing-about-git), Ryan calls it: *“The Tangled Working Copy Problem.”*
With git-svn you can make a local GIT repository of the remote SVN repository, work with it using the full GIT feature set (including partial commits) and then push it all back to the SVN repository. [git-svn (1)](http://schacon.github.com/git/git-svn.html)
75,819
<p>I'm having an issue with a query that currently uses </p> <pre><code>LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) </code></pre> <p>However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of <code>LIKE</code>, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?</p>
[ { "answer_id": 75861, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 1, "selected": false, "text": "<p>you're talking about short circuit evaluation.</p>\n\n<p>Take a look at this article it might help you:\n<a href=\"http://bein...
2008/09/16
[ "https://Stackoverflow.com/questions/75819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12073/" ]
I'm having an issue with a query that currently uses ``` LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of `LIKE`, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?
It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now. Try this: ``` LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32) LEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` Then, in your select clause, use something like this: ``` select isnull(pwd1.field, pwd2.field) ``` however, if you are dealing with a field that can be null in pwd, that will cause problems, this should work though: ``` select case pwd1.nonnullfield is null then pwd2.field else pwd1.field end ``` You'll also have to make sure to do a group by, as the join to pwd2 will still add rows to your result set, even if you end up ignoring the data in it.
75,829
<p>All the docs for SQLAlchemy give <code>INSERT</code> and <code>UPDATE</code> examples using the local table instance (e.g. <code>tablename.update()</code>... )</p> <p>Doing this seems difficult with the declarative syntax, I need to reference <code>Base.metadata.tables["tablename"]</code> to get the table reference.</p> <p>Am I supposed to do this another way? Is there a different syntax for <code>INSERT</code> and <code>UPDATE</code> recommended when using the declarative syntax? Should I just switch to the old way?</p>
[ { "answer_id": 77962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>via the <code>__table__</code> attribute on your declarative class</p>\n" }, { "answer_id": 156968, "author": "G...
2008/09/16
[ "https://Stackoverflow.com/questions/75829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
All the docs for SQLAlchemy give `INSERT` and `UPDATE` examples using the local table instance (e.g. `tablename.update()`... ) Doing this seems difficult with the declarative syntax, I need to reference `Base.metadata.tables["tablename"]` to get the table reference. Am I supposed to do this another way? Is there a different syntax for `INSERT` and `UPDATE` recommended when using the declarative syntax? Should I just switch to the old way?
well it works for me: ``` class Users(Base): __tablename__ = 'users' __table_args__ = {'autoload':True} users = Users() print users.__table__.select() ``` ...SELECT users.......
75,848
<p>I'm trying to insert a <a href="http://en.wikipedia.org/wiki/Spry_framework" rel="nofollow noreferrer">Spry</a> <a href="http://en.wikipedia.org/wiki/Accordion_(GUI)" rel="nofollow noreferrer">accordion</a> into an already existing <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> page using <a href="http://en.wikipedia.org/wiki/Adobe_Dreamweaver" rel="nofollow noreferrer">Dreamweaver</a>. Is this possible? </p> <p>I've already tried several things, and only the labels show up.</p>
[ { "answer_id": 81534, "author": "Dave Smylie", "author_id": 1505600, "author_profile": "https://Stackoverflow.com/users/1505600", "pm_score": 3, "selected": true, "text": "<p>I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: </p>\n\n<pre><...
2008/09/16
[ "https://Stackoverflow.com/questions/75848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459442/" ]
I'm trying to insert a [Spry](http://en.wikipedia.org/wiki/Spry_framework) [accordion](http://en.wikipedia.org/wiki/Accordion_(GUI)) into an already existing [JSF](http://en.wikipedia.org/wiki/JavaServer_Faces) page using [Dreamweaver](http://en.wikipedia.org/wiki/Adobe_Dreamweaver). Is this possible? I've already tried several things, and only the labels show up.
I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: ``` <div id="Accordion1" class="Accordion"> <div class="AccordionPanel"> <div class="AccordionPanelTab">Panel 1</div> <div class="AccordionPanelContent"> Panel 1 Content<br/> Panel 1 Content<br/> Panel 1 Content<br/> </div> </div> </div> ``` Provided you have the [JavaScript](http://en.wikipedia.org/wiki/JavaScript) library loaded correctly, that should pretty much be all you need to do.
75,943
<p>I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: </p> <pre><code>&lt;div&gt; &lt;!-- some html --&gt; &lt;script type="text/javascript"&gt; /** some javascript */ &lt;/script&gt; &lt;/div&gt; </code></pre> <p>I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? </p> <p>Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?</p>
[ { "answer_id": 76003, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 4, "selected": false, "text": "<p>You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagNa...
2008/09/16
[ "https://Stackoverflow.com/questions/75943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4243/" ]
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: ``` <div> <!-- some html --> <script type="text/javascript"> /** some javascript */ </script> </div> ``` I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example: ``` <html> <head> <script type='text/javascript'> function addScript() { var str = "<script>alert('i am here');<\/script>"; var newdiv = document.createElement('div'); newdiv.innerHTML = str; document.getElementById('target').appendChild(newdiv); } </script> </head> <body> <input type="button" value="add script" onclick="addScript()"/> <div>hello world</div> <div id="target"></div> </body> </html> ```
75,978
<p>In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>
[ { "answer_id": 76067, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "<p>Use the following (remember to include System.Configuration assembly)</p>\n\n<pre><code>ConfigurationManager....
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
75,980
<p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p> <p>Use escape:</p> <pre><code>escape("% +&amp;="); </code></pre> <p>OR</p> <p>use encodeURI() / encodeURIComponent()</p> <pre><code>encodeURI("http://www.google.com?var1=value1&amp;var2=value2"); encodeURIComponent("var1=value1&amp;var2=value2"); </code></pre>
[ { "answer_id": 75989, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 5, "selected": false, "text": "<p>encodeURI() - the escape() function is for javascript escaping, not HTTP.</p>\n" }, { "answer_id": 76119, ...
2008/09/16
[ "https://Stackoverflow.com/questions/75980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
When encoding a query string to be sent to a web server - when do you use `escape()` and when do you use `encodeURI()` or `encodeURIComponent()`: Use escape: ``` escape("% +&="); ``` OR use encodeURI() / encodeURIComponent() ``` encodeURI("http://www.google.com?var1=value1&var2=value2"); encodeURIComponent("var1=value1&var2=value2"); ```
escape() ======== Don't use it! `escape()` is defined in section [B.2.1.2 escape](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string) and the [introduction text of Annex B](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers) says: > > ... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ... > > ... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code.... > > > Behaviour: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape> Special characters are encoded with the exception of: @\*\_+-./ The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: `%xx`. For characters with a greater code unit, the four-digit format `%uxxxx` is used. This is not allowed within a query string (as defined in [RFC3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.4)): ``` query = *( pchar / "/" / "?" ) pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" pct-encoded = "%" HEXDIG HEXDIG sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" ``` A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by `u` is not allowed. encodeURI() =========== Use encodeURI when you want a working URL. Make this call: ``` encodeURI("http://www.example.org/a file with spaces.html") ``` to get: ``` http://www.example.org/a%20file%20with%20spaces.html ``` Don't call encodeURIComponent since it would destroy the URL and return ``` http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html ``` Note that encodeURI, like encodeURIComponent, does not escape the ' character. encodeURIComponent() ==================== Use encodeURIComponent when you want to encode the value of a URL parameter. ``` var p1 = encodeURIComponent("http://example.org/?a=12&b=55") ``` Then you may create the URL you need: ``` var url = "http://example.net/?param1=" + p1 + "&param2=99"; ``` And you will get this complete URL: `http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99` Note that encodeURIComponent does not escape the `'` character. A common bug is to use it to create html attributes such as `href='MyUrl'`, which could suffer an injection bug. If you are constructing html from strings, either use `"` instead of `'` for attribute quotes, or add an extra layer of encoding (`'` can be encoded as %27). For more information on this type of encoding you can check: <http://en.wikipedia.org/wiki/Percent-encoding>
76,065
<p>I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:</p> <pre><code>mysql&gt; source script.sql </code></pre> <p>How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.</p> <p>I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.</p>
[ { "answer_id": 76124, "author": "Brad Choate", "author_id": 553, "author_profile": "https://Stackoverflow.com/users/553", "pm_score": 6, "selected": true, "text": "<p>Like this:</p>\n\n<pre><code>set @department := 'Engineering';\n</code></pre>\n\n<p>Then, reference <code>@department</co...
2008/09/16
[ "https://Stackoverflow.com/questions/76065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13519/" ]
I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this: ``` mysql> source script.sql ``` How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable. I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.
Like this: ``` set @department := 'Engineering'; ``` Then, reference `@department` wherever you need to in script.sql: ``` update employee set salary = salary + 10000 where department = @department; ```
76,074
<p>I have a couple old services that I want to completely uninstall. How can I do this?</p>
[ { "answer_id": 76101, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 6, "selected": false, "text": "<p>Click <em>Start</em> | <strong>Run</strong> and type <code>regedit</code> in the Open: line. Click OK.</p>\n\n<p>Navig...
2008/09/16
[ "https://Stackoverflow.com/questions/76074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204/" ]
I have a couple old services that I want to completely uninstall. How can I do this?
Use the *SC* command, like this (you need to be on a command prompt to execute the commands in this post): ``` SC STOP shortservicename SC DELETE shortservicename ``` --- **Note:** You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". **Note to PowerShell users:** `sc` is aliased to `set-content`. So `sc delete service` will actually create a file called `delete` with the content `service`. To do this in Powershell, use `sc.exe delete service` instead --- If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses: ``` SC QUERY state= all >"C:\Service List.txt" ``` For a more concise list, execute this command: ``` SC QUERY state= all | FIND "_NAME" ``` The short service name will be listed just above the display name, like this: ``` SERVICE_NAME: MyService DISPLAY_NAME: My Special Service ``` And thus to delete that service: ``` SC STOP MyService SC DELETE MyService ```
76,076
<p>I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.</p> <p>To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.</p> <p>I was thinking of using octtrees, but I was wondering if someone knows a better method.</p>
[ { "answer_id": 76185, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": true, "text": "<p>Octtrees are the way to go. You subdivide the array into 8 octants:</p>\n\n<pre>\n1 2\n3 4\n\n---\n\n5 6\n7 8\n</p...
2008/09/16
[ "https://Stackoverflow.com/questions/76076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13405/" ]
I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points. To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once. I was thinking of using octtrees, but I was wondering if someone knows a better method.
Octtrees are the way to go. You subdivide the array into 8 octants: ``` 1 2 3 4 --- 5 6 7 8 ``` And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above. You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point). This has much, much better cache coherency and locality of reference than the naive layout.
76,079
<p>can anyone please suggest a <strong>good code example</strong> of vb.net/c# code to put the application in system tray when minized.</p>
[ { "answer_id": 76120, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 5, "selected": true, "text": "<p>Add a NotifyIcon control to your form, then use the following code:</p>\n\n<pre><code> private void frm_main_Resiz...
2008/09/16
[ "https://Stackoverflow.com/questions/76079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337/" ]
can anyone please suggest a **good code example** of vb.net/c# code to put the application in system tray when minized.
Add a NotifyIcon control to your form, then use the following code: ``` private void frm_main_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.ShowInTaskbar = false; this.Hide(); notifyIcon1.Visible = true; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; notifyIcon1.Visible = false; } ``` You may not need to set the ShowInTaskbar property.
76,080
<p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p> <p>For reference, here is code to get the Application Data folder under both systems:</p> <pre><code> HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); </code></pre> <p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p> <p>Under Windows XP, the app data subfolder is:</p> <p>Microsoft\Internet Explorer\Quick Launch</p> <p>Under Vista, it appears that the sub-folder has been changed to:</p> <p>Roaming\Microsoft\Internet Explorer\Quick Launch</p> <p>but I'd like to make sure that this is the correct way to determine the correct location.</p> <p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p> <p>EDIT: The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p> <p>So the following algorithm is correct per MS:</p> <pre><code>HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch"; </code></pre> <p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
[ { "answer_id": 76246, "author": "StocksR", "author_id": 6892, "author_profile": "https://Stackoverflow.com/users/6892", "pm_score": 3, "selected": true, "text": "<p>AppData on vista refers to C:\\Users\\xxxx\\AppData\\Roaming not the C:\\Users\\xxxx\\AppData folder it's self.</p>\n\n<p>A...
2008/09/16
[ "https://Stackoverflow.com/questions/76080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10973/" ]
We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question. For reference, here is code to get the Application Data folder under both systems: ``` HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); ``` I suspect this is just a matter of knowing which sub-folder Microsoft uses. Under Windows XP, the app data subfolder is: Microsoft\Internet Explorer\Quick Launch Under Vista, it appears that the sub-folder has been changed to: Roaming\Microsoft\Internet Explorer\Quick Launch but I'd like to make sure that this is the correct way to determine the correct location. Finding the *correct* way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP). EDIT: The following msdn article: <http://msdn.microsoft.com/en-us/library/bb762494.aspx> indicates that CSIDL\_APPDATA has an equivalent ID of FOLDERID\_RoamingAppData, which does seem to support StocksR's assertion that CSIDL\_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL\_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch). So the following algorithm is correct per MS: ``` HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch"; ``` it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.
AppData on vista refers to C:\Users\xxxx\AppData\Roaming not the C:\Users\xxxx\AppData folder it's self. Also this artical <http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx> on a microsoft site implies that you simply have to use the path relative to the appdata folder
76,134
<p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p> <p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p> <p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>
[ { "answer_id": 76282, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :</p>\n\n<p>Find two points with max inter...
2008/09/16
[ "https://Stackoverflow.com/questions/76134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ]
I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this? I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though. This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information.
Alright, I came here looking for an answer and didn't find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation. Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates. Here is a still photo from Thomas the Tank Engine: [![Thomas the Tank Engine](https://i.stack.imgur.com/YUhsm.png)](https://i.stack.imgur.com/YUhsm.png) Let's say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth): [![With an outline of the square](https://i.stack.imgur.com/u8nKF.png)](https://i.stack.imgur.com/u8nKF.png) I get four points in the 2D image: `(318, 247)`, `(326, 312)`, `(418, 241)`, and `(452, 303)`. By convention, we say that these points should correspond to the 3D points: `(0, 0, 0)`, `(0, 0, 1)`, `(1, 0, 0)`, and `(1, 0, 1)`. In other words, a unit square in the y=0 plane. Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector `[x, y, z, 1]` with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what [gluProject()](https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml) does, except `gluProject()` also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the `gluProject()` documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula. Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we're going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess. Let's define our points: ``` # Known 2D coordinates of our rectangle i0 = Point2(318, 247) i1 = Point2(326, 312) i2 = Point2(418, 241) i3 = Point2(452, 303) # 3D coordinates corresponding to i0, i1, i2, i3 r0 = Point3(0, 0, 0) r1 = Point3(0, 0, 1) r2 = Point3(1, 0, 0) r3 = Point3(1, 0, 1) ``` We need to start with some matrix, identity matrix seems a natural choice: ``` mat = [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ``` We need to actually implement the projection (which is basically a matrix multiplication): ``` def project(p, mat): x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1 y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1 w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1 return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.) ``` This is basically what `gluProject()` does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You'll notice we're not calculating z, that's because we don't really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer). Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.: ``` # The squared distance between two points a and b def norm2(a, b): dx = b.x - a.x dy = b.y - a.y return dx * dx + dy * dy def evaluate(mat): c0 = project(r0, mat) c1 = project(r1, mat) c2 = project(r2, mat) c3 = project(r3, mat) return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3) ``` To perturb the matrix, we simply pick an element to perturb by a random amount within some range: ``` def perturb(amount): from copy import deepcopy from random import randrange, uniform mat2 = deepcopy(mat) mat2[randrange(4)][randrange(4)] += uniform(-amount, amount) ``` (It's worth noting that our `project()` function doesn't actually use `mat[2]` at all, since we don't compute z, and since all our y coordinates are 0 the `mat[*][1]` values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...) For convenience, let's add a function that does the bulk of the approximation by calling `perturb()` over and over again on what is the best matrix we've found so far: ``` def approximate(mat, amount, n=100000): est = evaluate(mat) for i in xrange(n): mat2 = perturb(mat, amount) est2 = evaluate(mat2) if est2 < est: mat = mat2 est = est2 return mat, est ``` Now all that's left to do is to run it...: ``` for i in xrange(100): mat = approximate(mat, 1) mat = approximate(mat, .1) ``` I find this already gives a pretty accurate answer. After running for a while, the matrix I found was: ``` [ [1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597], [0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ], [0, 0, 1, 0 ], [0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ], ] ``` with an error of around `2.6e-5`. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that's because changing these entries would not change the result of the evaluation and so the change would never get carried along.) We can pass the matrix into OpenGL using `glLoadMatrix()` (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix): ``` def transpose(m): return [ [m[0][0], m[1][0], m[2][0], m[3][0]], [m[0][1], m[1][1], m[2][1], m[3][1]], [m[0][2], m[1][2], m[2][2], m[3][2]], [m[0][3], m[1][3], m[2][3], m[3][3]], ] glLoadMatrixf(transpose(mat)) ``` Now we can for example translate along the z axis to get different positions along the tracks: ``` glTranslate(0, 0, frame) frame = frame + 1 glBegin(GL_QUADS) glVertex3f(0, 0, 0) glVertex3f(0, 0, 1) glVertex3f(1, 0, 1) glVertex3f(1, 0, 0) glEnd() ``` [![With 3D translation](https://i.stack.imgur.com/dfeEx.gif)](https://i.stack.imgur.com/dfeEx.gif) For sure this is not very elegant from a mathematical point of view; you don't get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it's a brute force of sorts, but works, and works well. [![Choo choo!](https://i.stack.imgur.com/smdR8.png)](https://i.stack.imgur.com/smdR8.png)
76,204
<p>I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function).</p> <p>N.B. I am using .net 2.0 to process the XSLT</p> <p>Here is a sample of the XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom"&gt; &lt;id&gt;some id&lt;/id&gt; &lt;title&gt;some title&lt;/title&gt; &lt;updated&gt;2008-09-11T15:53:31+01:00&lt;/updated&gt; &lt;link rel="self" href="http://www.somefeedurl.co.uk" /&gt; &lt;author&gt; &lt;name&gt;some author&lt;/name&gt; &lt;uri&gt;http://someuri.co.uk&lt;/uri&gt; &lt;/author&gt; &lt;generator uri="http://aardvarkmedia.co.uk/"&gt;AardvarkMedia script&lt;/generator&gt; &lt;entry&gt; &lt;id&gt;http://soemaddress.co.uk/branded3/80406&lt;/id&gt; &lt;title type="html"&gt;My Ttile&lt;/title&gt; &lt;link rel="alternate" href="http://www.someurl.co.uk" /&gt; &lt;updated&gt;2008-02-13T00:00:00+01:00&lt;/updated&gt; &lt;published&gt;2002-09-11T14:16:20+01:00&lt;/published&gt; &lt;category term="mycategorytext" label="restaurant"&gt;Test&lt;/category&gt; &lt;content type="xhtml"&gt; &lt;div xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;div class="vcard"&gt; &lt;p class="fn org"&gt;some title&lt;/p&gt; &lt;p class="adr"&gt; &lt;abbr class="type" title="POSTAL" /&gt; &lt;span class="street-address"&gt;54 Some Street&lt;/span&gt; , &lt;span class="locality" /&gt; , &lt;span class="country-name"&gt;UK&lt;/span&gt; &lt;/p&gt; &lt;p class="tel"&gt; &lt;span class="value"&gt;0123456789&lt;/span&gt; &lt;/p&gt; &lt;div class="geo"&gt; &lt;span class="latitude"&gt;51.99999&lt;/span&gt; , &lt;span class="longitude"&gt;-0.123456&lt;/span&gt; &lt;/div&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Review&lt;/span&gt; &lt;span class="value"&gt;Some content&lt;/span&gt; &lt;/p&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Overall rating&lt;/span&gt; &lt;span class="value"&gt;8&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/content&gt; &lt;category term="cuisine-54" label="Spanish" /&gt; &lt;Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#"&gt; &lt;lat&gt;51.123456789&lt;/lat&gt; &lt;long&gt;-0.11111111&lt;/long&gt; &lt;/Point&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p>This is XSLT</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs"&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:key name="uniqueVenuesKey" match="entry" use="id"/&gt; &lt;xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/&gt; &lt;xsl:template match="/"&gt; &lt;locations&gt; &lt;!-- Get all unique venues --&gt; &lt;xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']"&gt; &lt;xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueName" select="*[local-name()='title']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"&gt;&lt;/xsl:variable&gt; &lt;location&gt; &lt;locationName&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/locationName&gt; &lt;category&gt; &lt;xsl:value-of select = "$CurrentCategory" /&gt; &lt;/category&gt; &lt;description&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/description&gt; &lt;venueAddress&gt; &lt;streetName&gt; &lt;xsl:value-of select = "$CurrentVenueAddress1" /&gt; &lt;/streetName&gt; &lt;town&gt; &lt;xsl:value-of select = "$CurrentVenueCity" /&gt; &lt;/town&gt; &lt;postcode&gt; &lt;xsl:value-of select = "$CurrentVenuePostcode" /&gt; &lt;/postcode&gt; &lt;wgs84_latitude&gt; &lt;xsl:value-of select = "$CurrentVenueLat" /&gt; &lt;/wgs84_latitude&gt; &lt;wgs84_longitude&gt; &lt;xsl:value-of select = "$CurrentVenueLong" /&gt; &lt;/wgs84_longitude&gt; &lt;/venueAddress&gt; &lt;venuePhone&gt; &lt;phonenumber&gt; &lt;xsl:value-of select = "$CurrentVenueTelephone" /&gt; &lt;/phonenumber&gt; &lt;/venuePhone&gt; &lt;/location&gt; &lt;/xsl:for-each&gt; &lt;/locations&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I'm trying to replace the $CurrentCategory variable the appropriate code to display <em>mycategorytext</em></p>
[ { "answer_id": 76497, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 5, "selected": true, "text": "<p>I don't have an XSLT editor here, but have you tried using</p>\n\n<pre><code>*[local-name()='category']/@*[loc...
2008/09/16
[ "https://Stackoverflow.com/questions/76204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258/" ]
I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function). N.B. I am using .net 2.0 to process the XSLT Here is a sample of the XML: ``` <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>some id</id> <title>some title</title> <updated>2008-09-11T15:53:31+01:00</updated> <link rel="self" href="http://www.somefeedurl.co.uk" /> <author> <name>some author</name> <uri>http://someuri.co.uk</uri> </author> <generator uri="http://aardvarkmedia.co.uk/">AardvarkMedia script</generator> <entry> <id>http://soemaddress.co.uk/branded3/80406</id> <title type="html">My Ttile</title> <link rel="alternate" href="http://www.someurl.co.uk" /> <updated>2008-02-13T00:00:00+01:00</updated> <published>2002-09-11T14:16:20+01:00</published> <category term="mycategorytext" label="restaurant">Test</category> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> <div class="vcard"> <p class="fn org">some title</p> <p class="adr"> <abbr class="type" title="POSTAL" /> <span class="street-address">54 Some Street</span> , <span class="locality" /> , <span class="country-name">UK</span> </p> <p class="tel"> <span class="value">0123456789</span> </p> <div class="geo"> <span class="latitude">51.99999</span> , <span class="longitude">-0.123456</span> </div> <p class="note"> <span class="type">Review</span> <span class="value">Some content</span> </p> <p class="note"> <span class="type">Overall rating</span> <span class="value">8</span> </p> </div> </div> </content> <category term="cuisine-54" label="Spanish" /> <Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#"> <lat>51.123456789</lat> <long>-0.11111111</long> </Point> </entry> </feed> ``` This is XSLT ``` <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs"> <xsl:output method="xml" indent="yes"/> <xsl:key name="uniqueVenuesKey" match="entry" use="id"/> <xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/> <xsl:template match="/"> <locations> <!-- Get all unique venues --> <xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']"> <xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" ></xsl:variable> <xsl:variable name="CurrentVenueName" select="*[local-name()='title']" ></xsl:variable> <xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" ></xsl:variable> <xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" ></xsl:variable> <xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" ></xsl:variable> <xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" ></xsl:variable> <xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" ></xsl:variable> <xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" ></xsl:variable> <xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"></xsl:variable> <location> <locationName> <xsl:value-of select = "$CurrentVenueName" /> </locationName> <category> <xsl:value-of select = "$CurrentCategory" /> </category> <description> <xsl:value-of select = "$CurrentVenueName" /> </description> <venueAddress> <streetName> <xsl:value-of select = "$CurrentVenueAddress1" /> </streetName> <town> <xsl:value-of select = "$CurrentVenueCity" /> </town> <postcode> <xsl:value-of select = "$CurrentVenuePostcode" /> </postcode> <wgs84_latitude> <xsl:value-of select = "$CurrentVenueLat" /> </wgs84_latitude> <wgs84_longitude> <xsl:value-of select = "$CurrentVenueLong" /> </wgs84_longitude> </venueAddress> <venuePhone> <phonenumber> <xsl:value-of select = "$CurrentVenueTelephone" /> </phonenumber> </venuePhone> </location> </xsl:for-each> </locations> </xsl:template> </xsl:stylesheet> ``` I'm trying to replace the $CurrentCategory variable the appropriate code to display *mycategorytext*
I don't have an XSLT editor here, but have you tried using ``` *[local-name()='category']/@*[local-name()='term'] ```
76,223
<p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p> <pre><code> for (int month = 0; month &lt; 13; month++) { GregorianCalendar d = new GregorianCalendar(); d.set(d.MONTH, month); System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH)); d.set(d.DAY_OF_WEEK, d.FRIDAY); d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH)); while (d.get(d.MONTH) &gt; month || d.get(d.MONTH) &lt; month) { d.add(d.WEEK_OF_MONTH, -1); } Date dt = d.getTime(); System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString()); } </code></pre>
[ { "answer_id": 76265, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 0, "selected": false, "text": "<p>That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to opt...
2008/09/16
[ "https://Stackoverflow.com/questions/76223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7008/" ]
I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year: ``` for (int month = 0; month < 13; month++) { GregorianCalendar d = new GregorianCalendar(); d.set(d.MONTH, month); System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH)); d.set(d.DAY_OF_WEEK, d.FRIDAY); d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH)); while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) { d.add(d.WEEK_OF_MONTH, -1); } Date dt = d.getTime(); System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString()); } ```
Based on [marked23's](https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437) suggestion: ``` public Date getLastFriday( int month, int year ) { Calendar cal = Calendar.getInstance(); cal.set( year, month + 1, 1 ); cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) ); return cal.getTime(); } ```