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
|
---|---|---|---|---|---|---|
247,331 |
<p>I'm using jQuery validate on a form I am building and it is working great. What I want to do is when something is invalid to have the text field change colors and the error message to be white. I figured the following CSS would work:</p>
<pre><code>label .error {color: white; font-weight: bold;}
input .error {background-color: pink; border: 1px dashed red; color: white}
</code></pre>
<p>When I test the validation the above CSS doesn't seem to apply. I checked using Firebug and the label and input area have the 'error' class applied.</p>
<p>The CSS seems valid as when I leave off the .error clause everything looks like I want it too. What am I doing wrong?</p>
|
[
{
"answer_id": 247341,
"author": "Dave",
"author_id": 32300,
"author_profile": "https://Stackoverflow.com/users/32300",
"pm_score": 2,
"selected": false,
"text": "<p>Try label.error and input.error without spaces.</p>\n"
},
{
"answer_id": 247343,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>One space can be one too much. Try:</p>\n\n<pre><code>label.error {color: white; font-weight: bold;}\ninput.error {background-color: pink; border: 1px dashed red; color: white}\n</code></pre>\n\n<p>Background info: </p>\n\n<pre><code>label .error /* selects all elements of class \"error\" *within* any label */\nlabel.error /* selects labels of class \"error\" */\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204/"
] |
I'm using jQuery validate on a form I am building and it is working great. What I want to do is when something is invalid to have the text field change colors and the error message to be white. I figured the following CSS would work:
```
label .error {color: white; font-weight: bold;}
input .error {background-color: pink; border: 1px dashed red; color: white}
```
When I test the validation the above CSS doesn't seem to apply. I checked using Firebug and the label and input area have the 'error' class applied.
The CSS seems valid as when I leave off the .error clause everything looks like I want it too. What am I doing wrong?
|
One space can be one too much. Try:
```
label.error {color: white; font-weight: bold;}
input.error {background-color: pink; border: 1px dashed red; color: white}
```
Background info:
```
label .error /* selects all elements of class "error" *within* any label */
label.error /* selects labels of class "error" */
```
|
247,369 |
<p>I am attempting to allow my web designers to use the metadata we have about database fields in the asp.net pages they are creating. The most obvious one is as follows:</p>
<pre><code><asp:TextBox runat="server" id="txTextBox" MaxLength="<Value From Metadata here>" ... />
</code></pre>
<p>All the required metadata is stored in our class objects and is accessible due to its public static nature.</p>
<p>The benefit of this would be that they can set values which</p>
<p><strong>a)</strong> might change without them being aware or caring<br>
<strong>b)</strong> improve the user experience with very little coding effort</p>
<p>and all without having them need worry about what the value is or where it has come from. This will primarily be used for automatically bound controls - i.e. ones which are added with little or no developer interaction. </p>
<p>This question is very similar to <a href="https://stackoverflow.com/questions/232986/xaml-binding-textbox-maxlength-to-class-constant">One of my previous questions</a> which now works wonderfully (but that was in WPF / XAML ).</p>
<p>The main point of this question is that I want as little developer requirement on this as possible - Ideally there would be some <code><%# Constant.Value %></code> type syntax which could be used directly within the <code>Maxlength=""</code> attribute of the asp:Textbox control meaning that no code needs to be added to a page/usercontrol at all.</p>
<p>I have a feeling it isn't possible, but I would love someone to prove me wrong.</p>
<p>Ta</p>
|
[
{
"answer_id": 247390,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should be able to do it with something like this</p>\n\n<pre><code><asp:TextBox runat=\"server\" id=\"txTextBox\" MaxLength=\"<%=Constants.SomeValue%>\" />\n</code></pre>\n\n<p>But my only concern is that this doesn't really make much sense. If the constant is stored in a .cs file in order to make a change that would cause the new constant value to be reflected in the UI you would have to recompile the site. I think it may be easier just to have a hard coded value in the .aspx page that can be changed easily without the need to recompile the entire codebase. Maybe I'm not understanding the problem though.</p>\n"
},
{
"answer_id": 247502,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "<p>You can use a data binding expression:</p>\n\n<pre><code><asp:TextBox MaxLength=\"<%# Constant.Value %>\" />\n</code></pre>\n\n<p><em>but</em>, that requires it to be in a databound control. If it's not in a repeater or somesuch, you'll need to call Container.DataBind() at some point in the page lifecycle.</p>\n\n<p>Alternatively, you could create an <a href=\"http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx\" rel=\"nofollow noreferrer\">ExpressionBuilder</a> which would allow syntax such as:</p>\n\n<pre><code><asp:TextBox MaxLength=\"<%$ Constants:Value %>\" />\n</code></pre>\n\n<p>Here's a sample that'll pull from a single static dictionary:</p>\n\n<pre><code>using System;\nusing System.Web.UI;\nusing System.Web.Compilation;\nusing System.CodeDom;\nusing System.Collections.Generic;\n\nclass ConstantsExpressionBuilder : ExpressionBuilder {\n private static readonly Dictionary<string, object> Values = \n new Dictionary<string, object>() {\n { \"Value1\", 12 },\n { \"Value2\", false },\n { \"Value3\", \"this is a test\" }\n };\n\n public override bool SupportsEvaluate { get { return true; } }\n\n public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {\n string key = entry.Expression.Trim();\n return GetValue(key);\n }\n\n public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {\n CodePrimitiveExpression keyExpression = new CodePrimitiveExpression(entry.Expression.Trim());\n return new CodeMethodInvokeExpression(this.GetType(), \"GetValue\", new CodeExpression[] { keyExpression }); \n }\n\n public static object GetValue(string key) {\n return Values[key];\n }\n}\n</code></pre>\n\n<p>You'd register this in web.config:</p>\n\n<pre><code><system.web>\n <compilation>\n <expressionBuilders>\n <add expressionPrefix=\"Constants\" type=\"ConstantsExpressionBuilder\" />\n </expressionBuilders>\n </compilation>\n</system.web>\n</code></pre>\n\n<p>And call it in an ASPX page:</p>\n\n<pre><code><asp:Textbox runat=\"server\" MaxLength=\"<%$ Constants:Value1 %>\" ReadOnly=\"<%$ Constants:Value2 %>\" Text=\"<%$ Constants:Value3 %>\" />\n</code></pre>\n\n<p>Which should produce:</p>\n\n<pre><code><input type=\"text\" maxlength=\"12\" readonly=\"false\" value=\"this is a test\" />\n</code></pre>\n\n<p>in the HTML output.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31128/"
] |
I am attempting to allow my web designers to use the metadata we have about database fields in the asp.net pages they are creating. The most obvious one is as follows:
```
<asp:TextBox runat="server" id="txTextBox" MaxLength="<Value From Metadata here>" ... />
```
All the required metadata is stored in our class objects and is accessible due to its public static nature.
The benefit of this would be that they can set values which
**a)** might change without them being aware or caring
**b)** improve the user experience with very little coding effort
and all without having them need worry about what the value is or where it has come from. This will primarily be used for automatically bound controls - i.e. ones which are added with little or no developer interaction.
This question is very similar to [One of my previous questions](https://stackoverflow.com/questions/232986/xaml-binding-textbox-maxlength-to-class-constant) which now works wonderfully (but that was in WPF / XAML ).
The main point of this question is that I want as little developer requirement on this as possible - Ideally there would be some `<%# Constant.Value %>` type syntax which could be used directly within the `Maxlength=""` attribute of the asp:Textbox control meaning that no code needs to be added to a page/usercontrol at all.
I have a feeling it isn't possible, but I would love someone to prove me wrong.
Ta
|
You can use a data binding expression:
```
<asp:TextBox MaxLength="<%# Constant.Value %>" />
```
*but*, that requires it to be in a databound control. If it's not in a repeater or somesuch, you'll need to call Container.DataBind() at some point in the page lifecycle.
Alternatively, you could create an [ExpressionBuilder](http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx) which would allow syntax such as:
```
<asp:TextBox MaxLength="<%$ Constants:Value %>" />
```
Here's a sample that'll pull from a single static dictionary:
```
using System;
using System.Web.UI;
using System.Web.Compilation;
using System.CodeDom;
using System.Collections.Generic;
class ConstantsExpressionBuilder : ExpressionBuilder {
private static readonly Dictionary<string, object> Values =
new Dictionary<string, object>() {
{ "Value1", 12 },
{ "Value2", false },
{ "Value3", "this is a test" }
};
public override bool SupportsEvaluate { get { return true; } }
public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
string key = entry.Expression.Trim();
return GetValue(key);
}
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
CodePrimitiveExpression keyExpression = new CodePrimitiveExpression(entry.Expression.Trim());
return new CodeMethodInvokeExpression(this.GetType(), "GetValue", new CodeExpression[] { keyExpression });
}
public static object GetValue(string key) {
return Values[key];
}
}
```
You'd register this in web.config:
```
<system.web>
<compilation>
<expressionBuilders>
<add expressionPrefix="Constants" type="ConstantsExpressionBuilder" />
</expressionBuilders>
</compilation>
</system.web>
```
And call it in an ASPX page:
```
<asp:Textbox runat="server" MaxLength="<%$ Constants:Value1 %>" ReadOnly="<%$ Constants:Value2 %>" Text="<%$ Constants:Value3 %>" />
```
Which should produce:
```
<input type="text" maxlength="12" readonly="false" value="this is a test" />
```
in the HTML output.
|
247,373 |
<p>I'm importing data from another system to MySQL, its a CSV file. The "Date" field however contains cryptic of 3-digit time entries, here's a random sample set:</p>
<pre><code>> 540
> 780
> 620
> 965
</code></pre>
<p>What's this? obviously its not 5:40 and 6:20. But it's not UNIX either (I tried 1225295<strong>XXX</strong> before I realized the time range this represents is about 16 minutes)</p>
<p>Anyone recognize these?</p>
<p><strong>Update</strong>: I just noticed that further down in the replies, a coworker who's closer to the data just <a href="https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#247456">opened a new SO account and added some more data</a>. It seems like these numeric entries are just time entries (not date). Still clueless. </p>
<p>IMHO, if no one can recognise this, then it probably isn't some (if obscure) standard time format and is more likely that these entries are foreign keys.</p>
<p><strong>Update 2</strong>: Many thanks to all! <a href="https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248123">we found the answer visually</a>, but as usual, <a href="https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248070">SO pulled through clutch</a>.</p>
|
[
{
"answer_id": 247381,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>I've seen some systems where the date is stored in a special table and elsewhere as an id to it. This might be one of them</p>\n"
},
{
"answer_id": 247386,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Swatch_Internet_Time\" rel=\"nofollow noreferrer\">swatch internet time</a></p>\n\n<p>day is divided into 1,000 equal parts. very metric altogether.</p>\n"
},
{
"answer_id": 247397,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>I think you'd be best off asking the original authors...</p>\n\n<p>Alternatively, can you insert a date into the old system and export it?\nIf you can do that then you should be able to reverse-engineer it very easily.</p>\n"
},
{
"answer_id": 247419,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>Are they are supposed to represent dates or times? If dates, then they are probably just an offset from a 'well known' epoch (like time_t are seconds from 1-Jan-70). </p>\n\n<p>If you don't have documentation to find the epoch you'll need an example to work it out from.</p>\n"
},
{
"answer_id": 247456,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This represent time, no date. And the same code-time appear in different date.</p>\n"
},
{
"answer_id": 247487,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>could be a julian date...?</p>\n"
},
{
"answer_id": 248070,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 4,
"selected": true,
"text": "<p>It's the number of minutes since midnight in five minute intervals. Your range of values should be 0 to 1440</p>\n"
},
{
"answer_id": 248100,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>There is no way to know for sure. I could be <a href=\"http://en.wikipedia.org/wiki/Swatch_Internet_Time\" rel=\"nofollow noreferrer\">beats</a>, but then again, it might not be. </p>\n"
},
{
"answer_id": 248123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the solution... thanks....</p>\n\n<p>hmoya</p>\n\n<p>9:00:00 AM 540\n9:15:00 AM 555\n9:30:00 AM 570\n9:45:00 AM 585\n10:00:00 AM 600\n10:15:00 AM 615\n10:30:00 AM 630\n10:45:00 AM 645\n11:00:00 AM 660\n11:15:00 AM 675\n11:30:00 AM 690\n11:45:00 AM 705\n12:00:00 PM 720\n12:15:00 PM 735\n12:30:00 PM 750\n12:45:00 PM 765\n1:00:00 PM 780\n1:15:00 PM 795\n1:30:00 PM 810\n1:45:00 PM 825\n2:00:00 PM 840\n2:15:00 PM 855\n2:30:00 PM 870\n2:45:00 PM 885\n3:00:00 PM 900\n3:15:00 PM 915\n3:30:00 PM 930\n3:45:00 PM 945\n4:00:00 PM 960\n4:15:00 PM 975\n4:30:00 PM 990\n4:45:00 PM 1005\n5:00:00 PM 1020\n5:15:00 PM 1035\n5:30:00 PM 1050\n5:45:00 PM 1065\n6:00:00 PM 1080\n6:15:00 PM 1095\n6:30:00 PM 1110\n6:45:00 PM 1125\n7:00:00 PM 1140</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] |
I'm importing data from another system to MySQL, its a CSV file. The "Date" field however contains cryptic of 3-digit time entries, here's a random sample set:
```
> 540
> 780
> 620
> 965
```
What's this? obviously its not 5:40 and 6:20. But it's not UNIX either (I tried 1225295**XXX** before I realized the time range this represents is about 16 minutes)
Anyone recognize these?
**Update**: I just noticed that further down in the replies, a coworker who's closer to the data just [opened a new SO account and added some more data](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#247456). It seems like these numeric entries are just time entries (not date). Still clueless.
IMHO, if no one can recognise this, then it probably isn't some (if obscure) standard time format and is more likely that these entries are foreign keys.
**Update 2**: Many thanks to all! [we found the answer visually](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248123), but as usual, [SO pulled through clutch](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248070).
|
It's the number of minutes since midnight in five minute intervals. Your range of values should be 0 to 1440
|
247,413 |
<p>Here's my binding source object: </p>
<pre><code>Public Class MyListObject
Private _mylist As New ObservableCollection(Of String)
Private _selectedName As String
Public Sub New(ByVal nameList As List(Of String), ByVal defaultName As String)
For Each name In nameList
_mylist.Add(name)
Next
_selectedName = defaultName
End Sub
Public ReadOnly Property MyList() As ObservableCollection(Of String)
Get
Return _mylist
End Get
End Property
Public ReadOnly Property SelectedName() As String
Get
Return _selectedName
End Get
End Property
End Class
</code></pre>
<p>Here is my XAML:</p>
<pre><code><Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication1"
>
<Window.Resources>
<ObjectDataProvider x:Key="MyListObject" ObjectInstance="" />
</Window.Resources>
<Grid>
<ComboBox Height="23"
Margin="24,91,53,0"
Name="ComboBox1"
VerticalAlignment="Top"
SelectedValue="{Binding Path=SelectedName, Source={StaticResource MyListObject}, Mode=OneWay}"
ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}, Mode=OneWay}"
/>
<Button Height="23"
HorizontalAlignment="Left"
Margin="47,0,0,87"
Name="btn_List1"
VerticalAlignment="Bottom"
Width="75">List 1</Button>
<Button Height="23"
Margin="0,0,75,87"
Name="btn_List2"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="75">List 2</Button>
</Grid>
</Window>
</code></pre>
<p>Here's the code-behind:</p>
<pre><code>Class Window1
Private obj1 As MyListObject
Private obj2 As MyListObject
Private odp As ObjectDataProvider
Public Sub New()
InitializeComponent()
Dim namelist1 As New List(Of String)
namelist1.Add("Joe")
namelist1.Add("Steve")
obj1 = New MyListObject(namelist1, "Steve")
.
Dim namelist2 As New List(Of String)
namelist2.Add("Bob")
namelist2.Add("Tim")
obj2 = New MyListObject(namelist2, "Tim")
odp = DirectCast(Me.FindResource("MyListObject"), ObjectDataProvider)
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List1.Click
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List2.Click
odp.ObjectInstance = obj2
End Sub
End Class
</code></pre>
<p>When the Window first loads, the bindings hook up fine. The ComboBox contains the names "Joe" and "Steve" and "Steve" is selected by default. However, when I click a button to switch the ObjectInstance to obj2, the ComboBox ItemsSource gets populated correctly in the dropdown, but the SelectedValue is set to Nothing instead of being equal to obj2.SelectedName.</p>
|
[
{
"answer_id": 247482,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 6,
"selected": true,
"text": "<p>We had a similar issue last week. It has to do with how <code>SelectedValue</code> updates its internals. What we found was if you set <code>SelectedValue</code> it would not see the change we had to instead set <code>SelectedItem</code> which would properly update every thing. My conclusion is that <code>SelectedValue</code> is <strong>designed for get</strong> operations and <strong>not set</strong>. But this may just be a bug in the current version of 3.5sp1 .net</p>\n"
},
{
"answer_id": 1241322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Ran into something similar, finally I just subscribed to the SelectionChanged event for the drop down and set my data property with it. Silly and wish it was not needed, but it worked.</p>\n"
},
{
"answer_id": 1262778,
"author": "Mikeb",
"author_id": 154630,
"author_profile": "https://Stackoverflow.com/users/154630",
"pm_score": 2,
"selected": false,
"text": "<p>Is it reasonable to set the <code>SelectedValuePath="Content"</code> in the combobox's xaml, and then use <code>SelectedValue</code> as the binding?</p>\n<p>It appears that you have a list of strings and want the binding to just do string matching against the actual item content in the combobox, so if you tell it which property to use for the <code>SelectedValue</code> it should work; at least, that worked for me when I ran across this problem.</p>\n<p>It seems like Content would be a sensible default for <code>SelectedValue</code> but perhaps it isn't?</p>\n"
},
{
"answer_id": 2405859,
"author": "Chuck Borcher",
"author_id": 289271,
"author_profile": "https://Stackoverflow.com/users/289271",
"pm_score": 0,
"selected": false,
"text": "<p>The Binding Mode needs to be OneWayToSource or TwoWay since the source is what you want updated. Mode OneWay is Source to Target and therefore makes the Source ReadOnly which results in never updating the Source.</p>\n"
},
{
"answer_id": 2503548,
"author": "VBRocks",
"author_id": 300305,
"author_profile": "https://Stackoverflow.com/users/300305",
"pm_score": 0,
"selected": false,
"text": "<p>You know... I've been fighting with this issue for hours today, and you know what I found out? It was a DataType issue! The list that was populating the ComboBox was Int64, and I was trying to store the value in an Int32 field! No errors were being thrown, it just wasn't storing the values!</p>\n"
},
{
"answer_id": 3301328,
"author": "ASeale",
"author_id": 398200,
"author_profile": "https://Stackoverflow.com/users/398200",
"pm_score": 4,
"selected": false,
"text": "<p>To stir up a 2 year old conversation:</p>\n\n<p>Another possibility, if you're wanting to use strings, is to bind it to the Text property of the combobox.</p>\n\n<pre><code><ComboBox Text=\"{Binding Test}\">\n <ComboBoxItem Content=\"A\" />\n <ComboBoxItem Content=\"B\" />\n <ComboBoxItem Content=\"C\" />\n</ComboBox>\n</code></pre>\n\n<p>That's bound to something like:</p>\n\n<pre><code>public class TestCode\n{\n private string _test;\n public string Test \n { \n get { return _test; }\n set\n {\n _test = value;\n NotifyPropertyChanged(() => Test); // NotifyPropertyChanged(\"Test\"); if not using Caliburn\n }\n }\n}\n</code></pre>\n\n<p>The above code is Two-Way so if you set Test=\"B\"; in code then the combobox will show 'B', and then if you select 'A' from the drop down then the bound property will reflect the change. </p>\n"
},
{
"answer_id": 5742784,
"author": "Dummy01",
"author_id": 461463,
"author_profile": "https://Stackoverflow.com/users/461463",
"pm_score": 3,
"selected": false,
"text": "<p>The type of the <code>SelectedValuePath</code> and the <code>SelectedValue</code> must be EXACTLY the same.</p>\n\n<p>If for example the type of <code>SelectedValuePath</code> is <code>Int16</code> and the type of the property that binds to <code>SelectedValue</code> is <code>int</code> it will not work.</p>\n\n<p>I spend hours to find that, and that's why I am answering here after so much time the question was asked. Maybe another poor guy like me with the same problem can see it.</p>\n"
},
{
"answer_id": 5986840,
"author": "Pavel Kovalev",
"author_id": 701869,
"author_profile": "https://Stackoverflow.com/users/701869",
"pm_score": 3,
"selected": false,
"text": "<p>Problem:</p>\n\n<p>The ComboBox class searches for the specified object by using the IndexOf method. This method uses the Equals method to determine equality.</p>\n\n<p>Solution:</p>\n\n<p>So, try to set SelectedIndex using SelectedValue via Converter like this:</p>\n\n<p><strong>C# code</strong></p>\n\n<pre><code>//Converter\n\npublic class SelectedToIndexConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value != null && value is YourType)\n {\n YourType YourSelectedValue = (YourType) value;\n\n YourSelectedValue = (YourType) cmbDowntimeDictionary.Tag;\n YourType a = (from dd in Helper.YourType\n where dd.YourTypePrimaryKey == YourSelectedValue.YourTypePrimaryKey\n select dd).First();\n\n int index = YourTypeCollection.IndexOf(a); //YourTypeCollection - Same as ItemsSource of ComboBox\n }\n return null;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value!=null && value is int)\n {\n return YourTypeCollection[(int) value];\n }\n\n return null;\n }\n }\n</code></pre>\n\n<p><strong>Xaml</strong></p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><ComboBox \n ItemsSource=\"{Binding Source={StaticResource YourDataProvider}}\"\n SelectedIndex=\"{Binding Path=YourValue, Mode=TwoWay, Converter={StaticResource SelectedToIndexConverter}, UpdateSourceTrigger=PropertyChanged}\"/>\n</code></pre>\n\n<p>Good luck! :)</p>\n"
},
{
"answer_id": 9167136,
"author": "davidinjc",
"author_id": 1193265,
"author_profile": "https://Stackoverflow.com/users/1193265",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried raising an event that signals SelectName has been updated, e.g., OnPropertyChanged(\"SelectedName\")? That worked for me.</p>\n"
},
{
"answer_id": 10529054,
"author": "Junier",
"author_id": 1386391,
"author_profile": "https://Stackoverflow.com/users/1386391",
"pm_score": 3,
"selected": false,
"text": "<p>Use </p>\n\n<pre><code>UpdateSourceTrigger=PropertyChanged \n</code></pre>\n\n<p>in the binding</p>\n"
},
{
"answer_id": 34274458,
"author": "Sam Darteh",
"author_id": 5679242,
"author_profile": "https://Stackoverflow.com/users/5679242",
"pm_score": 0,
"selected": false,
"text": "<p>Just resolved this. Huh!!!\nEither use [one of...] .SelectedValue | .SelectedItem | .SelectedText\nTip: Selected Value is preferred for ComboStyle.DropDownList while .SelectedText is for ComboStyle.DropDown.</p>\n\n<p>-This should solve your problem. took me more than a week to resolve this small fyn. hah!!</p>\n"
},
{
"answer_id": 55591489,
"author": "Rajon Tanducar",
"author_id": 6310002,
"author_profile": "https://Stackoverflow.com/users/6310002",
"pm_score": 1,
"selected": false,
"text": "<p>In my case I was binding to a list while I should be binding to a string. </p>\n\n<p><strong>What I was doing:</strong></p>\n\n<pre><code>private ObservableCollection<string> _SelectedPartyType;\n\npublic ObservableCollection<string> SelectedPartyType { get { return \n_SelectedPartyType; } set { \n _SelectedPartyType = value; OnPropertyChanged(\"SelectedPartyType\"); } }\n</code></pre>\n\n<p><strong>What should be</strong>\n </p>\n\n<pre><code> private string _SelectedPartyType;\n\n public string SelectedPartyType { get { return _SelectedPartyType; } set { \n _SelectedPartyType = value; OnPropertyChanged(\"SelectedPartyType\"); } }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
Here's my binding source object:
```
Public Class MyListObject
Private _mylist As New ObservableCollection(Of String)
Private _selectedName As String
Public Sub New(ByVal nameList As List(Of String), ByVal defaultName As String)
For Each name In nameList
_mylist.Add(name)
Next
_selectedName = defaultName
End Sub
Public ReadOnly Property MyList() As ObservableCollection(Of String)
Get
Return _mylist
End Get
End Property
Public ReadOnly Property SelectedName() As String
Get
Return _selectedName
End Get
End Property
End Class
```
Here is my XAML:
```
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication1"
>
<Window.Resources>
<ObjectDataProvider x:Key="MyListObject" ObjectInstance="" />
</Window.Resources>
<Grid>
<ComboBox Height="23"
Margin="24,91,53,0"
Name="ComboBox1"
VerticalAlignment="Top"
SelectedValue="{Binding Path=SelectedName, Source={StaticResource MyListObject}, Mode=OneWay}"
ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}, Mode=OneWay}"
/>
<Button Height="23"
HorizontalAlignment="Left"
Margin="47,0,0,87"
Name="btn_List1"
VerticalAlignment="Bottom"
Width="75">List 1</Button>
<Button Height="23"
Margin="0,0,75,87"
Name="btn_List2"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="75">List 2</Button>
</Grid>
</Window>
```
Here's the code-behind:
```
Class Window1
Private obj1 As MyListObject
Private obj2 As MyListObject
Private odp As ObjectDataProvider
Public Sub New()
InitializeComponent()
Dim namelist1 As New List(Of String)
namelist1.Add("Joe")
namelist1.Add("Steve")
obj1 = New MyListObject(namelist1, "Steve")
.
Dim namelist2 As New List(Of String)
namelist2.Add("Bob")
namelist2.Add("Tim")
obj2 = New MyListObject(namelist2, "Tim")
odp = DirectCast(Me.FindResource("MyListObject"), ObjectDataProvider)
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List1.Click
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List2.Click
odp.ObjectInstance = obj2
End Sub
End Class
```
When the Window first loads, the bindings hook up fine. The ComboBox contains the names "Joe" and "Steve" and "Steve" is selected by default. However, when I click a button to switch the ObjectInstance to obj2, the ComboBox ItemsSource gets populated correctly in the dropdown, but the SelectedValue is set to Nothing instead of being equal to obj2.SelectedName.
|
We had a similar issue last week. It has to do with how `SelectedValue` updates its internals. What we found was if you set `SelectedValue` it would not see the change we had to instead set `SelectedItem` which would properly update every thing. My conclusion is that `SelectedValue` is **designed for get** operations and **not set**. But this may just be a bug in the current version of 3.5sp1 .net
|
247,416 |
<p>I'm using several variants of the Validator controls (RequiredFieldValidator, CompareValidator, etc) and am using the CssClass property of the validator. I can see (via Firebug) that the class is being applied, but the validator control itself is adding a style element to it, namely color: red. But I don't want that. I want the control to use the cssclass only.</p>
<p>I know I can override the Forecolor attribute, but I'll have to do that on every validator in the project. And I'd really like to be able to just change my CSS Class in my stylesheet in case we have to change all the error message appearances in the future.</p>
<p>Anyone have any clues how to tell the Validator controls to NOT use their default styles?</p>
|
[
{
"answer_id": 247435,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at themes?</p>\n"
},
{
"answer_id": 247453,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 5,
"selected": true,
"text": "<p>You can do this in your css file:</p>\n\n<pre><code>.validator\n{\n color: blue !important;\n}\n</code></pre>\n\n<p>This will override the inline red style.</p>\n"
},
{
"answer_id": 247510,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 2,
"selected": false,
"text": "<p>If you use themes, you can set up your skin file to control the appearance of your validator. The problem with Forecolor inline is that the way .Net renders the default controls, it inserts a color=\"#...\" attribute that overrides CSS at the element level. If Keltex's solution above doesn't get it for you with the !important directive, your next step is probably to use/adapt/help work on the CSS-Friendly Control Adapters project at <a href=\"http://www.asp.net/CSSAdapters/\" rel=\"nofollow noreferrer\">http://www.asp.net/CSSAdapters/</a>.</p>\n\n<p>Shameless plug: Brian DeMarzo is working on extending this project at Google Code.</p>\n"
},
{
"answer_id": 14277151,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 3,
"selected": false,
"text": "<p>You can change the default style of validators using Themes.</p>\n\n<ul>\n<li>Right click on the website in Visual Studio</li>\n<li>Choose \"Add ASP.NET Folder\"</li>\n<li>Choose \"Themes\", name the new folder \"DefaultTheme\"</li>\n<li>Create a file called \"Controls.skin\" in the DefaultTheme folder</li>\n</ul>\n\n<p>Add the following to the Controls.skin file:</p>\n\n<pre><code><asp:RequiredFieldValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:RangeValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:CompareValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:RegularExpressionValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:CustomValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:ValidationSummary runat=\"server\" CssClass=\"validation-error\" />\n</code></pre>\n\n<p>Merge the following into your <code>web.config</code>:</p>\n\n<pre><code><configuration>\n <system.web>\n <pages theme=\"DefaultTheme\" />\n </system.web>\n</configuration>\n</code></pre>\n\n<p>Then you can set whatever colour you want for <code>.validation-error</code> in your CSS files.</p>\n\n<p>(Note that versions of ASP.Net before 4.0 used to apply <code>style=\"Color:red\"</code> to all validators by default, making it hard to override their colours in CSS. If you find that is affecting you, then you can override it by setting the <code>ForeColor</code> property on each of the theme elements above, or add <code>!important</code> to your CSS rule.)</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms247256%28v=vs.100%29.aspx\" rel=\"noreferrer\">How to: Define ASP.NET Page Themes</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/0yy5hxdk%28v=vs.100%29.aspx\" rel=\"noreferrer\">How to: Apply ASP.NET Themes</a></li>\n<li><a href=\"http://www.codeproject.com/Articles/85786/Validation-Controls-Lost-Their-Red-Color\" rel=\"noreferrer\">Validation Controls Lost Their Red Color</a> in ASP.Net 4.0</li>\n</ul>\n"
},
{
"answer_id": 37847764,
"author": "Eyad Eyadian",
"author_id": 5520809,
"author_profile": "https://Stackoverflow.com/users/5520809",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Set Forecolor=\"\"\n</code></pre>\n\n<p>And </p>\n\n<pre><code>CssClass=\"your-css-class\"\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
I'm using several variants of the Validator controls (RequiredFieldValidator, CompareValidator, etc) and am using the CssClass property of the validator. I can see (via Firebug) that the class is being applied, but the validator control itself is adding a style element to it, namely color: red. But I don't want that. I want the control to use the cssclass only.
I know I can override the Forecolor attribute, but I'll have to do that on every validator in the project. And I'd really like to be able to just change my CSS Class in my stylesheet in case we have to change all the error message appearances in the future.
Anyone have any clues how to tell the Validator controls to NOT use their default styles?
|
You can do this in your css file:
```
.validator
{
color: blue !important;
}
```
This will override the inline red style.
|
247,422 |
<p>I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail.</p>
<p>Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?</p>
|
[
{
"answer_id": 247436,
"author": "Josh",
"author_id": 5233,
"author_profile": "https://Stackoverflow.com/users/5233",
"pm_score": 4,
"selected": true,
"text": "<p>I haven't worked with Excel, but with VSTO in Word, attaching the debugger to the WINWORD process works, but makes it impossible to debug startup code, as it has already ran before you can attach. In this case you can insert</p>\n\n<pre><code>Debugger.Launch();\n</code></pre>\n\n<p>which will stop your code and ask to attach a debugger. It's about the best solution I could find.</p>\n"
},
{
"answer_id": 247565,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 0,
"selected": false,
"text": "<p>I was using VS2008 and VSTO 2005 (Office 2003), and I can debug directly from VS itself. Not quite sure about VS2005, I assume it should be the same.</p>\n"
},
{
"answer_id": 401292,
"author": "Øyvind Skaar",
"author_id": 49194,
"author_profile": "https://Stackoverflow.com/users/49194",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this, it should be no different from Word.\nCheck if you have multiple processes. Ensure that your add-in is actually loaded. It may be banned from starting. Check settings under Add-Ins and see if it is listed as deactivated.</p>\n"
},
{
"answer_id": 3148119,
"author": "AMissico",
"author_id": 163921,
"author_profile": "https://Stackoverflow.com/users/163921",
"pm_score": 2,
"selected": false,
"text": "<p>I usually include a \"StopSwitch\" which launches the debugger when the stop-switch is enabled in the app.config file.</p>\n\n<ul>\n<li><em>StopSwitch Stops Execution for Just-In-Time Debugging</em> at <a href=\"http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!309.entry\" rel=\"nofollow noreferrer\">http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!309.entry</a>)</li>\n</ul>\n\n<p>After enabling the <code>StopSwitch</code>, sometimes the JIT Debugger is not launch because the problem occurs before the .NET Framework loads the assembly and executes the <code>Stop</code> statement.</p>\n"
},
{
"answer_id": 36308454,
"author": "Janiek Buysrogge",
"author_id": 288851,
"author_profile": "https://Stackoverflow.com/users/288851",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this with a Word add-in, but I had to disable 'Just My Code' in the debugger options.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18818/"
] |
I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail.
Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?
|
I haven't worked with Excel, but with VSTO in Word, attaching the debugger to the WINWORD process works, but makes it impossible to debug startup code, as it has already ran before you can attach. In this case you can insert
```
Debugger.Launch();
```
which will stop your code and ask to attach a debugger. It's about the best solution I could find.
|
247,430 |
<p>Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?</p>
<pre><code>obj.property1 = from.property1;
obj.property2 = from.property2;
</code></pre>
<p>etc.</p>
<p>Thanks,
Dani</p>
|
[
{
"answer_id": 248091,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 4,
"selected": true,
"text": "<p>If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:</p>\n\n<pre><code>classdef Foo < handle\n properties\n a = 1;\n end\n methods\n function F=Foo(rhs)\n if nargin==0\n % default constructor\n F.a = rand(1);\n else\n % copy constructor\n fns = properties(rhs);\n for i=1:length(fns)\n F.(fns{i}) = rhs.(fns{i});\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>and some test code:</p>\n\n<pre><code>f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.\n</code></pre>\n"
},
{
"answer_id": 1760151,
"author": "Gui",
"author_id": 214217,
"author_profile": "https://Stackoverflow.com/users/214217",
"pm_score": 2,
"selected": false,
"text": "<p>You can even use </p>\n\n<pre><code>try\n F.(fns{i}) = rhs.(fns{i});\nend\n</code></pre>\n\n<p>which makes the method more useful</p>\n"
},
{
"answer_id": 16170645,
"author": "Navan",
"author_id": 156525,
"author_profile": "https://Stackoverflow.com/users/156525",
"pm_score": 4,
"selected": false,
"text": "<p>There is another easy way to create copies of handle objects by using matlab.mixin.Copyable. If you inherit from this class you will get a copy method which will copy all the properties for you.</p>\n\n<pre><code>classdef YourClass < matlab.mixin.Copyable\n...\n\na = YourClass;\nb = copy(a); % b is a copy of a\n</code></pre>\n\n<p>This copy method creates a copy without calling constructors or set functions of properties. So this should be faster. You can also customize the copy behavior by overriding some methods.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28772/"
] |
Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?
```
obj.property1 = from.property1;
obj.property2 = from.property2;
```
etc.
Thanks,
Dani
|
If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:
```
classdef Foo < handle
properties
a = 1;
end
methods
function F=Foo(rhs)
if nargin==0
% default constructor
F.a = rand(1);
else
% copy constructor
fns = properties(rhs);
for i=1:length(fns)
F.(fns{i}) = rhs.(fns{i});
end
end
end
end
end
```
and some test code:
```
f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.
```
|
247,442 |
<p>I have a JAX-RPC (Java) web service that needs to return a complex polymorphic value. To be more specific, the class structure is something like this:</p>
<pre><code>abstract class Child {
}
class Question extends Child {
private String name;
// other fields, getters, and setters
}
class Section extends Child {
private String label;
private Child[] children;
// getters and setters
}
class Quiz {
private Child[] elements;
// getter and setter
}
</code></pre>
<p>My web service has a method that returns a Quiz, which of course may contain Questions and Sections which may contain Questions and other Sections, and so on and so forth. However, when I generate the WSDL, only Child and Quiz make it in. When I call the web service, I get back a Quiz element with the right number of children, but they're all Child elements, and they're all empty.</p>
<p>Is there a good way to make this work, short of just returning XML as a String?</p>
<p>Before anyone asks, due to circumstances beyond my control, I cannot use JAX-WS.</p>
|
[
{
"answer_id": 247458,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 0,
"selected": false,
"text": "<p>I had to deal with the same issue. But I ended up using a combobox with paging support and auto complete. Currently this combobox happens to be from Telerik. Its a comboBox for auto complete since you can't type into a droplist.</p>\n"
},
{
"answer_id": 247475,
"author": "Slapout",
"author_id": 19072,
"author_profile": "https://Stackoverflow.com/users/19072",
"pm_score": 0,
"selected": false,
"text": "<p>I agree that no user is going to want to look thru 25,000 items to find the one they want. Is there some way you can limit the data so that they drill down? Like selecting a region or type of company first and then showing the ones that match? </p>\n"
},
{
"answer_id": 250614,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": true,
"text": "<p>I think your idea for the autocomplete extender is the best solution. I've had this problem as well (sounds similar--a project you are taking over from somebody else). The push-back often comes from the user side. They are used to being able to select from a list of items. Unfortunately as the database grows, this becomes less and less feasible.</p>\n\n<p>But when you have 0.5MB of html downloaded on the page (not including the viewstate), compromises have to be made.</p>\n\n<p>Why do you think you need to create modal popup? Can't you just have the extender on your data entry page?</p>\n"
},
{
"answer_id": 254551,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>Multiple cascading ListBoxes, each futher refining the resultset of the previous</li>\n<li>AJAX <a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx\" rel=\"nofollow noreferrer\">AutoCompleteExtender</a></li>\n</ul>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25498/"
] |
I have a JAX-RPC (Java) web service that needs to return a complex polymorphic value. To be more specific, the class structure is something like this:
```
abstract class Child {
}
class Question extends Child {
private String name;
// other fields, getters, and setters
}
class Section extends Child {
private String label;
private Child[] children;
// getters and setters
}
class Quiz {
private Child[] elements;
// getter and setter
}
```
My web service has a method that returns a Quiz, which of course may contain Questions and Sections which may contain Questions and other Sections, and so on and so forth. However, when I generate the WSDL, only Child and Quiz make it in. When I call the web service, I get back a Quiz element with the right number of children, but they're all Child elements, and they're all empty.
Is there a good way to make this work, short of just returning XML as a String?
Before anyone asks, due to circumstances beyond my control, I cannot use JAX-WS.
|
I think your idea for the autocomplete extender is the best solution. I've had this problem as well (sounds similar--a project you are taking over from somebody else). The push-back often comes from the user side. They are used to being able to select from a list of items. Unfortunately as the database grows, this becomes less and less feasible.
But when you have 0.5MB of html downloaded on the page (not including the viewstate), compromises have to be made.
Why do you think you need to create modal popup? Can't you just have the extender on your data entry page?
|
247,471 |
<p>I'm trying to build a shared library (DLL) on Windows, using MSVC 6 (retro!) and I have a peculiar link issue I need to resolve. My shared library must access some global state, controlled by the loading application.</p>
<p>Broadly, what I have is this:</p>
<p>application.c:</p>
<pre><code>static int g_private_value;
int use_private_value() {
/* do something with g_private_value */
}
int main (...) {
return shared_library_method ();
}
</code></pre>
<p>shared_library.c:</p>
<pre><code>__declspec(dllexport) int __stdcall shared_library_method() {
use_private_value();
}
</code></pre>
<p>(<strong>Updated</strong> - I forgot the <code>__declspec(dllexport) int __stdcall</code> portion, but it's there in the real code)</p>
<p>How do I set up shared_library.dll so that it exports <code>shared_library_method</code> and imports <code>use_private_value</code>?</p>
<p>Please remember that A) I'm a unix programmer, generally, and B) that I'm doing this without Visual Studio; our automated build infrastructure drives MSVC with makefiles. If I'm omitting something that will make it easier to answer the question, please comment and I'll update it ASAP.</p>
|
[
{
"answer_id": 247588,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 1,
"selected": false,
"text": "<p>I'll start with half of the answer.</p>\n\n<p>In shared_library.c:</p>\n\n<pre><code>__declspec(dllexport) int __stdcall shared_library_method(void)\n{\n\n\n}\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/z4zxe9k8(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN article</a> about exporting function from DLL:s.</p>\n"
},
{
"answer_id": 247669,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 2,
"selected": false,
"text": "<p>This is actually going to be pretty difficult to get working. On Unix/Linux you can have shared objects and applications import symbols from each other, but on Windows you can't have a DLL import symbols from the application that loads it: the Windows PE executable format just doesn't support that idiom.</p>\n\n<p>I know that the Cygwin project have some sort of work-around to address this problem, but I don't believe that it's trivial. Unless you want to do lots of PE-related hacking you probably don't want to go there.</p>\n\n<p>An easier solution might be to just have some sort of initializer method exported from the DLL:</p>\n\n<pre><code>typedef int (*func_ptr)();\nvoid init_library(func_ptr func);\n</code></pre>\n\n<p>The application must call this at start-up, passing in the address of the function you want to share. Not exactly elegant, but it should work okay.</p>\n"
},
{
"answer_id": 247694,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 1,
"selected": false,
"text": "<p>For the second half you need to export the functions from your application.c.\nYou can do this in the linker with:</p>\n\n<pre><code>/export:use_private_value@0\n</code></pre>\n\n<p>This should get you a lib-file that you build with your DLL.</p>\n\n<p>The option to link the lib-file is to use GetProcAddress().</p>\n\n<p>As DavidK noted if you only have a few functions it is probably easier to pass the function pointers in an init function. It is however possible to do what you are asking for.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
I'm trying to build a shared library (DLL) on Windows, using MSVC 6 (retro!) and I have a peculiar link issue I need to resolve. My shared library must access some global state, controlled by the loading application.
Broadly, what I have is this:
application.c:
```
static int g_private_value;
int use_private_value() {
/* do something with g_private_value */
}
int main (...) {
return shared_library_method ();
}
```
shared\_library.c:
```
__declspec(dllexport) int __stdcall shared_library_method() {
use_private_value();
}
```
(**Updated** - I forgot the `__declspec(dllexport) int __stdcall` portion, but it's there in the real code)
How do I set up shared\_library.dll so that it exports `shared_library_method` and imports `use_private_value`?
Please remember that A) I'm a unix programmer, generally, and B) that I'm doing this without Visual Studio; our automated build infrastructure drives MSVC with makefiles. If I'm omitting something that will make it easier to answer the question, please comment and I'll update it ASAP.
|
This is actually going to be pretty difficult to get working. On Unix/Linux you can have shared objects and applications import symbols from each other, but on Windows you can't have a DLL import symbols from the application that loads it: the Windows PE executable format just doesn't support that idiom.
I know that the Cygwin project have some sort of work-around to address this problem, but I don't believe that it's trivial. Unless you want to do lots of PE-related hacking you probably don't want to go there.
An easier solution might be to just have some sort of initializer method exported from the DLL:
```
typedef int (*func_ptr)();
void init_library(func_ptr func);
```
The application must call this at start-up, passing in the address of the function you want to share. Not exactly elegant, but it should work okay.
|
247,474 |
<p>A path in Perforce contains files a.txt and b.txt. I'll refer to the main path as mainline.</p>
<p>I've create a branch (called initialbranch) from there which contains just a.txt. I make lots of changes to a.txt, and am very happy with it. However, it's not yet ready for submitting back to mainline. I can easily integrate any changes to a.txt that occur in mainline.</p>
<p>Another project comes along, which needs the changes from initialbranch. Now, say I want to make changes to b.txt, and want to be able to integrate changes that happen both in initialbranch and in mainline. At present, I'm branching from initialbranch (call this new branch secondbranch). Previously I've been adding b.txt to initialbranch, and then integrating my changes across to secondbranch. Is there a nicer way to do this?</p>
<p>Sorry if this question seems somewhat convoluted, I've expressed it as best I can!</p>
<p>Thanks,</p>
<p>Dom</p>
|
[
{
"answer_id": 247566,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not convinced I understand your question, but I'll try to help. </p>\n\n<p>If you're saying that you don't really want b.txt in initialbranch, you can define a branch specification like this:</p>\n\n<pre><code>initialbranch/a.txt secondbranch/a.txt\nmainline/b.txt secondbranch/b.txt\n</code></pre>\n\n<p>That way, when you integrate using the \"secondbranch\" branch spec, your changes in secondbranch will get pushed to initialbranch or mainline.</p>\n\n<p>If you don't want to push changes directly from secondbranch to mainline, then do what it sounds like you are already doing: integrate b.txt from mainline to initialbranch, then from initialbranch to secondbranch. Work on it in secondbranch, then integrate the changes successively back to initialbranch and mainline.</p>\n"
},
{
"answer_id": 247665,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps a diagram might help?</p>\n\n<pre><code> a,b------------------------------------------------------> mainline\n \\ branched / integrated back in\n \\-a----------------------------------/------------> initialbranch\n copied from mainline /\n -b-------------------/--------------> secondbranch\n</code></pre>\n\n<p>Branching in perforce is inexpensive, so I would normally branch an entire directory structure rather than individual files.</p>\n\n<p>Its not too late to do this. As erickson says, rather than copy/add the file to secondbranch, you can just branch from mainline into your dev branches.</p>\n\n<pre><code> a,b--------------------------------------------------> mainline\n \\ branched \\ / integrated back in\n \\-a-----------\\---------------------------/----> initialbranch\n \\ branched from mainline /\n -b-----------------------------> secondbranch\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20972/"
] |
A path in Perforce contains files a.txt and b.txt. I'll refer to the main path as mainline.
I've create a branch (called initialbranch) from there which contains just a.txt. I make lots of changes to a.txt, and am very happy with it. However, it's not yet ready for submitting back to mainline. I can easily integrate any changes to a.txt that occur in mainline.
Another project comes along, which needs the changes from initialbranch. Now, say I want to make changes to b.txt, and want to be able to integrate changes that happen both in initialbranch and in mainline. At present, I'm branching from initialbranch (call this new branch secondbranch). Previously I've been adding b.txt to initialbranch, and then integrating my changes across to secondbranch. Is there a nicer way to do this?
Sorry if this question seems somewhat convoluted, I've expressed it as best I can!
Thanks,
Dom
|
I'm not convinced I understand your question, but I'll try to help.
If you're saying that you don't really want b.txt in initialbranch, you can define a branch specification like this:
```
initialbranch/a.txt secondbranch/a.txt
mainline/b.txt secondbranch/b.txt
```
That way, when you integrate using the "secondbranch" branch spec, your changes in secondbranch will get pushed to initialbranch or mainline.
If you don't want to push changes directly from secondbranch to mainline, then do what it sounds like you are already doing: integrate b.txt from mainline to initialbranch, then from initialbranch to secondbranch. Work on it in secondbranch, then integrate the changes successively back to initialbranch and mainline.
|
247,479 |
<p>Does anyone know of a script that can select all text references to URLs and automatically replace them with anchor tags pointing to those locations?</p>
<pre><code>For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
</code></pre>
<p>Note: I am wanting this because I don't want to go through all my content and wrap them with anchor tags. </p>
|
[
{
"answer_id": 247542,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 5,
"selected": true,
"text": "<p>JQuery isn't going to help you a whole lot here as you're not really concerned with DOM traversal/manipulation (other than creating the anchor tag). If all your URLs were in <p class=\"url\"> tags then perhaps.</p>\n\n<p>A vanilla JavaScript solution is probably what you want, and as fate would have it, <a href=\"https://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript\">this guy should have you covered</a>.</p>\n"
},
{
"answer_id": 247558,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest you do this on your static pages before rendering to the browser, or you'll be pushing the burden of conversion computation onto your poor visitors. :) Here's how you might do it in Ruby (reading from stdin, writing to stdout):</p>\n\n<pre><code>while line = gets\n puts line.gsub( /(^|[^\"'])(http\\S+)/, \"\\\\1<a href='\\\\2'>\\\\2</a>\" )\nend\n</code></pre>\n\n<p>Obviously, you'll want to think about how to make this as robust as you desire. The above requires all URLs to start with http, and will check not to convert URLs that are in quotes (i.e. which may already be inside an <a href=\"...\">). It will not catch ftp://, mailto:. It will happily convert material in places like <script> bodies, which you may not want to happen.</p>\n\n<p>The most satisfactory solution is really to do the conversion by hand with your editor so you can eyeball and approve all substitutions. <a href=\"http://purepistos.net/diakonos\" rel=\"nofollow noreferrer\">A good editor</a> will let you do regexp substitution with group references (aka back references), so it shouldn't be a big deal.</p>\n"
},
{
"answer_id": 247579,
"author": "DGM",
"author_id": 14253,
"author_profile": "https://Stackoverflow.com/users/14253",
"pm_score": 0,
"selected": false,
"text": "<p>If you want a solution from another perspective... if you can run the pages through php and HTML Purifier, it can autoformat the output and linkify any urls.</p>\n"
},
{
"answer_id": 248901,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 6,
"selected": false,
"text": "<p><strong>NOTE:</strong> An updated and corrected version of this script is now available at <a href=\"https://github.com/maranomynet/linkify\" rel=\"nofollow noreferrer\">https://github.com/maranomynet/linkify</a> (GPL/MIT licence)</p>\n\n<hr>\n\n<p>Hmm... to me this seems like the perfect task for jQuery.</p>\n\n<p>...something like this came off the top of my mind:</p>\n\n<pre><code>// Define: Linkify plugin\n(function($){\n\n var url1 = /(^|&lt;|\\s)(www\\..+?\\..+?)(\\s|&gt;|$)/g,\n url2 = /(^|&lt;|\\s)(((https?|ftp):\\/\\/|mailto:).+?)(\\s|&gt;|$)/g,\n\n linkifyThis = function () {\n var childNodes = this.childNodes,\n i = childNodes.length;\n while(i--)\n {\n var n = childNodes[i];\n if (n.nodeType == 3) {\n var html = $.trim(n.nodeValue);\n if (html)\n {\n html = html.replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(url1, '$1<a href=\"http://$2\">$2</a>$3')\n .replace(url2, '$1<a href=\"$2\">$2</a>$5');\n $(n).after(html).remove();\n }\n }\n else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {\n linkifyThis.call(n);\n }\n }\n };\n\n $.fn.linkify = function () {\n return this.each(linkifyThis);\n };\n\n})(jQuery);\n\n// Usage example:\njQuery('div.textbody').linkify();\n</code></pre>\n\n<p>It attempts to turn all occurrences of the following into links:</p>\n\n<ul>\n<li><code>www.example.com/path</code></li>\n<li><code>http://www.example.com/path</code></li>\n<li><code>mailto:[email protected]</code></li>\n<li><code>ftp://www.server.com/path</code></li>\n<li>...all of the above wrapped in angle brackets (i.e. <code><</code>...<code>></code>)</li>\n</ul>\n\n<p>Enjoy :-)</p>\n"
},
{
"answer_id": 3755427,
"author": "mynameistechno",
"author_id": 271442,
"author_profile": "https://Stackoverflow.com/users/271442",
"pm_score": 1,
"selected": false,
"text": "<p>Doing this server-side is not an option sometimes. Think of a client-side Twitter widget (that goes directly to Twitter API using jsonp), and you want to linkify all the URLs in the Tweets dynamically...</p>\n"
},
{
"answer_id": 7031994,
"author": "MauroPorras",
"author_id": 320791,
"author_profile": "https://Stackoverflow.com/users/320791",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at this JQuery plugin: <a href=\"https://code.google.com/p/jquery-linkifier/\" rel=\"nofollow\">https://code.google.com/p/jquery-linkifier/</a></p>\n"
},
{
"answer_id": 11359292,
"author": "Kimtho6",
"author_id": 451571,
"author_profile": "https://Stackoverflow.com/users/451571",
"pm_score": 3,
"selected": false,
"text": "<p>I have this function i call </p>\n\n<pre><code>textToLinks: function(text) {\n\n var re = /(https?:\\/\\/(([-\\w\\.]+)+(:\\d+)?(\\/([\\w/_\\.]*(\\?\\S+)?)?)?))/g;\n return text.replace(re, \"<a href=\\\"$1\\\" title=\\\"\\\">$1</a>\");\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
Does anyone know of a script that can select all text references to URLs and automatically replace them with anchor tags pointing to those locations?
```
For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
```
Note: I am wanting this because I don't want to go through all my content and wrap them with anchor tags.
|
JQuery isn't going to help you a whole lot here as you're not really concerned with DOM traversal/manipulation (other than creating the anchor tag). If all your URLs were in <p class="url"> tags then perhaps.
A vanilla JavaScript solution is probably what you want, and as fate would have it, [this guy should have you covered](https://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript).
|
247,483 |
<p>I need to do an <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">HTTP GET</a> request in JavaScript. What's the best way to do that?</p>
<p>I need to do this in a Mac OS X dashcode widget.</p>
|
[
{
"answer_id": 247489,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a></p>\n\n<p>You'd be best off using a library such as <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a> or <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a>.</p>\n"
},
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "<p>Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.</p>\n\n<p>In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.</p>\n\n<pre><code>var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.prototypejs.org\" rel=\"noreferrer\">Prototype</a> makes it dead simple</p>\n\n<pre><code>new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://api.jquery.com/jQuery.get/\" rel=\"noreferrer\">In jQuery</a>:</p>\n\n<pre><code>$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n</code></pre>\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "<p>IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.</p>\n\n<p>Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:</p>\n\n<pre><code>var sURL = '/your/url.html?' + (new Date()).getTime();\n</code></pre>\n\n<p>This will append a unique timestamp to the end of the URL and will prevent any caching from happening.</p>\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>In your widget's Info.plist file, don't forget to set your <code>AllowNetworkAccess</code> key to true.</p>\n"
},
{
"answer_id": 248726,
"author": "Nikola Stjelja",
"author_id": 32582,
"author_profile": "https://Stackoverflow.com/users/32582",
"pm_score": 3,
"selected": false,
"text": "<p>The best way is to use AJAX ( you can find a simple tutorial on this page <a href=\"http://www.tizag.com/"Tizag"\" rel=\"noreferrer\">Tizag</a>). The reason is that any other technique you may use requires more code, it is not guaranteed to work cross browser without rework and requires you use more client memory by opening hidden pages inside frames passing urls parsing their data and closing them. \nAJAX is the way to go in this situation. That my two years of javascript heavy development speaking. </p>\n"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequests</a>, I'd use <a href=\"http://docs.jquery.com/Ajax/jQuery.get#examples\" rel=\"noreferrer\">jQuery</a> and do something like this:</p>\n\n<pre><code>var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n</code></pre>\n"
},
{
"answer_id": 3429189,
"author": "apaderno",
"author_id": 225647,
"author_profile": "https://Stackoverflow.com/users/225647",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.</p>\n\n<p>As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.</p>\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "<p>Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:</p>\n\n<pre><code>function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n</code></pre>\n\n<p>However, synchronous requests are discouraged and will generate a warning along the lines of:</p>\n\n<blockquote>\n <p>Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), <strong>synchronous requests on the main thread have been deprecated</strong> due to the negative effects to the user experience.</p>\n</blockquote>\n\n<p>You should make an asynchronous request and handle the response inside an event handler.</p>\n\n<pre><code>function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n</code></pre>\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "<p>A version without callback</p>\n\n<pre><code>var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n</code></pre>\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "<p>Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.</p>\n\n<p>Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.</p>\n\n<pre><code>var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n</code></pre>\n\n<p>Using it is as easy as:</p>\n\n<pre><code>var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n</code></pre>\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>A copy-paste modern version <em>( using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"noreferrer\">fetch</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"noreferrer\">arrow function</a> )</em> :</p>\n</blockquote>\n\n<pre><code>//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n</code></pre>\n\n<blockquote>\n <p>A copy-paste classic version:</p>\n</blockquote>\n\n<pre><code>let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n</code></pre>\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "<p>You can get an HTTP GET request in two ways:</p>\n\n<ol>\n<li><p>This approach based on xml format. You have to pass the URL for the request. </p>\n\n<pre><code>xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n</code></pre></li>\n<li><p>This one is based on jQuery. You have to specify the URL and function_name you want to call.</p>\n\n<pre><code>$(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "<p>For those who use <a href=\"https://docs.angularjs.org/api/ng/service/$http\" rel=\"noreferrer\">AngularJs</a>, it's <code>$http.get</code>:</p>\n\n<pre><code>$http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n</code></pre>\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n</code></pre>\n\n<p>Same thing can be done for post request as well.<br>\nHave a look at this link <a href=\"https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit\">JavaScript post request like a form submit</a></p>\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "<p>The new <a href=\"https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en\" rel=\"noreferrer\"><code>window.fetch</code></a> API is a cleaner replacement for <code>XMLHttpRequest</code> that makes use of ES6 promises. There's a nice explanation <a href=\"https://jakearchibald.com/2015/thats-so-fetch/\" rel=\"noreferrer\">here</a>, but it boils down to (from the article):</p>\n\n<pre><code>fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n</code></pre>\n\n<p><a href=\"http://caniuse.com/#feat=fetch\" rel=\"noreferrer\">Browser support</a> is now good in the latest releases (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), however IE will likely not get official support. <a href=\"https://github.com/github/fetch\" rel=\"noreferrer\">GitHub has a polyfill</a> available which is recommended to support older browsers still largely in use (esp versions of Safari pre March 2017 and mobile browsers from the same period).</p>\n\n<p>I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.</p>\n\n<p>Here's a link to the spec <a href=\"https://fetch.spec.whatwg.org/\" rel=\"noreferrer\">https://fetch.spec.whatwg.org/</a></p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>Using ES7 async/await, this becomes simply (based on <a href=\"https://gist.github.com/msmfsd/fca50ab095b795eb39739e8c4357a808\" rel=\"noreferrer\">this Gist</a>):</p>\n\n<pre><code>async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>One solution supporting older browsers:</p>\n\n<pre><code>function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n</code></pre>\n\n<p>Maybe somewhat overkill but you definitely go safe with this code.</p>\n\n<p><strong>Usage:</strong>\n<br></p>\n\n<pre><code>//create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n</code></pre>\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with pure JS too:</p>\n\n<pre><code>// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n</code></pre>\n\n<p>See: for more details: <a href=\"https://www.html5rocks.com/en/tutorials/cors/\" rel=\"nofollow noreferrer\">html5rocks tutorial</a></p>\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Short and clean:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const http = new XMLHttpRequest()\r\n\r\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\r\nhttp.send()\r\n\r\nhttp.onload = () => console.log(http.responseText)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "<p>To refresh best answer from joann with promise this is my code:</p>\n\n<pre><code>let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n</code></pre>\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<p>To do this Fetch API is the recommended approach, using JavaScript Promises. XMLHttpRequest (XHR), IFrame object or dynamic <code><script></code> tags are older (and clunkier) approaches.</p>\n<pre><code><script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n</code></pre>\n<p>Here is a great <a href=\"https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data\" rel=\"nofollow noreferrer\">fetch demo</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">MDN docs</a></p>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Simple async request:</p>\n\n<pre><code>function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n</code></pre>\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an alternative to xml files to load your files as an object and access properties as an object in a very fast way.</p>\n\n<ul>\n<li>Attention, so that javascript can him and to interpret the content correctly it is necessary to save your files in the same format as your HTML page. If you use UTF 8 save your files in UTF8, etc.</li>\n</ul>\n\n<p>XML works as a tree ok? instead of writing </p>\n\n<pre><code> <property> value <property> \n</code></pre>\n\n<p>write a simple file like this:</p>\n\n<pre><code> Property1: value\n Property2: value\n etc.\n</code></pre>\n\n<p>Save your file ..\nNow call the function ....</p>\n\n<pre><code> var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n</code></pre>\n\n<p>now you can get your values efficiently.</p>\n\n<pre><code>getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n</code></pre>\n\n<p>It's just a small gift to contibute to the group. Thanks of your like :)</p>\n\n<p>If you want to test the function on your PC locally, restart your browser with the following command (supported by all browsers except safari):</p>\n\n<pre><code>yournavigator.exe '' --allow-file-access-from-files\n</code></pre>\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n</code></pre>\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<pre><code><button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Modern, clean and shortest</strong></p>\n<pre><code>fetch('https://www.randomtext.me/api/lorem')\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Open Chrome console network tab to see request</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "<p>now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "\n<h2>SET OF FUNCTIONS RECIPES EASY AND SIMPLE</h2>\n<p>I prepared a set of functions that are somehow similar but yet demonstrate new functionality as well as the simplicity that Javascript has reached if you know how to take advantage of it.</p>\n<hr />\n<ol start=\"0\">\n<li>Let some basic constants</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>let data;\nconst URLAPI = "https://gorest.co.in/public/v1/users";\nfunction setData(dt) {\n data = dt;\n}\n</code></pre>\n<hr />\n<ol>\n<li>Most simple</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 1 --> ", data);\n data = null;\n });\n}\n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>Variations using Promises and Async facilities</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 2 --> ", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 3 --> ", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log("Data received 4 --> ", data);\n\n })\n}\n</code></pre>\n<hr />\n<ol start=\"3\">\n<li>Demostration of one liner function!!!</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n</code></pre>\n<p><em><strong>WORTH MENTION ---> <a href=\"https://stackoverflow.com/a/25358151/13903942\">@Daniel De León</a> propably the cleanest function</strong></em>*</p>\n<pre class=\"lang-js prettyprint-override\"><code>(async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n</code></pre>\n<hr />\n<ol start=\"4\">\n<li>The top answer -> <a href=\"https://stackoverflow.com/a/22076667/13903942\">By @tggagne</a> shows functionality with HttpClient API.</li>\n</ol>\n<p>The same can be achieve with Fetch. As per this <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">Using Fetch</a> by MDN shows how you can pass a INIT as second argument, basically opening the possibility to configure easily an API with classic methods (get, post...) .</p>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match "Content-Type" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n</code></pre>\n<h2>Node</h2>\n<p><strong>Fetch is not available on Node (<em>Server Side</em>)</strong></p>\n<p>The easiest solution (end of 2021) is to use <strong><a href=\"https://axios-http.com/docs/example\" rel=\"nofollow noreferrer\">Axios</a></strong>.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$ npm install axios\n</code></pre>\n<p>Then Run:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n</code></pre>\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": "<p>In pure javascript and returning a Promise:</p>\n<pre><code> httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26948/"
] |
I need to do an [HTTP GET](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) request in JavaScript. What's the best way to do that?
I need to do this in a Mac OS X dashcode widget.
|
Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:
```
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
```
However, synchronous requests are discouraged and will generate a warning along the lines of:
>
> Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), **synchronous requests on the main thread have been deprecated** due to the negative effects to the user experience.
>
>
>
You should make an asynchronous request and handle the response inside an event handler.
```
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
```
|
247,486 |
<p>I'm loading data into a DataSet from an XML file using the ReadXml method. This results in two tables with the same name. One of the tables has a namespace and the other doesn't. I'm trying to reference the table with the namespace. Can anyone tell me how to do this?</p>
<pre><code> Dim reader As XmlTextReader = New XmlTextReader(strURL)
Dim city as string = ""
Dim ds As DataSet = New DataSet()
ds.Namespace = "HomeAddress"
ds.ReadXml(reader)
city = ds.Tables("Address").Rows(0).Item(2).ToString()
</code></pre>
|
[
{
"answer_id": 247489,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a></p>\n\n<p>You'd be best off using a library such as <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a> or <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a>.</p>\n"
},
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "<p>Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.</p>\n\n<p>In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.</p>\n\n<pre><code>var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.prototypejs.org\" rel=\"noreferrer\">Prototype</a> makes it dead simple</p>\n\n<pre><code>new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://api.jquery.com/jQuery.get/\" rel=\"noreferrer\">In jQuery</a>:</p>\n\n<pre><code>$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n</code></pre>\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "<p>IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.</p>\n\n<p>Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:</p>\n\n<pre><code>var sURL = '/your/url.html?' + (new Date()).getTime();\n</code></pre>\n\n<p>This will append a unique timestamp to the end of the URL and will prevent any caching from happening.</p>\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>In your widget's Info.plist file, don't forget to set your <code>AllowNetworkAccess</code> key to true.</p>\n"
},
{
"answer_id": 248726,
"author": "Nikola Stjelja",
"author_id": 32582,
"author_profile": "https://Stackoverflow.com/users/32582",
"pm_score": 3,
"selected": false,
"text": "<p>The best way is to use AJAX ( you can find a simple tutorial on this page <a href=\"http://www.tizag.com/"Tizag"\" rel=\"noreferrer\">Tizag</a>). The reason is that any other technique you may use requires more code, it is not guaranteed to work cross browser without rework and requires you use more client memory by opening hidden pages inside frames passing urls parsing their data and closing them. \nAJAX is the way to go in this situation. That my two years of javascript heavy development speaking. </p>\n"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequests</a>, I'd use <a href=\"http://docs.jquery.com/Ajax/jQuery.get#examples\" rel=\"noreferrer\">jQuery</a> and do something like this:</p>\n\n<pre><code>var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n</code></pre>\n"
},
{
"answer_id": 3429189,
"author": "apaderno",
"author_id": 225647,
"author_profile": "https://Stackoverflow.com/users/225647",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.</p>\n\n<p>As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.</p>\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "<p>Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:</p>\n\n<pre><code>function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n</code></pre>\n\n<p>However, synchronous requests are discouraged and will generate a warning along the lines of:</p>\n\n<blockquote>\n <p>Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), <strong>synchronous requests on the main thread have been deprecated</strong> due to the negative effects to the user experience.</p>\n</blockquote>\n\n<p>You should make an asynchronous request and handle the response inside an event handler.</p>\n\n<pre><code>function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n</code></pre>\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "<p>A version without callback</p>\n\n<pre><code>var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n</code></pre>\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "<p>Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.</p>\n\n<p>Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.</p>\n\n<pre><code>var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n</code></pre>\n\n<p>Using it is as easy as:</p>\n\n<pre><code>var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n</code></pre>\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>A copy-paste modern version <em>( using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"noreferrer\">fetch</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"noreferrer\">arrow function</a> )</em> :</p>\n</blockquote>\n\n<pre><code>//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n</code></pre>\n\n<blockquote>\n <p>A copy-paste classic version:</p>\n</blockquote>\n\n<pre><code>let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n</code></pre>\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "<p>You can get an HTTP GET request in two ways:</p>\n\n<ol>\n<li><p>This approach based on xml format. You have to pass the URL for the request. </p>\n\n<pre><code>xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n</code></pre></li>\n<li><p>This one is based on jQuery. You have to specify the URL and function_name you want to call.</p>\n\n<pre><code>$(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "<p>For those who use <a href=\"https://docs.angularjs.org/api/ng/service/$http\" rel=\"noreferrer\">AngularJs</a>, it's <code>$http.get</code>:</p>\n\n<pre><code>$http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n</code></pre>\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n</code></pre>\n\n<p>Same thing can be done for post request as well.<br>\nHave a look at this link <a href=\"https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit\">JavaScript post request like a form submit</a></p>\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "<p>The new <a href=\"https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en\" rel=\"noreferrer\"><code>window.fetch</code></a> API is a cleaner replacement for <code>XMLHttpRequest</code> that makes use of ES6 promises. There's a nice explanation <a href=\"https://jakearchibald.com/2015/thats-so-fetch/\" rel=\"noreferrer\">here</a>, but it boils down to (from the article):</p>\n\n<pre><code>fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n</code></pre>\n\n<p><a href=\"http://caniuse.com/#feat=fetch\" rel=\"noreferrer\">Browser support</a> is now good in the latest releases (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), however IE will likely not get official support. <a href=\"https://github.com/github/fetch\" rel=\"noreferrer\">GitHub has a polyfill</a> available which is recommended to support older browsers still largely in use (esp versions of Safari pre March 2017 and mobile browsers from the same period).</p>\n\n<p>I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.</p>\n\n<p>Here's a link to the spec <a href=\"https://fetch.spec.whatwg.org/\" rel=\"noreferrer\">https://fetch.spec.whatwg.org/</a></p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>Using ES7 async/await, this becomes simply (based on <a href=\"https://gist.github.com/msmfsd/fca50ab095b795eb39739e8c4357a808\" rel=\"noreferrer\">this Gist</a>):</p>\n\n<pre><code>async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>One solution supporting older browsers:</p>\n\n<pre><code>function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n</code></pre>\n\n<p>Maybe somewhat overkill but you definitely go safe with this code.</p>\n\n<p><strong>Usage:</strong>\n<br></p>\n\n<pre><code>//create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n</code></pre>\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with pure JS too:</p>\n\n<pre><code>// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n</code></pre>\n\n<p>See: for more details: <a href=\"https://www.html5rocks.com/en/tutorials/cors/\" rel=\"nofollow noreferrer\">html5rocks tutorial</a></p>\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Short and clean:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const http = new XMLHttpRequest()\r\n\r\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\r\nhttp.send()\r\n\r\nhttp.onload = () => console.log(http.responseText)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "<p>To refresh best answer from joann with promise this is my code:</p>\n\n<pre><code>let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n</code></pre>\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<p>To do this Fetch API is the recommended approach, using JavaScript Promises. XMLHttpRequest (XHR), IFrame object or dynamic <code><script></code> tags are older (and clunkier) approaches.</p>\n<pre><code><script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n</code></pre>\n<p>Here is a great <a href=\"https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data\" rel=\"nofollow noreferrer\">fetch demo</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">MDN docs</a></p>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Simple async request:</p>\n\n<pre><code>function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n</code></pre>\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an alternative to xml files to load your files as an object and access properties as an object in a very fast way.</p>\n\n<ul>\n<li>Attention, so that javascript can him and to interpret the content correctly it is necessary to save your files in the same format as your HTML page. If you use UTF 8 save your files in UTF8, etc.</li>\n</ul>\n\n<p>XML works as a tree ok? instead of writing </p>\n\n<pre><code> <property> value <property> \n</code></pre>\n\n<p>write a simple file like this:</p>\n\n<pre><code> Property1: value\n Property2: value\n etc.\n</code></pre>\n\n<p>Save your file ..\nNow call the function ....</p>\n\n<pre><code> var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n</code></pre>\n\n<p>now you can get your values efficiently.</p>\n\n<pre><code>getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n</code></pre>\n\n<p>It's just a small gift to contibute to the group. Thanks of your like :)</p>\n\n<p>If you want to test the function on your PC locally, restart your browser with the following command (supported by all browsers except safari):</p>\n\n<pre><code>yournavigator.exe '' --allow-file-access-from-files\n</code></pre>\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n</code></pre>\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<pre><code><button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Modern, clean and shortest</strong></p>\n<pre><code>fetch('https://www.randomtext.me/api/lorem')\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Open Chrome console network tab to see request</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "<p>now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "\n<h2>SET OF FUNCTIONS RECIPES EASY AND SIMPLE</h2>\n<p>I prepared a set of functions that are somehow similar but yet demonstrate new functionality as well as the simplicity that Javascript has reached if you know how to take advantage of it.</p>\n<hr />\n<ol start=\"0\">\n<li>Let some basic constants</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>let data;\nconst URLAPI = "https://gorest.co.in/public/v1/users";\nfunction setData(dt) {\n data = dt;\n}\n</code></pre>\n<hr />\n<ol>\n<li>Most simple</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 1 --> ", data);\n data = null;\n });\n}\n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>Variations using Promises and Async facilities</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 2 --> ", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 3 --> ", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log("Data received 4 --> ", data);\n\n })\n}\n</code></pre>\n<hr />\n<ol start=\"3\">\n<li>Demostration of one liner function!!!</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n</code></pre>\n<p><em><strong>WORTH MENTION ---> <a href=\"https://stackoverflow.com/a/25358151/13903942\">@Daniel De León</a> propably the cleanest function</strong></em>*</p>\n<pre class=\"lang-js prettyprint-override\"><code>(async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n</code></pre>\n<hr />\n<ol start=\"4\">\n<li>The top answer -> <a href=\"https://stackoverflow.com/a/22076667/13903942\">By @tggagne</a> shows functionality with HttpClient API.</li>\n</ol>\n<p>The same can be achieve with Fetch. As per this <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">Using Fetch</a> by MDN shows how you can pass a INIT as second argument, basically opening the possibility to configure easily an API with classic methods (get, post...) .</p>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match "Content-Type" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n</code></pre>\n<h2>Node</h2>\n<p><strong>Fetch is not available on Node (<em>Server Side</em>)</strong></p>\n<p>The easiest solution (end of 2021) is to use <strong><a href=\"https://axios-http.com/docs/example\" rel=\"nofollow noreferrer\">Axios</a></strong>.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$ npm install axios\n</code></pre>\n<p>Then Run:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n</code></pre>\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": "<p>In pure javascript and returning a Promise:</p>\n<pre><code> httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28327/"
] |
I'm loading data into a DataSet from an XML file using the ReadXml method. This results in two tables with the same name. One of the tables has a namespace and the other doesn't. I'm trying to reference the table with the namespace. Can anyone tell me how to do this?
```
Dim reader As XmlTextReader = New XmlTextReader(strURL)
Dim city as string = ""
Dim ds As DataSet = New DataSet()
ds.Namespace = "HomeAddress"
ds.ReadXml(reader)
city = ds.Tables("Address").Rows(0).Item(2).ToString()
```
|
Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:
```
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
```
However, synchronous requests are discouraged and will generate a warning along the lines of:
>
> Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), **synchronous requests on the main thread have been deprecated** due to the negative effects to the user experience.
>
>
>
You should make an asynchronous request and handle the response inside an event handler.
```
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
```
|
247,530 |
<p>I've an image that is wrapped in an anchor tag that, through jQuery, triggers an action somewhere else on the page. When I click on the image, two tiny 1px by 1px boxes show up in the upper and lower left corners of the image.</p>
<p>My CSS styles explicitly state no borders for images: <code>a,img { border: 0; }</code></p>
<p>It also seems to only happen in Firefox 3. Anyone else had this issue?</p>
<hr>
<p>Here's a screenshot of the left part of the image (the graphic has a white background):</p>
<p><a href="http://neezer.net/img/ss.png" rel="nofollow noreferrer">alt text http://neezer.net/img/ss.png</a></p>
<p>It's not the background, or the border of any other element. I checked.</p>
|
[
{
"answer_id": 247489,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a></p>\n\n<p>You'd be best off using a library such as <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a> or <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a>.</p>\n"
},
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "<p>Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.</p>\n\n<p>In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.</p>\n\n<pre><code>var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.prototypejs.org\" rel=\"noreferrer\">Prototype</a> makes it dead simple</p>\n\n<pre><code>new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://api.jquery.com/jQuery.get/\" rel=\"noreferrer\">In jQuery</a>:</p>\n\n<pre><code>$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n</code></pre>\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "<p>IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.</p>\n\n<p>Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:</p>\n\n<pre><code>var sURL = '/your/url.html?' + (new Date()).getTime();\n</code></pre>\n\n<p>This will append a unique timestamp to the end of the URL and will prevent any caching from happening.</p>\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>In your widget's Info.plist file, don't forget to set your <code>AllowNetworkAccess</code> key to true.</p>\n"
},
{
"answer_id": 248726,
"author": "Nikola Stjelja",
"author_id": 32582,
"author_profile": "https://Stackoverflow.com/users/32582",
"pm_score": 3,
"selected": false,
"text": "<p>The best way is to use AJAX ( you can find a simple tutorial on this page <a href=\"http://www.tizag.com/"Tizag"\" rel=\"noreferrer\">Tizag</a>). The reason is that any other technique you may use requires more code, it is not guaranteed to work cross browser without rework and requires you use more client memory by opening hidden pages inside frames passing urls parsing their data and closing them. \nAJAX is the way to go in this situation. That my two years of javascript heavy development speaking. </p>\n"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequests</a>, I'd use <a href=\"http://docs.jquery.com/Ajax/jQuery.get#examples\" rel=\"noreferrer\">jQuery</a> and do something like this:</p>\n\n<pre><code>var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n</code></pre>\n"
},
{
"answer_id": 3429189,
"author": "apaderno",
"author_id": 225647,
"author_profile": "https://Stackoverflow.com/users/225647",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.</p>\n\n<p>As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.</p>\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "<p>Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:</p>\n\n<pre><code>function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n</code></pre>\n\n<p>However, synchronous requests are discouraged and will generate a warning along the lines of:</p>\n\n<blockquote>\n <p>Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), <strong>synchronous requests on the main thread have been deprecated</strong> due to the negative effects to the user experience.</p>\n</blockquote>\n\n<p>You should make an asynchronous request and handle the response inside an event handler.</p>\n\n<pre><code>function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n</code></pre>\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "<p>A version without callback</p>\n\n<pre><code>var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n</code></pre>\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "<p>Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.</p>\n\n<p>Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.</p>\n\n<pre><code>var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n</code></pre>\n\n<p>Using it is as easy as:</p>\n\n<pre><code>var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n</code></pre>\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>A copy-paste modern version <em>( using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"noreferrer\">fetch</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"noreferrer\">arrow function</a> )</em> :</p>\n</blockquote>\n\n<pre><code>//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n</code></pre>\n\n<blockquote>\n <p>A copy-paste classic version:</p>\n</blockquote>\n\n<pre><code>let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n</code></pre>\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "<p>You can get an HTTP GET request in two ways:</p>\n\n<ol>\n<li><p>This approach based on xml format. You have to pass the URL for the request. </p>\n\n<pre><code>xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n</code></pre></li>\n<li><p>This one is based on jQuery. You have to specify the URL and function_name you want to call.</p>\n\n<pre><code>$(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "<p>For those who use <a href=\"https://docs.angularjs.org/api/ng/service/$http\" rel=\"noreferrer\">AngularJs</a>, it's <code>$http.get</code>:</p>\n\n<pre><code>$http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n</code></pre>\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n</code></pre>\n\n<p>Same thing can be done for post request as well.<br>\nHave a look at this link <a href=\"https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit\">JavaScript post request like a form submit</a></p>\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "<p>The new <a href=\"https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en\" rel=\"noreferrer\"><code>window.fetch</code></a> API is a cleaner replacement for <code>XMLHttpRequest</code> that makes use of ES6 promises. There's a nice explanation <a href=\"https://jakearchibald.com/2015/thats-so-fetch/\" rel=\"noreferrer\">here</a>, but it boils down to (from the article):</p>\n\n<pre><code>fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n</code></pre>\n\n<p><a href=\"http://caniuse.com/#feat=fetch\" rel=\"noreferrer\">Browser support</a> is now good in the latest releases (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), however IE will likely not get official support. <a href=\"https://github.com/github/fetch\" rel=\"noreferrer\">GitHub has a polyfill</a> available which is recommended to support older browsers still largely in use (esp versions of Safari pre March 2017 and mobile browsers from the same period).</p>\n\n<p>I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.</p>\n\n<p>Here's a link to the spec <a href=\"https://fetch.spec.whatwg.org/\" rel=\"noreferrer\">https://fetch.spec.whatwg.org/</a></p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>Using ES7 async/await, this becomes simply (based on <a href=\"https://gist.github.com/msmfsd/fca50ab095b795eb39739e8c4357a808\" rel=\"noreferrer\">this Gist</a>):</p>\n\n<pre><code>async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>One solution supporting older browsers:</p>\n\n<pre><code>function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n</code></pre>\n\n<p>Maybe somewhat overkill but you definitely go safe with this code.</p>\n\n<p><strong>Usage:</strong>\n<br></p>\n\n<pre><code>//create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n</code></pre>\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with pure JS too:</p>\n\n<pre><code>// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n</code></pre>\n\n<p>See: for more details: <a href=\"https://www.html5rocks.com/en/tutorials/cors/\" rel=\"nofollow noreferrer\">html5rocks tutorial</a></p>\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Short and clean:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const http = new XMLHttpRequest()\r\n\r\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\r\nhttp.send()\r\n\r\nhttp.onload = () => console.log(http.responseText)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "<p>To refresh best answer from joann with promise this is my code:</p>\n\n<pre><code>let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n</code></pre>\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<p>To do this Fetch API is the recommended approach, using JavaScript Promises. XMLHttpRequest (XHR), IFrame object or dynamic <code><script></code> tags are older (and clunkier) approaches.</p>\n<pre><code><script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n</code></pre>\n<p>Here is a great <a href=\"https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data\" rel=\"nofollow noreferrer\">fetch demo</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">MDN docs</a></p>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Simple async request:</p>\n\n<pre><code>function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n</code></pre>\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an alternative to xml files to load your files as an object and access properties as an object in a very fast way.</p>\n\n<ul>\n<li>Attention, so that javascript can him and to interpret the content correctly it is necessary to save your files in the same format as your HTML page. If you use UTF 8 save your files in UTF8, etc.</li>\n</ul>\n\n<p>XML works as a tree ok? instead of writing </p>\n\n<pre><code> <property> value <property> \n</code></pre>\n\n<p>write a simple file like this:</p>\n\n<pre><code> Property1: value\n Property2: value\n etc.\n</code></pre>\n\n<p>Save your file ..\nNow call the function ....</p>\n\n<pre><code> var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n</code></pre>\n\n<p>now you can get your values efficiently.</p>\n\n<pre><code>getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n</code></pre>\n\n<p>It's just a small gift to contibute to the group. Thanks of your like :)</p>\n\n<p>If you want to test the function on your PC locally, restart your browser with the following command (supported by all browsers except safari):</p>\n\n<pre><code>yournavigator.exe '' --allow-file-access-from-files\n</code></pre>\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n</code></pre>\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<pre><code><button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Modern, clean and shortest</strong></p>\n<pre><code>fetch('https://www.randomtext.me/api/lorem')\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Open Chrome console network tab to see request</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "<p>now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "\n<h2>SET OF FUNCTIONS RECIPES EASY AND SIMPLE</h2>\n<p>I prepared a set of functions that are somehow similar but yet demonstrate new functionality as well as the simplicity that Javascript has reached if you know how to take advantage of it.</p>\n<hr />\n<ol start=\"0\">\n<li>Let some basic constants</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>let data;\nconst URLAPI = "https://gorest.co.in/public/v1/users";\nfunction setData(dt) {\n data = dt;\n}\n</code></pre>\n<hr />\n<ol>\n<li>Most simple</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 1 --> ", data);\n data = null;\n });\n}\n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>Variations using Promises and Async facilities</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 2 --> ", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log("Data received 3 --> ", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log("Data received 4 --> ", data);\n\n })\n}\n</code></pre>\n<hr />\n<ol start=\"3\">\n<li>Demostration of one liner function!!!</li>\n</ol>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n</code></pre>\n<p><em><strong>WORTH MENTION ---> <a href=\"https://stackoverflow.com/a/25358151/13903942\">@Daniel De León</a> propably the cleanest function</strong></em>*</p>\n<pre class=\"lang-js prettyprint-override\"><code>(async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n</code></pre>\n<hr />\n<ol start=\"4\">\n<li>The top answer -> <a href=\"https://stackoverflow.com/a/22076667/13903942\">By @tggagne</a> shows functionality with HttpClient API.</li>\n</ol>\n<p>The same can be achieve with Fetch. As per this <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\">Using Fetch</a> by MDN shows how you can pass a INIT as second argument, basically opening the possibility to configure easily an API with classic methods (get, post...) .</p>\n<hr />\n<pre class=\"lang-js prettyprint-override\"><code>// Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match "Content-Type" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n</code></pre>\n<h2>Node</h2>\n<p><strong>Fetch is not available on Node (<em>Server Side</em>)</strong></p>\n<p>The easiest solution (end of 2021) is to use <strong><a href=\"https://axios-http.com/docs/example\" rel=\"nofollow noreferrer\">Axios</a></strong>.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$ npm install axios\n</code></pre>\n<p>Then Run:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n</code></pre>\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": "<p>In pure javascript and returning a Promise:</p>\n<pre><code> httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32154/"
] |
I've an image that is wrapped in an anchor tag that, through jQuery, triggers an action somewhere else on the page. When I click on the image, two tiny 1px by 1px boxes show up in the upper and lower left corners of the image.
My CSS styles explicitly state no borders for images: `a,img { border: 0; }`
It also seems to only happen in Firefox 3. Anyone else had this issue?
---
Here's a screenshot of the left part of the image (the graphic has a white background):
[alt text http://neezer.net/img/ss.png](http://neezer.net/img/ss.png)
It's not the background, or the border of any other element. I checked.
|
Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:
```
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
```
However, synchronous requests are discouraged and will generate a warning along the lines of:
>
> Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), **synchronous requests on the main thread have been deprecated** due to the negative effects to the user experience.
>
>
>
You should make an asynchronous request and handle the response inside an event handler.
```
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
```
|
247,538 |
<p>I was looking through the plans for C++0x and came upon <code>std::initializer_list</code> for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement <code>initializer_list</code> could be used to implement initializer lists in your own class.</p>
<p>What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?</p>
<p>Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without <code>initializer_list</code>). </p>
<p>A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.</p>
|
[
{
"answer_id": 247540,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "<p>The only other one I could think of was the <a href=\"http://msdn.microsoft.com/en-us/library/70ky2y6k.aspx\" rel=\"nofollow noreferrer\">type_info</a> class returned by typeid. As far as I can tell, VC++ implements this by instantiating all the needed type_info classes statically at compile time, and then simply casting a pointer at runtime based on values in the vtable. These are things that could be done using C code, but not in a standard-conforming or portable way.</p>\n"
},
{
"answer_id": 247580,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": "<p>All classes in the standard library, by definition, <strong><em>must</em></strong> be implemented in C++. Some of them hide some obscure language/compiler constructs, but still are just wrappers around that complexity, not language features.</p>\n"
},
{
"answer_id": 247614,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "<p>I think you're pretty safe on this score. C++ mostly serves as a thick layer of abstraction around C. Since C++ is <em>also</em> a superset of C itself, the core language primitives are almost always implemented sans-classes (in a C-style). In other words, you're not going to find many situations like Java's <code>Object</code> which is a class which has special meaning hard-coded into the compiler.</p>\n"
},
{
"answer_id": 248818,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 0,
"selected": false,
"text": "<p>Again from C++0x, I think that threads would not be implementable as a portable library in the hypothetical language \"C++0x, with all the standard libraries except threads\".</p>\n\n<p>[Edit: just to clarify, there seems to be some disagreement as to what it would mean to \"implement threads\". What I understand it to mean in the context of this question is:</p>\n\n<p>1) Implement the C++0x threading specification (whatever that turns out to be). Note C++0x, which is what I and the questioner are both talking about. Not any other threading specification, such as POSIX.</p>\n\n<p>2) without \"compiler magic\". This means not adding anything to the compiler to help your implementation work, and not relying on any non-standard implementation details (such as a particular stack layout, or a means of switching stacks, or non-portable system calls to set a timed interrupt) to produce a thread library that works only on a particular C++ implementation. In other words: pure, portable C++. You can use signals and setjmp/longjmp, since they are portable, but my impression is that's not enough.</p>\n\n<p>3) Assume a C++0x compiler, except that it's missing all parts of the C++0x threading specification. If all it's missing is some data structure (that stores an exit value and a synchronisation primitive used by join() or equivalent), but the compiler magic to implement threads is present, then obviously that data structure could be added as a third-party portable component. But that's kind of a dull answer, when the question was about which C++0x standard library classes require compiler magic to support them. IMO.]</p>\n"
},
{
"answer_id": 248842,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>Anything that the runtime \"hooks into\" at defined points is likely not to be implementable as a portable library in the hypothetical language \"C++, excluding that thing\".</p>\n\n<p>So for instance I think atexit() in <cstdlib> can't be implemented purely as a library, since there is no other way in C++ to ensure it is called at the right time in the termination sequence, that is before any global destructor.</p>\n\n<p>Of course, you could argue that C features \"don't count\" for this question. In which case std::unexpected may be a better example, for exactly the same reason. If it didn't exist, there would be no way to implement it without tinkering with the exception code emitted by the compiler.</p>\n\n<p>[Edit: I just noticed the questioner actually asked what <em>classes</em> can't be implemented, not what parts of the standard library can't be implemented. So actually these examples don't strictly answer the question.]</p>\n"
},
{
"answer_id": 248891,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 4,
"selected": true,
"text": "<p><code>std::type_info</code> is a simple class, although populating it requires <code>typeinfo</code>: a compiler construct.</p>\n\n<p>Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?).</p>\n\n<p>The question, to me, is \"how close can we get to <code>std::initializer_list</code>s without compiler magic?\"</p>\n\n<p>Looking at <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists\" rel=\"nofollow noreferrer\">wikipedia</a>, <code>std::initializer_list<typename T></code> can be initialized by something that looks a lot like an array literal. Let's try giving our <code>std::initializer_list<typename T></code> a conversion constructor that takes an array (i.e., a constructor that takes a single argument of <code>T[]</code>):</p>\n\n<pre><code>namespace std {\n template<typename T> class initializer_list {\n T internal_array[];\n public:\n initializer_list(T other_array[]) : internal_array(other_array) { };\n\n // ... other methods needed to actually access internal_array\n }\n}\n</code></pre>\n\n<p>Likewise, a class that uses a <code>std::initializer_list</code> does so by declaring a constructor that takes a single <code>std::initializer_list</code> argument -- a.k.a. a conversion constructor:</p>\n\n<pre><code>struct my_class {\n ...\n my_class(std::initializer_list<int>) ...\n}\n</code></pre>\n\n<p>So the line:</p>\n\n<pre><code> my_class m = {1, 2, 3};\n</code></pre>\n\n<p>Causes the compiler to think: \"I need to call a constructor for <code>my_class</code>; <code>my_class</code> has a constructor that takes a <code>std::initializer_list<int></code>; I have an <code>int[]</code> literal; I can convert an <code>int[]</code> to a <code>std::initializer_list<int></code>; and I can pass that to the <code>my_class</code> constructor\" (<strong>please read to the end of the answer before telling me that C++ doesn't allow two implicit user-defined conversions to be chained</strong>).</p>\n\n<p>So how close is this? First, I'm missing a few features/restrictions of initializer lists. One thing I don't enforce is that initializer lists can only be constructed with array literals, while my <code>initializer_list</code> would also accept an already-created array:</p>\n\n<pre><code>int arry[] = {1, 2, 3};\nmy_class = arry;\n</code></pre>\n\n<p>Additionally, I didn't bother messing with rvalue references.</p>\n\n<p>Finally, this class only works as the new standard says it should if the compiler implicitly chains two user-defined conversions together. This is specifically prohibited under normal cases, so the example still needs compiler magic. But I would argue that (1) the class itself is a normal class, and (2) the magic involved (enforcing the \"array literal\" initialization syntax and allowing two user-defined conversions to be implicitly chained) is less than it seems at first glance.</p>\n"
},
{
"answer_id": 249731,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>C++ allows compilers to define otherwise undefined behavior. This makes it possible to implement the Standard Library in non-standard C++. For instance, \"onebyone\" wonders about atexit(). The library writers can assume things about the compiler that makes their non-portable C++ work OK for their compiler.</p>\n"
},
{
"answer_id": 250642,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>MSalter points out printf/cout/stdout in a comment. You could implement any one of them in terms of the one of the others (I think), but you can't implement the whole set of them together without OS calls or compiler magic, because:</p>\n\n<ol>\n<li><p>These are all the ways of accessing the process's standard output stream. You have to stuff the bytes somewhere, and that's implementation-specific in the absence of these things. Unless I've forgotten another way of accessing it, but the point is you can't implement standard output other than through implementation-specific \"magic\".</p></li>\n<li><p>They have \"magic\" behaviour in the runtime, which I think could not be perfectly imitated by a pure library. For example, you couldn't just use static initialization to construct cout, because the order of static initialization between compilation units is not defined, so there would be no guarantee that it would exist in time to be used by other static initializers. stdout is perhaps easier, since it's just fd 1, so any apparatus supporting it can be created by the calls it's passed into when they see it.</p></li>\n</ol>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
I was looking through the plans for C++0x and came upon `std::initializer_list` for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement `initializer_list` could be used to implement initializer lists in your own class.
What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?
Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without `initializer_list`).
A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.
|
`std::type_info` is a simple class, although populating it requires `typeinfo`: a compiler construct.
Likewise, exceptions are normal objects, but throwing exceptions requires compiler magic (where are the exceptions allocated?).
The question, to me, is "how close can we get to `std::initializer_list`s without compiler magic?"
Looking at [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists), `std::initializer_list<typename T>` can be initialized by something that looks a lot like an array literal. Let's try giving our `std::initializer_list<typename T>` a conversion constructor that takes an array (i.e., a constructor that takes a single argument of `T[]`):
```
namespace std {
template<typename T> class initializer_list {
T internal_array[];
public:
initializer_list(T other_array[]) : internal_array(other_array) { };
// ... other methods needed to actually access internal_array
}
}
```
Likewise, a class that uses a `std::initializer_list` does so by declaring a constructor that takes a single `std::initializer_list` argument -- a.k.a. a conversion constructor:
```
struct my_class {
...
my_class(std::initializer_list<int>) ...
}
```
So the line:
```
my_class m = {1, 2, 3};
```
Causes the compiler to think: "I need to call a constructor for `my_class`; `my_class` has a constructor that takes a `std::initializer_list<int>`; I have an `int[]` literal; I can convert an `int[]` to a `std::initializer_list<int>`; and I can pass that to the `my_class` constructor" (**please read to the end of the answer before telling me that C++ doesn't allow two implicit user-defined conversions to be chained**).
So how close is this? First, I'm missing a few features/restrictions of initializer lists. One thing I don't enforce is that initializer lists can only be constructed with array literals, while my `initializer_list` would also accept an already-created array:
```
int arry[] = {1, 2, 3};
my_class = arry;
```
Additionally, I didn't bother messing with rvalue references.
Finally, this class only works as the new standard says it should if the compiler implicitly chains two user-defined conversions together. This is specifically prohibited under normal cases, so the example still needs compiler magic. But I would argue that (1) the class itself is a normal class, and (2) the magic involved (enforcing the "array literal" initialization syntax and allowing two user-defined conversions to be implicitly chained) is less than it seems at first glance.
|
247,541 |
<p>I've editing this original question as I think I've narrowed down the problem...</p>
<p>I have one view in my site that will not let me put $document.ready within a masterpage contentplaceholder. I've stripped this page to the bare bones and the only thing that is special about it is it has a custom route in global.asax</p>
<pre><code> routes.MapRoute("Books",
"{controller}/{action}/{keywords}/{pageNumber}",
new { controller = "Books", action = "SearchResults" }
);
</code></pre>
<p>Any idea why this custom route would stop $document.ready working correctly when put in a masterpages contentplaceholder zone?</p>
|
[
{
"answer_id": 247554,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>Your master page (or view page if you're not using master pages) needs to reference jquery. This is included in the latest Beta release of the MVC framework.</p>\n\n<p>Check to make sure you have jQuery included in the tag of your page.</p>\n\n<p>check the syntax as well...</p>\n\n<pre><code>$(document).ready(function() { alert('loaded'); });\n</code></pre>\n\n<p>these shortened versions also work:</p>\n\n<pre><code>$().ready(function() { alert('loaded'); });\n$(function() { alert('loaded'); });\n</code></pre>\n"
},
{
"answer_id": 247645,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Just stick it somewhere within the content control of your view page in a <code><script ...></code> tag.</p>\n\n<pre><code><asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContentPlaceHolder\" runat=\"server\">\n <div class=\"contentItem\">\n <%!-- yadda --%>\n </div>\n\n <script type=\"text/javascript\">\n $(document).ready(function() {\n // do your worst\n });\n </script>\n</asp:Content>\n</code></pre>\n\n<p>If you have stuff that runs on every page, you can peel that off into a .js file and access it from the master page. But for functions relating to a specific view, this is probably the simplest way to go and easiest to maintain.</p>\n"
},
{
"answer_id": 251188,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 4,
"selected": true,
"text": "<p>I had the same problem and it turned out that when I used a certain route it changed the perceived file hierarchy of the site such as the ../../Content link for the .js file didn't work any more. I fixed it by changing my jquery script reference to look like this:</p>\n\n<pre><code><script src=\"<%= Url.Content(\"~/Content/jquery-1.2.6.min.js\") %>\" type=\"text/javascript\"></script>\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5463/"
] |
I've editing this original question as I think I've narrowed down the problem...
I have one view in my site that will not let me put $document.ready within a masterpage contentplaceholder. I've stripped this page to the bare bones and the only thing that is special about it is it has a custom route in global.asax
```
routes.MapRoute("Books",
"{controller}/{action}/{keywords}/{pageNumber}",
new { controller = "Books", action = "SearchResults" }
);
```
Any idea why this custom route would stop $document.ready working correctly when put in a masterpages contentplaceholder zone?
|
I had the same problem and it turned out that when I used a certain route it changed the perceived file hierarchy of the site such as the ../../Content link for the .js file didn't work any more. I fixed it by changing my jquery script reference to look like this:
```
<script src="<%= Url.Content("~/Content/jquery-1.2.6.min.js") %>" type="text/javascript"></script>
```
|
247,546 |
<p>I'm sending an email using the dotnet framework. Here is the template that I'm using to create the message:</p>
<pre><code>Date of Hire: %HireDate%
Annual Salary: %AnnualIncome%
Reason for Request: %ReasonForRequest%
Name of Voluntary Employee: %FirstName% %LastName%
Total Coverage Applied For: %EECoverageAmount%
Guaranteed Coverage Portion: %GICoveragePortion%
Amount Subject to Medical Evident: %GIOverage%
</code></pre>
<p>When the messages is received in outlook, outlook tells me "Extra line breaks in this message were removed". And the message displays like this:</p>
<pre><code>Date of Hire: 9/28/2001
Annual Salary: $100,000
Reason for Request: New Hire
Name of Voluntary Employee: Ronald Weasley Total Coverage Applied For: $500,000 Guaranteed Coverage Portion: $300,000.00 Amount Subject to Medical Evident: $200,000
</code></pre>
<p>Note how Outlook incorrectly removes needed line breaks after the name, EECoverageAmount, etc...</p>
<p>It's important for the email recepients to get a correctly formatted email, and I have to assume that some of them use outlook 2003. I also can't assume they will know enough to shutoff the autoclean feature to get the message to format properly. </p>
<p>I have viewed these messages in other mail clients and they display correctly</p>
<p>some more information:</p>
<ul>
<li>I am using UTF-8 BodyEncoding (msg.BodyEncoding = System.Text.Encoding.UTF8)</li>
<li>The msg.Body is being read from a UTF-8 encoded text file, and each line is terminated with a crlf.</li>
</ul>
<p>Question:
How do I change the format of the message to avoid this problem?</p>
|
[
{
"answer_id": 247664,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": -1,
"selected": false,
"text": "<p>Change your line termination from crlf to either cr or lf. </p>\n\n<p>I suspect that the top of the email uses only cr (or lf), and Outlook expects the rest of the email to follow the same format. </p>\n"
},
{
"answer_id": 247698,
"author": "Doug L.",
"author_id": 19179,
"author_profile": "https://Stackoverflow.com/users/19179",
"pm_score": 3,
"selected": false,
"text": "<p>I have always had better luck formatting e-mails as html. You may still have the end-user issue of having to set the client to allow html format, but they are usually more familiar with this since so many e-mails do come html formatted. You also have a little more work on your end adding the html tags, but the end result is much more controllable.</p>\n\n<p>@ephemient also suggests: <em>Send as both HTML and plaintext. Good clients will show the latter, Outlook will show the former, everybody is happy (except the programmer who has to do more work).</em> </p>\n"
},
{
"answer_id": 247939,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 8,
"selected": true,
"text": "<p>Start every line with 2 spaces and outlook will be \"tricked\" into keeping your formatting.</p>\n\n<p>So change</p>\n\n<pre><code>Date of Hire: %HireDate%\nAnnual Salary: %AnnualIncome%\nReason for Request: %ReasonForRequest%\n\nName of Voluntary Employee: %FirstName% %LastName%\nTotal Coverage Applied For: %EECoverageAmount%\nGuaranteed Coverage Portion: %GICoveragePortion%\nAmount Subject to Medical Evident: %GIOverage%\n</code></pre>\n\n<p>to</p>\n\n<pre><code> Date of Hire: %HireDate%\n Annual Salary: %AnnualIncome%\n Reason for Request: %ReasonForRequest%\n\n Name of Voluntary Employee: %FirstName% %LastName%\n Total Coverage Applied For: %EECoverageAmount%\n Guaranteed Coverage Portion: %GICoveragePortion%\n Amount Subject to Medical Evident: %GIOverage%\n^^ <--- Two extra spaces at the start of every line\n</code></pre>\n\n<p>Here is the <a href=\"http://www.masternewmedia.org/newsletter_publishing/newsletter_formatting/remove_line_breaks_issue_Microsoft_Outlook_2003_when_publishing_text_newsletters_20051217.htm\" rel=\"noreferrer\">article</a> I found when researching this problem which goes into a little more depth than my answer.</p>\n"
},
{
"answer_id": 285527,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm seeing the same problem when generating a plain-text email and then reading it with Outlook 2003 SP3. It appears you can avoid the removal process by it by keep the line length under 40 characters. May not always be practical.</p>\n"
},
{
"answer_id": 436114,
"author": "Jim Davis",
"author_id": 43807,
"author_profile": "https://Stackoverflow.com/users/43807",
"pm_score": 7,
"selected": false,
"text": "<p>You can also insert a tab character at the <em>end</em> of the line (just before the CR LF). This extra white space will be at the end of the line and hence not visible to user. You might prefer this to having to insert spaces on the left. Note that a single space is not enough (though perhaps multiple spaces would help, I don't know.)</p>\n"
},
{
"answer_id": 1358607,
"author": "DHornpout",
"author_id": 21268,
"author_profile": "https://Stackoverflow.com/users/21268",
"pm_score": 5,
"selected": false,
"text": "<p>This answer is on how to \"disable\" the feature from the Outlook Client.</p>\n\n<ul>\n<li>Go to Tools -> \"Options ...\"</li>\n<li>In the \"Preferences\" tab click on \"Email Options ...\"</li>\n<li>Uncheck the box \"Remove extra line breaks in plain text messages.\"</li>\n<li>Hit OK</li>\n</ul>\n\n<p>FYI:I am using Outlook 2007</p>\n"
},
{
"answer_id": 18986207,
"author": "Christian Casutt",
"author_id": 270085,
"author_profile": "https://Stackoverflow.com/users/270085",
"pm_score": 0,
"selected": false,
"text": "<p>Put the text in <code><pre></code> Tags and outlook will format and display the text correctly. </p>\n\n<p>i defined it in CSS inline in HTML Body like: </p>\n\n<p>CSS:</p>\n\n<pre><code>pre {\n font-family: Verdana, Geneva, sans-serif;\n}\n</code></pre>\n\n<p>i defined the font-family to have to font set. </p>\n\n<p>HTML: </p>\n\n<pre><code><td width=\"70%\"><pre>Entry Date/Time: 2013-09-19 17:06:25\nEntered By: Chris\n\nworklog mania\n\n____________________________________________________________________________________________________\n\nEntry Date/Time: 2013-09-19 17:05:42\nEntered By: Chris\n\nthis is a new Worklog Entry</pre></td>\n</code></pre>\n"
},
{
"answer_id": 26904734,
"author": "Keyur Patel",
"author_id": 1817557,
"author_profile": "https://Stackoverflow.com/users/1817557",
"pm_score": -1,
"selected": false,
"text": "<p>My text includes '\\r\\n' but Outlook 2010 does not render line break. Create tokens of lines delimited by '\\r\\n' and envelope tokens by HTML Paragraph tags. My Email format is HTML. I am generating HTML Body for my email in the code below.</p>\n\n<pre><code>string[] tokens = Regex.Split(objTickt.Description, \"\\r\\n\");\n if (tokens.Length > 0)\n {\n foreach (string line in tokens)\n {\n //htmlTW.WriteEncodedText(objTickt.Description.Replace(\"\\r\\n\", \"\\n\\n\"));\n htmlTW.RenderBeginTag(HtmlTextWriterTag.P);\n htmlTW.WriteEncodedText(line);\n htmlTW.RenderEndTag();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 36577194,
"author": "supernova",
"author_id": 538160,
"author_profile": "https://Stackoverflow.com/users/538160",
"pm_score": 3,
"selected": false,
"text": "<p>Adding \"\\t\\r\\n\" ( \\t for TAB) instead of \"\\r\\n\" worked for me on Outlook 2010.</p>\n"
},
{
"answer_id": 45742136,
"author": "Ho Ho Ho",
"author_id": 2386528,
"author_profile": "https://Stackoverflow.com/users/2386528",
"pm_score": 1,
"selected": false,
"text": "<p>Expanding on the <a href=\"https://stackoverflow.com/users/19179/doug-l\">Doug L</a> answer, since I think HTML messaging is even more ubiquitous and accepted now than in 2008 when that answer was posted. Here is a little c# snippet to help convert the body and send the message in HTML format: </p>\n\n<pre><code>body = string.Format(\"<font face='calibri,arial,sans-serif'>{0}<font/>\", body.Replace(\"\\r\\n\", \"<br>\"));\n\nusing (var smtpClient = new SmtpClient() { Host = smtpHost })\nusing (var msg = new MailMessage(from, emailDistribution, subject, body) { IsBodyHtml = true })\n smtpClient.Send(msg);\n</code></pre>\n"
},
{
"answer_id": 55183800,
"author": "Brijesh Kumar Tripathi",
"author_id": 9203434,
"author_profile": "https://Stackoverflow.com/users/9203434",
"pm_score": 1,
"selected": false,
"text": "<p>Auto cleaning is an outlook feature which removes extra line breaks. You can prevent it by two ways.</p>\n\n<ul>\n<li><p><strong>First way</strong> is to add at least 2 extra spaces before lines while sending the email through code. You can add these extra spaces only before those lines which outlook automatically removes.</p></li>\n<li><p><strong>Second way</strong> is to change outlook setting which will prevent outlook\nfrom removing extra line breaks.</p></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/Fvh6c.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Fvh6c.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/LYwPz.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LYwPz.jpg\" alt=\"enter image description here\"></a> </p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21155/"
] |
I'm sending an email using the dotnet framework. Here is the template that I'm using to create the message:
```
Date of Hire: %HireDate%
Annual Salary: %AnnualIncome%
Reason for Request: %ReasonForRequest%
Name of Voluntary Employee: %FirstName% %LastName%
Total Coverage Applied For: %EECoverageAmount%
Guaranteed Coverage Portion: %GICoveragePortion%
Amount Subject to Medical Evident: %GIOverage%
```
When the messages is received in outlook, outlook tells me "Extra line breaks in this message were removed". And the message displays like this:
```
Date of Hire: 9/28/2001
Annual Salary: $100,000
Reason for Request: New Hire
Name of Voluntary Employee: Ronald Weasley Total Coverage Applied For: $500,000 Guaranteed Coverage Portion: $300,000.00 Amount Subject to Medical Evident: $200,000
```
Note how Outlook incorrectly removes needed line breaks after the name, EECoverageAmount, etc...
It's important for the email recepients to get a correctly formatted email, and I have to assume that some of them use outlook 2003. I also can't assume they will know enough to shutoff the autoclean feature to get the message to format properly.
I have viewed these messages in other mail clients and they display correctly
some more information:
* I am using UTF-8 BodyEncoding (msg.BodyEncoding = System.Text.Encoding.UTF8)
* The msg.Body is being read from a UTF-8 encoded text file, and each line is terminated with a crlf.
Question:
How do I change the format of the message to avoid this problem?
|
Start every line with 2 spaces and outlook will be "tricked" into keeping your formatting.
So change
```
Date of Hire: %HireDate%
Annual Salary: %AnnualIncome%
Reason for Request: %ReasonForRequest%
Name of Voluntary Employee: %FirstName% %LastName%
Total Coverage Applied For: %EECoverageAmount%
Guaranteed Coverage Portion: %GICoveragePortion%
Amount Subject to Medical Evident: %GIOverage%
```
to
```
Date of Hire: %HireDate%
Annual Salary: %AnnualIncome%
Reason for Request: %ReasonForRequest%
Name of Voluntary Employee: %FirstName% %LastName%
Total Coverage Applied For: %EECoverageAmount%
Guaranteed Coverage Portion: %GICoveragePortion%
Amount Subject to Medical Evident: %GIOverage%
^^ <--- Two extra spaces at the start of every line
```
Here is the [article](http://www.masternewmedia.org/newsletter_publishing/newsletter_formatting/remove_line_breaks_issue_Microsoft_Outlook_2003_when_publishing_text_newsletters_20051217.htm) I found when researching this problem which goes into a little more depth than my answer.
|
247,550 |
<p>I have a blank test app created in VS 2005 as ASP.NET application. <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow noreferrer">MSDN says</a> that </p>
<blockquote>
<p>By default, ASP.NET does not use impersonation, and your code runs using the ASP.NET application's process identity.</p>
</blockquote>
<p>And I have the following web.config</p>
<pre><code><configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" defaultLanguage="c#" />
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<identity impersonate="false"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
</code></pre>
<p>So it seem impersonation is disabled just like <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow noreferrer">the article</a> is suggesting.</p>
<p>My aspx is blank default and the codebehind is</p>
<pre><code>namespace TestWebapp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(String.Format("Before1: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
int a = 0;
System.Diagnostics.Debug.WriteLine(String.Format("After: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
} finally
{
ctx.Undo();
}
}
}
}
</code></pre>
<p>When I reload the page I get the following debug output:</p>
<blockquote>
<p>[5288] Before1: Current Princupal =
DOMAIN\User
[5288] After: Current Princupal =
DOMAIN\User</p>
</blockquote>
<p>Output is the same with</p>
<pre><code><identity impersonate="false"/>
</code></pre>
<p>The web site uses Default Application Pool and the pool is set up to use NETWORK SERVICE account for its worker processes.
I'm sure the application uses the web.config it should use and the w3p.exe worker process is running under NETWORK SERVICE.</p>
<p>What can be wrong in this case?</p>
<p>Thanks!</p>
<p>@Edit: Rob, thanks for the tip!
The $user shortcut shows me that everything is happening as I expect: with impersonation on I have the process running user NT AUTHORITY\NETWORK SERVICE and the thread has DOMAIN\User before WindowsIdentity.Impersonate(IntPtr.Zero) and "No Token. Thread not impersonating." after.
But Thread.CurrentPrincipal.Identity.Name and HttpContext.Current.User.Identity.Name still give me DOMAIN\User in both places.</p>
<p>@Edit: I've found out that to get Thread.CurrentPrincipal and HttpContext.Current.User changed I have to manually do it:</p>
<pre><code>Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
HttpContext.Current.User = Thread.CurrentPrincipal;
</code></pre>
<p>I'm not sure what's the point here, but anyway. I now have a problem with sharepoint shared services manage user profile permission but that's another question.</p>
|
[
{
"answer_id": 247582,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": "<p>Seems odd, A few things to try:</p>\n\n<ul>\n<li>While in on a breakpoint in Debug type $user in a watch window, that will show you the process and thread identities.</li>\n<li><p>Your use of impersonate is incorrect, try this code:</p>\n\n<pre><code>// Declare the logon types as constants\nconst long LOGON32_LOGON_INTERACTIVE = 2;\nconst long LOGON32_LOGON_NETWORK = 3;\n\n// Declare the logon providers as constants\nconst long LOGON32_PROVIDER_DEFAULT = 0;\nconst long LOGON32_PROVIDER_WINNT50 = 3;\nconst long LOGON32_PROVIDER_WINNT40 = 2;\nconst long LOGON32_PROVIDER_WINNT35 = 1;\n\n[DllImport(\"advapi32.dll\", EntryPoint = \"LogonUser\")]\nprivate static extern bool LogonUser(\n string lpszUsername,\n string lpszDomain,\n string lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n ref IntPtr phToken);\n\npublic static WindowsImpersonationContext ImpersonateCurrentUserBegin(System.Net.NetworkCredential credential)\n{\n WindowsImpersonationContext impersonationContext = null;\n if (credential == null || credential.UserName.Length == 0 || credential.Password.Length == 0 || credential.Domain.Length == 0)\n {\n throw new Exception(\"Incomplete user credentials specified\");\n }\n impersonationContext = Security.Impersonate(credential);\n if (impersonationContext == null)\n {\n return null;\n }\n else\n {\n return impersonationContext;\n }\n}\n\npublic static void ImpersonateCurrentUserEnd(WindowsImpersonationContext impersonationContext)\n{\n if (impersonationContext != null)\n {\n impersonationContext.Undo();\n }\n}\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 247583,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 1,
"selected": false,
"text": "<p>What does <code>HttpContext.User.Identity.Name</code> give you?</p>\n\n<p>Assume you've checked the security tab within IIS that it allows anonymous access? </p>\n\n<p>Are you within an active directory that has some strange local policy?</p>\n"
},
{
"answer_id": 56868986,
"author": "Kushan Gowda",
"author_id": 9819727,
"author_profile": "https://Stackoverflow.com/users/9819727",
"pm_score": 2,
"selected": false,
"text": "<p>I think I understand your problem here.</p>\n\n<p>Things to know before moving further,</p>\n\n<ol>\n<li><p>There are different security context while an application is running. Like <code>System.Security.Principal.WindowsIdentity.GetCurrent().Name</code>, and the one you mentioned above, i.e. <code>System.Threading.Thread.CurrentPrincipal.Identity.Name</code></p></li>\n<li><p>In a web application, <code>System.Threading.Thread.CurrentPrincipal.Identity</code> is always provided by <code>HttpContext.Current.User.Identity</code>.</p></li>\n</ol>\n\n<p>Coming to your point. If you want to modify <code>System.Threading.Thread.CurrentPrincipal.Identity</code>, then modify <code>HttpContext.Current.User.Identity</code> which initially provided by your authentication mechanism.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
I have a blank test app created in VS 2005 as ASP.NET application. [MSDN says](http://msdn.microsoft.com/en-us/library/ms998351.aspx) that
>
> By default, ASP.NET does not use impersonation, and your code runs using the ASP.NET application's process identity.
>
>
>
And I have the following web.config
```
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" defaultLanguage="c#" />
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<identity impersonate="false"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
```
So it seem impersonation is disabled just like [the article](http://msdn.microsoft.com/en-us/library/ms998351.aspx) is suggesting.
My aspx is blank default and the codebehind is
```
namespace TestWebapp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(String.Format("Before1: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
int a = 0;
System.Diagnostics.Debug.WriteLine(String.Format("After: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
} finally
{
ctx.Undo();
}
}
}
}
```
When I reload the page I get the following debug output:
>
> [5288] Before1: Current Princupal =
> DOMAIN\User
> [5288] After: Current Princupal =
> DOMAIN\User
>
>
>
Output is the same with
```
<identity impersonate="false"/>
```
The web site uses Default Application Pool and the pool is set up to use NETWORK SERVICE account for its worker processes.
I'm sure the application uses the web.config it should use and the w3p.exe worker process is running under NETWORK SERVICE.
What can be wrong in this case?
Thanks!
@Edit: Rob, thanks for the tip!
The $user shortcut shows me that everything is happening as I expect: with impersonation on I have the process running user NT AUTHORITY\NETWORK SERVICE and the thread has DOMAIN\User before WindowsIdentity.Impersonate(IntPtr.Zero) and "No Token. Thread not impersonating." after.
But Thread.CurrentPrincipal.Identity.Name and HttpContext.Current.User.Identity.Name still give me DOMAIN\User in both places.
@Edit: I've found out that to get Thread.CurrentPrincipal and HttpContext.Current.User changed I have to manually do it:
```
Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
HttpContext.Current.User = Thread.CurrentPrincipal;
```
I'm not sure what's the point here, but anyway. I now have a problem with sharepoint shared services manage user profile permission but that's another question.
|
I think I understand your problem here.
Things to know before moving further,
1. There are different security context while an application is running. Like `System.Security.Principal.WindowsIdentity.GetCurrent().Name`, and the one you mentioned above, i.e. `System.Threading.Thread.CurrentPrincipal.Identity.Name`
2. In a web application, `System.Threading.Thread.CurrentPrincipal.Identity` is always provided by `HttpContext.Current.User.Identity`.
Coming to your point. If you want to modify `System.Threading.Thread.CurrentPrincipal.Identity`, then modify `HttpContext.Current.User.Identity` which initially provided by your authentication mechanism.
|
247,571 |
<p>I'm trying filter the child collection of an aggregate root when loading it with Nhibernate. Load a Customer with all their Orders that have been shipped. Is this possible?</p>
|
[
{
"answer_id": 248184,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 2,
"selected": false,
"text": "<p>Well, you can expose properties that are filtered in the map, like so:</p>\n\n<pre><code><bag name=\"shippedOrders\" ... where=\"Status == 'Shipped'\" >\n <key column=\"CustomerId\" />\n <one-to-many class=\"Order\" />\n</bag>\n</code></pre>\n\n<p>The 'where' attribute is arbitrary SQL.</p>\n\n<p>Theoretically you could have two properties of Customer, Orders and ShippedOrders. However, I should say that I have not done this, and I would want to test how NH handles cascading in this case. In any case, you will have to take care when new items are added/removed that they are added/removed correctly to both collections.</p>\n\n<p>The fact that you want to do this makes we wonder if Order is an aggregate root. It might be less trouble in the long run doing it like this: </p>\n\n<pre><code>orderRepository.GetOrders(int customerId, OrderStatus[] statuses)\n</code></pre>\n"
},
{
"answer_id": 250135,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "<p>You could look at it the other way - load all the shipped orders for a Customer. </p>\n\n<pre><code>session.CreateCriteria( typeOf(Order) )\n .Add( Restrictions.Eq(\"Shipped\", shippedStatus ) )\n .Add( Restrictions.Eq(\"Customer\", requiredCustomer) )\n .List<Order>();\n</code></pre>\n"
},
{
"answer_id": 868927,
"author": "Sebastian Markbåge",
"author_id": 76987,
"author_profile": "https://Stackoverflow.com/users/76987",
"pm_score": 1,
"selected": false,
"text": "<p>You can also do it using HQL using session.Filter(customer.Orders, \"where this.Status == 'Shipped'\");</p>\n"
},
{
"answer_id": 868955,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 1,
"selected": false,
"text": "<pre><code>ICriteria crit = session.CreateCriteria (typeof(Customer));\n\ncrit.CreateAlias (\"Orders\", \"o\");\ncrit.Add (Expression.Eq (\"o.Status\", shippedStatus));\ncrit.Add (Expression.Eq (\"Id\", customerId));\n\nreturn crit.UniqueResult <Customer>();\n</code></pre>\n\n<p>something like that.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying filter the child collection of an aggregate root when loading it with Nhibernate. Load a Customer with all their Orders that have been shipped. Is this possible?
|
Well, you can expose properties that are filtered in the map, like so:
```
<bag name="shippedOrders" ... where="Status == 'Shipped'" >
<key column="CustomerId" />
<one-to-many class="Order" />
</bag>
```
The 'where' attribute is arbitrary SQL.
Theoretically you could have two properties of Customer, Orders and ShippedOrders. However, I should say that I have not done this, and I would want to test how NH handles cascading in this case. In any case, you will have to take care when new items are added/removed that they are added/removed correctly to both collections.
The fact that you want to do this makes we wonder if Order is an aggregate root. It might be less trouble in the long run doing it like this:
```
orderRepository.GetOrders(int customerId, OrderStatus[] statuses)
```
|
247,596 |
<p>svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:</p>
<pre><code><svg ... onload="RunScript(evt);"...>
<script type="text/javascript">
...
function RunScript(loadEvent) {
// Get object in my html by id
var objElement = top.document.getElementById('objid1');
if (objElement)
{
// Extend object tag object's methods
objElement.SVGsetDimension = setDimension;
...
}
function setDimention(w, h) {...}
</code></pre>
<p>In my main html file, the svg is embedded in an object tag like this:</p>
<pre><code><object id="objid1" data="mygrahic.svg" ... >
<a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10);
return false;"
...>Set new dimention</a>...
</code></pre>
<p>This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:</p>
<pre><code><object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... >
</code></pre>
<p>the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?</p>
<p>Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.</p>
|
[
{
"answer_id": 247811,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 3,
"selected": true,
"text": "<p>I think the clue might be in 'on another site'. There are strict rules about when JavaScript programs from different sites are allowed to communicate with teach other. The embedded SVG is being treated the same way a document inside an <code>iframe</code> would.</p>\n"
},
{
"answer_id": 248183,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 1,
"selected": false,
"text": "<p>pdc has this one right. Browsers work hard to prevent cross site scripting attacks (XSS) and this is the result. You cannot execute scripts in a document loaded from another domain, or using another port or protocol. For more info you can see: <a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Same_origin_policy</a></p>\n"
},
{
"answer_id": 3510064,
"author": "Ms2ger",
"author_id": 33466,
"author_profile": "https://Stackoverflow.com/users/33466",
"pm_score": 2,
"selected": false,
"text": "<p>So, what you're doing is, from the point of view of a browser, equivalent to the following:</p>\n\n<pre><code><script>\nfunction stealPassword() {\n var passwordInput = document.querySelector('input[type=\"password\"]');\n var value = passwordInput.value; // My password!\n sendPasswordToServerToStealMyMoney(value);\n}\n</script>\n<iframe src=mybank.com onload=stealPassword()></iframe>\n</code></pre>\n\n<p>I think you'll understand why this isn't desirable. (There should probably be a warning or an exception in your error console, though.)</p>\n"
},
{
"answer_id": 8004401,
"author": "saburou",
"author_id": 1028976,
"author_profile": "https://Stackoverflow.com/users/1028976",
"pm_score": 0,
"selected": false,
"text": "<p>From my experiense;\nYour Code is true ,so that run exactly.\nMy PC Windows 7,IE9,installed Adobe Viewer.\nBoth unless SVG Viewer,IE9 SVG drawed,but can't run SVG TAG Animation,\nonly can run Javascript Animation.\nSo,under Windows XP,IE8,installed Adobe SVG Viewer, Same result(run exactly).</p>\n\n<p>Firefox SVG can't run(SVG ecmascript animation) exactly under my PC.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:
```
<svg ... onload="RunScript(evt);"...>
<script type="text/javascript">
...
function RunScript(loadEvent) {
// Get object in my html by id
var objElement = top.document.getElementById('objid1');
if (objElement)
{
// Extend object tag object's methods
objElement.SVGsetDimension = setDimension;
...
}
function setDimention(w, h) {...}
```
In my main html file, the svg is embedded in an object tag like this:
```
<object id="objid1" data="mygrahic.svg" ... >
<a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10);
return false;"
...>Set new dimention</a>...
```
This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:
```
<object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... >
```
the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?
Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.
|
I think the clue might be in 'on another site'. There are strict rules about when JavaScript programs from different sites are allowed to communicate with teach other. The embedded SVG is being treated the same way a document inside an `iframe` would.
|
247,626 |
<p>How can I set cron to run certain commands every one and a half hours?</p>
|
[
{
"answer_id": 247640,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 4,
"selected": false,
"text": "<p>Is there a good reason why you can't use 1 hour or 2 hours? It would be simpler for sure.</p>\n\n<p>I haven't tried this personally, but you can find some info here on getting cron to run every 90 minutes: <a href=\"http://keithdevens.com/weblog/archive/2004/May/05/cron\" rel=\"noreferrer\">http://keithdevens.com/weblog/archive/2004/May/05/cron</a></p>\n\n<p>An excert from the above link:</p>\n\n<pre><code>0 0,3,6,9,12,15,18,21 * * * <commands>\n30 1,4,7,10,13,16,19,22 * * * <commands>\n</code></pre>\n"
},
{
"answer_id": 247643,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": false,
"text": "<p>That's not possible with a single expression in normal <code>cron</code>.</p>\n<p>The best you could do without modifying the code is:</p>\n<pre><code>0 0,3,6,9,12,15,18,21 * * * [cmd]\n30 1,4,7,10,13,16,19,22 * * * [cmd]\n</code></pre>\n<p>These <em>might</em> be compressible, depending on the version of cron you have to:</p>\n<pre><code>0 */3 * * * [cmd]\n30 1-23/3 * * * [cmd]\n</code></pre>\n"
},
{
"answer_id": 247644,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": false,
"text": "<p>Two lines in the crontab. Along the lines of:</p>\n\n<pre><code>0 0,3,6,9,12,15,18,21 * * * /usr/bin/foo\n30 1,4,7,10,13,16,19,22 * * * /usr/bin/foo\n</code></pre>\n"
},
{
"answer_id": 247650,
"author": "Thomas DeGan",
"author_id": 12470,
"author_profile": "https://Stackoverflow.com/users/12470",
"pm_score": 3,
"selected": false,
"text": "<p>You could do it with two crontab entries. Each runs every three hours and they are offset by 90 minutes something like this:</p>\n\n<p>0 0,3,6,9,12,15,18,21 * * * </p>\n\n<p>30 1,4,7,10,13,16,19,22 * * * </p>\n"
},
{
"answer_id": 247749,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 1,
"selected": false,
"text": "<p>You could also use <a href=\"http://fcron.free.fr/\" rel=\"nofollow noreferrer\">fcron</a> which also accepts more complex time specifications such as :</p>\n\n<pre><code>@ 01h30 my_cmd\n</code></pre>\n"
},
{
"answer_id": 21820687,
"author": "user3174711",
"author_id": 3174711,
"author_profile": "https://Stackoverflow.com/users/3174711",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#! /bin/sh\n\n# Minute Cron\n# Usage: cron-min start\n# Copyright 2014 by Marc Perkel\n# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron\"\n# Free to use with attribution\n\n# Run this script under Cron once a minute\n\nbasedir=/etc/cron-min\n\nif [ $# -gt 0 ]\nthen\n echo\n echo \"cron-min by Marc Perkel\"\n echo\n echo \"This program is used to run all programs in a directory in parallel every X minutes.\"\n echo\n echo \"Usage: cron-min\"\n echo\n echo \"The scheduling is done by creating directories with the number of minutes as part of the\"\n echo \"directory name. The minutes do not have to evenly divide into 60 or be less than 60.\"\n echo\n echo \"Examples:\"\n echo \" /etc/cron-min/1 # Executes everything in that directory every 1 minute\"\n echo \" /etc/cron-min/5 # Executes everything in that directory every 5 minutes\"\n echo \" /etc/cron-min/13 # Executes everything in that directory every 13 minutes\"\n echo \" /etc/cron-min/90 # Executes everything in that directory every 90 minutes\"\n echo\n exit\nfi\n\nfor dir in $basedir/* ; do\n minutes=${dir##*/}\n if [ $(( ($(date +%s) / 60) % $minutes )) -eq 0 ]\n then\n for program in $basedir/$minutes/* ; do\n if [ -x $program ]\n then\n $program &> /dev/null &\n fi\n done\n fi\ndone\n</code></pre>\n"
},
{
"answer_id": 24449393,
"author": "user3782709",
"author_id": 3782709,
"author_profile": "https://Stackoverflow.com/users/3782709",
"pm_score": -1,
"selected": false,
"text": "<p>added the following to my crontab and is working</p>\n\n<pre><code>15 */1 * * * root /usr/bin/some_script.sh >> /tmp/something.log\n</code></pre>\n"
},
{
"answer_id": 25537959,
"author": "Alex",
"author_id": 3984676,
"author_profile": "https://Stackoverflow.com/users/3984676",
"pm_score": 2,
"selected": false,
"text": "<p><code>*/10 * * * * root perl -e 'exit(time()%(90*60)>60)' && command</code></p>\n\n<p>90 — it is one and a half hour in minutes </p>\n\n<p>\"> 60\" — I give to cron ability to delay the start of script during a minute</p>\n\n<p>Also with help of this hack you can set any period with a minute resolution</p>\n\n<p>For example start the script every 71 minutes</p>\n\n<p><code>* * * * * root perl -e 'exit(time()%(71*60)>60)' && command</code></p>\n"
},
{
"answer_id": 31759088,
"author": "stefanmaric",
"author_id": 2457929,
"author_profile": "https://Stackoverflow.com/users/2457929",
"pm_score": 2,
"selected": false,
"text": "<p>You can achieve any frequency if you count the minutes(, hours, days, or weeks) since <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow\">Epoch</a>, add a condition to the top of your script, and set the script to run every minute on your crontab:</p>\n\n<pre><code>#!/bin/bash\n\nminutesSinceEpoch=$(($(date +'%s / 60')))\n\n# every 90 minutes (one and a half hours)\nif [[ $(($minutesSinceEpoch % 90)) -ne 0 ]]; then\n exit 0\nfi\n</code></pre>\n\n<p><a href=\"http://linux.die.net/man/1/date\" rel=\"nofollow\"><code>date(1)</code></a> returns current date, we format it as seconds since Epoch (<code>%s</code>) and then we do basic maths:</p>\n\n<pre><code># .---------------------- bash command substitution\n# |.--------------------- bash arithmetic expansion\n# || .------------------- bash command substitution\n# || | .---------------- date command\n# || | | .------------ FORMAT argument\n# || | | | .----- formula to calculate minutes/hours/days/etc is included into the format string passed to date command\n# || | | | |\n# ** * * * * \n $(($(date +'%s / 60')))\n# * * ---------------\n# | | | \n# | | ·----------- date should result in something like \"1438390397 / 60\"\n# | ·-------------------- it gets evaluated as an expression. (the maths)\n# ·---------------------- and we can store it\n</code></pre>\n\n<p>And you may use this approach with hourly, daily, or monthly cron jobs:</p>\n\n<pre><code>#!/bin/bash\n# We can get the\n\nminutes=$(($(date +'%s / 60')))\nhours=$(($(date +'%s / 60 / 60')))\ndays=$(($(date +'%s / 60 / 60 / 24')))\nweeks=$(($(date +'%s / 60 / 60 / 24 / 7')))\n\n# or even\n\nmoons=$(($(date +'%s / 60 / 60 / 24 / 656')))\n\n# passed since Epoch and define a frequency\n# let's say, every 7 hours\n\nif [[ $(($hours % 7)) -ne 0 ]]; then\n exit 0\nfi\n\n# and your actual script starts here\n</code></pre>\n"
},
{
"answer_id": 70652799,
"author": "Marzycielx",
"author_id": 15670345,
"author_profile": "https://Stackoverflow.com/users/15670345",
"pm_score": 1,
"selected": false,
"text": "<p>use "<a href=\"https://linuxize.com/post/at-command-in-linux/\" rel=\"nofollow noreferrer\">at</a>" on crontab</p>\n<p>the command is executed at midnight and then set to execute at 1.30</p>\n<p>etc ..</p>\n<p><code>0 */3 * * * echo "Command" | at now +90 minutes && Command</code></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
How can I set cron to run certain commands every one and a half hours?
|
That's not possible with a single expression in normal `cron`.
The best you could do without modifying the code is:
```
0 0,3,6,9,12,15,18,21 * * * [cmd]
30 1,4,7,10,13,16,19,22 * * * [cmd]
```
These *might* be compressible, depending on the version of cron you have to:
```
0 */3 * * * [cmd]
30 1-23/3 * * * [cmd]
```
|
247,639 |
<p>I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:</p>
<ul>
<li><p><em>Pool</em>. This is a class which allocates memory efficiently, for some definition of 'efficient'. <em>Pool</em> is guaranteed to return a chunk of memory that is aligned for the requested size.</p></li>
<li><p><em>Obj_list</em>. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of <em>Obj_list</em> is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.</p></li>
<li><p><em>Aggregate</em>. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. <em>Aggregate</em>s can be empty, or manage an arbitrary number of objects.</p></li>
</ul>
<p>In this example, <em>Aggregate</em> items are always allocated from <em>Pool</em>s, so they are always aligned. The only occurrences of <em>Obj_list</em> in this example are the 'hidden' members in <em>Aggregate</em> objects, and therefore they are always allocated using <em>placement new</em>. Here are the support classes:</p>
<pre><code>class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
</code></pre>
<p>And here is Aggregate. Note that member declaration <em>member_list_store_d</em>:</p>
<pre><code>// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
</code></pre>
<p>It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:</p>
<pre><code>Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
</code></pre>
<p>You may be tempted to suggest that we replace the char array with a pointer to the <em>Obj_list</em> type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an <em>Obj_list</em> would cost one more pointer in the case when <em>Aggregate</em> objects <em>do</em> have members.</p>
<p>Besides that, I don't really want to get distracted from the main question here, which is alignment. I <em>think</em> the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' <em>new</em>.</p>
<p>So, does the above construct do anything more than cause an occasional pipe stall?</p>
<p><strong>Edit</strong>: I realize that there are ways to <em>replace</em> the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.</p>
<p>However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks!</p>
|
[
{
"answer_id": 247690,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 1,
"selected": false,
"text": "<p>The alignment will be picked by the compiler according to its defaults, this will probably end up as four-bytes under GCC / MSVC.</p>\n\n<p>This should only be a problem if there is code (SIMD/DMA) that requires a specific alignment. In this case you should be able to use compiler directives to ensure that member_list_store_d is aligned, or increase the size by (alignment-1) and use an appropriate offset.</p>\n"
},
{
"answer_id": 248826,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 0,
"selected": false,
"text": "<p>Allocate the char array <code>member_list_store_d</code> with malloc or global operator new[], either of which will give storage aligned for any type.</p>\n\n<p>Edit: Just read the OP again - you don't want to pay for another pointer. Will read again in the morning.</p>\n"
},
{
"answer_id": 248860,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to ensure alignment of your structures, just do a</p>\n\n<pre><code>// MSVC\n#pragma pack(push,1)\n\n// structure definitions\n\n#pragma pack(pop)\n\n// *nix\nstruct YourStruct\n{\n ....\n} __attribute__((packed));\n</code></pre>\n\n<p>To ensure 1 byte alignment of your char array in Aggregate</p>\n"
},
{
"answer_id": 248880,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Can you simply have an instance of Obj_list inside Aggregate? IOW, something along the lines of </p>\n\n<p>class Aggregate : public Lesser\n{\n ...\nprotected:\n Obj_list list;\n};</p>\n\n<p>I must be missing something, but I can't figure why this is bad.</p>\n\n<p>As to your question - it's perfectly compiler-dependent. Most compilers, though, will align every member at word boundary by default, even if the member's type does not need to be aligned that way for correct access.</p>\n"
},
{
"answer_id": 250159,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": true,
"text": "<p>Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.</p>\n\n<p>Your portable options to fix this are:</p>\n\n<ul>\n<li>allocate the storage with malloc or\na global allocation function, but\nyou think this is too\nexpensive.</li>\n<li><p>as Arkadiy says, make your buffer an Obj_list member:</p>\n\n<pre><code>Obj_list list;\n</code></pre></li>\n</ul>\n\n<p>but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor</p>\n\n<pre><code>list.~Obj_list();\n</code></pre>\n\n<p>before doing a placement new into this storage.</p>\n\n<p>Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.</p>\n\n<p>Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] |
I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks!
|
Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
* allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
* as Arkadiy says, make your buffer an Obj\_list member:
```
Obj_list list;
```
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
```
list.~Obj_list();
```
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem.
|
247,647 |
<p>I have a plugin for OpenFire that creates and delivers a message to a user using</p>
<pre><code>XMPPServer.getInstance().getMessageRouter().route(message)
</code></pre>
<p>What I would like to know is what happens to that message if the user is not online. </p>
<p>My goal is to only have the message delivered if the user is online, and fail or be routed to the bit bucket otherwise.</p>
|
[
{
"answer_id": 248003,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 3,
"selected": true,
"text": "<p>It's all down to Openfire config. In the Openfire admin console, go to Server -> Server Settings -> Offline Messages. There are options for store, bounce and drop. </p>\n\n<ul>\n<li>Store: deliver the message when the\nuser comes back online.</li>\n<li>Drop: Just discard the message.</li>\n<li>Bounce: Discard and notify the sender with a return message.</li>\n</ul>\n"
},
{
"answer_id": 258135,
"author": "Joe Hildebrand",
"author_id": 8388,
"author_profile": "https://Stackoverflow.com/users/8388",
"pm_score": 1,
"selected": false,
"text": "<p>Another approach, if you just want these messages to not go offline without affecting the delivery of other messages, is to use type='headline'. Headlines are not terribly well-specified, but <a href=\"http://xmpp.org/internet-drafts/draft-saintandre-rfc3921bis-07.html#message-syntax-type\" rel=\"nofollow noreferrer\">RFC 3921bis Section 5.2.2</a> says:</p>\n\n<blockquote>\n <p>headline -- The message provides an alert, a notification, or other information to which no reply is expected (e.g., news headlines, sports updates, near-real-time market data, and syndicated content). Because no reply to the message is expected, typically a receiving client will present a message of type \"headline\" in an interface that appropriately differentiates the message from standalone messages, chat messages, or groupchat messages (e.g., by not providing the recipient with the ability to reply). <strong>The receiving server SHOULD deliver the message to all of the recipient's available resources.</strong></p>\n</blockquote>\n\n<p>Most servers of today will just silently drop headlines to offline users, and deliver to the highest priority resource if the user is online.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21925/"
] |
I have a plugin for OpenFire that creates and delivers a message to a user using
```
XMPPServer.getInstance().getMessageRouter().route(message)
```
What I would like to know is what happens to that message if the user is not online.
My goal is to only have the message delivered if the user is online, and fail or be routed to the bit bucket otherwise.
|
It's all down to Openfire config. In the Openfire admin console, go to Server -> Server Settings -> Offline Messages. There are options for store, bounce and drop.
* Store: deliver the message when the
user comes back online.
* Drop: Just discard the message.
* Bounce: Discard and notify the sender with a return message.
|
247,666 |
<p>I need to use C# programatically to append several preexisting <code>docx</code> files into a single, long <code>docx</code> file - including special markups like bullets and images. Header and footer information will be stripped out, so those won't be around to cause any problems.</p>
<p>I can find plenty of information about manipulating an individual <code>docx</code> file with .NET Framework 3, but nothing easy or obvious about how you would merge files. There is also a third-party program (Acronis.Words) that will do it, but it is prohibitively expensive.</p>
<h2>Update:</h2>
<p>Automating through Word has been suggested, but my code is going to be running on ASP.NET on an IIS web server, so going out to Word is not an option for me. Sorry for not mentioning that in the first place.</p>
|
[
{
"answer_id": 248249,
"author": "Terence Lewis",
"author_id": 32539,
"author_profile": "https://Stackoverflow.com/users/32539",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a little test app a while ago to do this. My test app worked with Word 2003 documents (.doc) not .docx, but I imagine the process is the same - I should think all you'd have to change is to use a newer version of the Primary Interop Assembly. This code would look a lot neater with the new C# 4.0 features...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Microsoft.Office.Interop.Word;\nusing Microsoft.Office.Core;\nusing System.Runtime.InteropServices;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n new Program().Start();\n }\n\n private void Start()\n {\n object fileName = Path.Combine(Environment.CurrentDirectory, @\"NewDocument.doc\");\n File.Delete(fileName.ToString());\n\n try\n {\n WordApplication = new ApplicationClass();\n var doc = WordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);\n try\n {\n doc.Activate();\n\n AddDocument(@\"D:\\Projects\\WordTests\\ConsoleApplication1\\Documents\\Doc1.doc\", doc, false);\n AddDocument(@\"D:\\Projects\\WordTests\\ConsoleApplication1\\Documents\\Doc2.doc\", doc, true);\n\n doc.SaveAs(ref fileName,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing);\n }\n finally\n {\n doc.Close(ref missing, ref missing, ref missing);\n }\n }\n finally\n {\n WordApplication.Quit(ref missing, ref missing, ref missing);\n }\n }\n\n private void AddDocument(string path, Document doc, bool lastDocument)\n {\n object subDocPath = path;\n var subDoc = WordApplication.Documents.Open(ref subDocPath, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing);\n try\n {\n\n object docStart = doc.Content.End - 1;\n object docEnd = doc.Content.End;\n\n object start = subDoc.Content.Start;\n object end = subDoc.Content.End;\n\n Range rng = doc.Range(ref docStart, ref docEnd);\n rng.FormattedText = subDoc.Range(ref start, ref end);\n\n if (!lastDocument)\n {\n InsertPageBreak(doc);\n }\n }\n finally\n {\n subDoc.Close(ref missing, ref missing, ref missing);\n }\n }\n\n private static void InsertPageBreak(Document doc)\n {\n object docStart = doc.Content.End - 1;\n object docEnd = doc.Content.End;\n Range rng = doc.Range(ref docStart, ref docEnd);\n\n object pageBreak = WdBreakType.wdPageBreak;\n rng.InsertBreak(ref pageBreak);\n }\n\n private ApplicationClass WordApplication { get; set; }\n\n private object missing = Type.Missing;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 249119,
"author": "Rob Windsor",
"author_id": 28785,
"author_profile": "https://Stackoverflow.com/users/28785",
"pm_score": 3,
"selected": false,
"text": "<p>You don't need to use automation. DOCX files are based on the OpenXML Formats. They are just zip files with a bunch of XML and binary parts (think files) inside. You can open them with the Packaging API (System.IO.Packaging in WindowsBase.dll) and manipulate them with any of the XML classes in the Framework.</p>\n\n<p>Check out <a href=\"http://openxmldeveloper.org\" rel=\"noreferrer\">OpenXMLDeveloper.org</a> for details.</p>\n"
},
{
"answer_id": 448606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Its quit complex so the code is outside the scope of a forum post, I'd be writing your App for you, but to sum up.</p>\n\n<ul>\n<li>Open both documents as Packages </li>\n<li>Loop through the second docuemnt's parts looking for images and embbed stuff</li>\n<li>Add these parts to the first package remembering the new relationship IDs(this involves alot of stream work)</li>\n<li>open the document.xml part in the second document and replace all the old relationship IDs with the new ones- Append all the child nodes, but not the root node, of the second document.xml to the first document.xml</li>\n<li>save all the XmlDocuments and Flush the Package</li>\n</ul>\n"
},
{
"answer_id": 465257,
"author": "Pete Skelly",
"author_id": 57516,
"author_profile": "https://Stackoverflow.com/users/57516",
"pm_score": 2,
"selected": false,
"text": "<p>You want to use AltChunks and the OpenXml SDK 1.0 (at a minimum, 2.0 if you can). Check out Eric White's blog for more details and just as a great resource!. Here is a code sample that should get you started, if not work immediately.</p>\n\n<pre><code>public void AddAltChunkPart(Stream parentStream, Stream altStream, string altChunkId)\n{\n //make sure we are at the start of the stream \n parentStream.Position = 0;\n altStream.Position = 0;\n //push the parentStream into a WordProcessing Document\n using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(parentStream, true))\n {\n //get the main document part\n MainDocumentPart mainPart = wordDoc.MainDocumentPart;\n //create an altChunk part by adding a part to the main document part\n AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(altChunkPartType, altChunkId);\n //feed the altChunk stream into the chunk part\n chunk.FeedData(altStream);\n //create and XElement to represent the new chunk in the document\n XElement newChunk = new XElement(altChunk, new XAttribute(relId, altChunkId));\n //Add the chunk to the end of the document (search to last paragraph in body and add at the end)\n wordDoc.MainDocumentPart.GetXDocument().Root.Element(body).Elements(paragraph).Last().AddAfterSelf(newChunk);\n //Finally, save the document\n wordDoc.MainDocumentPart.PutXDocument();\n }\n //reset position of parent stream\n parentStream.Position = 0;\n}\n</code></pre>\n"
},
{
"answer_id": 470631,
"author": "Sumit Ghosh",
"author_id": 56150,
"author_profile": "https://Stackoverflow.com/users/56150",
"pm_score": 0,
"selected": false,
"text": "<p>I had made an application in C# to merge RTF files into one doc,Iam hopeful it should work for DOC and DOCX files as well.</p>\n\n<pre><code> Word._Application wordApp;\n Word._Document wordDoc;\n object outputFile = outputFileName;\n object missing = System.Type.Missing;\n object vk_false = false;\n object defaultTemplate = defaultWordDocumentTemplate;\n object pageBreak = Word.WdBreakType.wdPageBreak;\n string[] filesToMerge = new string[pageCounter];\n filestoDelete = new string[pageCounter];\n\n for (int i = 0; i < pageCounter; i++)\n {\n filesToMerge[i] = @\"C:\\temp\\temp\" + i.ToString() + \".rtf\";\n filestoDelete[i] = @\"C:\\temp\\temp\" + i.ToString() + \".rtf\"; \n }\n try\n {\n wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);\n }\n catch(Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n Word.Selection selection= wordApp.Selection;\n\n foreach (string file in filesToMerge)\n {\n selection.InsertFile(file,\n ref missing,\n ref missing,\n ref missing,\n ref missing);\n\n selection.InsertBreak(ref pageBreak); \n }\n wordDoc.SaveAs(ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing);\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 2463729,
"author": "GRGodoi",
"author_id": 71666,
"author_profile": "https://Stackoverflow.com/users/71666",
"pm_score": 5,
"selected": false,
"text": "<p>In spite of all good suggestions and solutions submitted, I developed an alternative. In my opinion you should avoid using Word in server applications entirely. So I worked with OpenXML, but it did not work with AltChunk. I added text to original body, I receive a List of byte[] instead a List of file names but you can easily change the code to your needs.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Xml.Linq;\nusing DocumentFormat.OpenXml.Packaging;\nusing DocumentFormat.OpenXml.Wordprocessing;\n\nnamespace OfficeMergeControl\n{\n public class CombineDocs\n {\n public byte[] OpenAndCombine( IList<byte[]> documents )\n {\n MemoryStream mainStream = new MemoryStream();\n\n mainStream.Write(documents[0], 0, documents[0].Length);\n mainStream.Position = 0;\n\n int pointer = 1;\n byte[] ret;\n try\n {\n using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(mainStream, true))\n {\n\n XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);\n\n for (pointer = 1; pointer < documents.Count; pointer++)\n {\n WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(documents[pointer]), true);\n XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);\n\n newBody.Add(tempBody);\n mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());\n mainDocument.MainDocumentPart.Document.Save();\n mainDocument.Package.Flush();\n }\n }\n }\n catch (OpenXmlPackageException oxmle)\n {\n throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, \"Error while merging files. Document index {0}\", pointer), oxmle);\n }\n catch (Exception e)\n {\n throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, \"Error while merging files. Document index {0}\", pointer), e);\n }\n finally\n {\n ret = mainStream.ToArray();\n mainStream.Close();\n mainStream.Dispose();\n }\n return (ret);\n }\n }\n}\n</code></pre>\n\n<p>I hope this helps you.</p>\n"
},
{
"answer_id": 12089639,
"author": "Mike B",
"author_id": 560237,
"author_profile": "https://Stackoverflow.com/users/560237",
"pm_score": 3,
"selected": false,
"text": "<p>This is a very late to the original question and quite a bit has change but thought I would share the way I have written my merge logic. This makes use of the <a href=\"http://powertools.codeplex.com/\" rel=\"noreferrer\">Open XML Power Tools</a></p>\n\n<pre><code>public byte[] CreateDocument(IList<byte[]> documentsToMerge)\n{\n List<Source> documentBuilderSources = new List<Source>();\n foreach (byte[] documentByteArray in documentsToMerge)\n {\n documentBuilderSources.Add(new Source(new WmlDocument(string.Empty, documentByteArray), false));\n }\n\n WmlDocument mergedDocument = DocumentBuilder.BuildDocument(documentBuilderSources);\n return mergedDocument.DocumentByteArray;\n}\n</code></pre>\n\n<p>Currently this is working very well in our application. I have changed the code a little because my requirements is that each document that needs to be processed first. So what gets passed in is a DTO object with the template byte array and the various values that need to be replaced. Here is how my code currently looks. Which takes the code a little bit further.</p>\n\n<pre><code>public byte[] CreateDocument(IList<DocumentSection> documentTemplates)\n{\n List<Source> documentBuilderSources = new List<Source>();\n foreach (DocumentSection documentTemplate in documentTemplates.OrderBy(dt => dt.Rank))\n {\n // Take the template replace the items and then push it into the chunk\n using (MemoryStream templateStream = new MemoryStream())\n {\n templateStream.Write(documentTemplate.Template, 0, documentTemplate.Template.Length);\n\n this.ProcessOpenXMLDocument(templateStream, documentTemplate.Fields);\n\n documentBuilderSources.Add(new Source(new WmlDocument(string.Empty, templateStream.ToArray()), false));\n }\n }\n\n WmlDocument mergedDocument = DocumentBuilder.BuildDocument(documentBuilderSources);\n return mergedDocument.DocumentByteArray;\n}\n</code></pre>\n"
},
{
"answer_id": 60540185,
"author": "Jinjinov",
"author_id": 4675770,
"author_profile": "https://Stackoverflow.com/users/4675770",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone who wants to work with a list of file names:</p>\n\n<pre><code>void AppendToExistingFile(string existingFile, IList<string> filenames)\n{\n using (WordprocessingDocument document = WordprocessingDocument.Open(existingFile, true))\n {\n MainDocumentPart mainPart = document.MainDocumentPart;\n\n for (int i = filenames.Count - 1; i >= 0; --i)\n {\n string altChunkId = \"AltChunkId\" + i;\n AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);\n\n using (FileStream fileStream = File.Open(filenames[i], FileMode.Open))\n {\n chunk.FeedData(fileStream);\n }\n\n AltChunk altChunk = new AltChunk { Id = altChunkId };\n mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());\n }\n\n mainPart.Document.Save();\n }\n}\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32471/"
] |
I need to use C# programatically to append several preexisting `docx` files into a single, long `docx` file - including special markups like bullets and images. Header and footer information will be stripped out, so those won't be around to cause any problems.
I can find plenty of information about manipulating an individual `docx` file with .NET Framework 3, but nothing easy or obvious about how you would merge files. There is also a third-party program (Acronis.Words) that will do it, but it is prohibitively expensive.
Update:
-------
Automating through Word has been suggested, but my code is going to be running on ASP.NET on an IIS web server, so going out to Word is not an option for me. Sorry for not mentioning that in the first place.
|
In spite of all good suggestions and solutions submitted, I developed an alternative. In my opinion you should avoid using Word in server applications entirely. So I worked with OpenXML, but it did not work with AltChunk. I added text to original body, I receive a List of byte[] instead a List of file names but you can easily change the code to your needs.
```
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OfficeMergeControl
{
public class CombineDocs
{
public byte[] OpenAndCombine( IList<byte[]> documents )
{
MemoryStream mainStream = new MemoryStream();
mainStream.Write(documents[0], 0, documents[0].Length);
mainStream.Position = 0;
int pointer = 1;
byte[] ret;
try
{
using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(mainStream, true))
{
XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);
for (pointer = 1; pointer < documents.Count; pointer++)
{
WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(documents[pointer]), true);
XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);
newBody.Add(tempBody);
mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());
mainDocument.MainDocumentPart.Document.Save();
mainDocument.Package.Flush();
}
}
}
catch (OpenXmlPackageException oxmle)
{
throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, "Error while merging files. Document index {0}", pointer), oxmle);
}
catch (Exception e)
{
throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, "Error while merging files. Document index {0}", pointer), e);
}
finally
{
ret = mainStream.ToArray();
mainStream.Close();
mainStream.Dispose();
}
return (ret);
}
}
}
```
I hope this helps you.
|
247,668 |
<p>I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered.
I am using C# and .NET Framework 3.5sp1. Any help much appreciated.</p>
<p>Thanks,
Bryan</p>
<pre><code>public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = @"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
</code></pre>
|
[
{
"answer_id": 247679,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "<p>Most likely your problem is with the permissions. The user under which ASP.NET process runs is with very limited rights.</p>\n\n<p>So, either you have to set the proper permissions for that user, or run ASP.NET under some other user.</p>\n\n<p>This hides a security risks though, so you have to be very careful.</p>\n"
},
{
"answer_id": 247699,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": true,
"text": "<p>You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.<br>\nIn order to have cmd.exe run a program and then quit, you need to send it the syntax \"/c [command]\". Try running the same code with the line</p>\n\n<pre><code> si.StartInfo.Arguments = \"dir\";\n</code></pre>\n\n<p>replaced with </p>\n\n<pre><code> si.StartInfo.Arguments = \"/c dir\";\n</code></pre>\n\n<p>and see if it works.</p>\n"
},
{
"answer_id": 247709,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>This is madness! Use the System.IO namepace to create your file list from inside your C# program! It's very easy to do; although this technique also has authorization issues. </p>\n"
},
{
"answer_id": 247735,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "<p>Use System.Diagnostics.Process.</p>\n\n<p>Here is some ASP.NET code shelling out to run subversion commands on the command line.</p>\n\n<pre><code> ///////////////////////////////////////////////////////////////////////\n public static string run_svn(string args_without_password, string svn_username, string svn_password)\n {\n // run \"svn.exe\" and capture its output\n\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n string svn_path = Util.get_setting(\"SubversionPathToSvn\", \"svn\");\n p.StartInfo.FileName = svn_path;\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardError = true;\n\n args_without_password += \" --non-interactive\";\n Util.write_to_log (\"Subversion command:\" + svn_path + \" \" + args_without_password);\n\n string args_with_password = args_without_password;\n\n if (svn_username != \"\")\n {\n args_with_password += \" --username \";\n args_with_password += svn_username;\n args_with_password += \" --password \";\n args_with_password += svn_password;\n }\n\n p.StartInfo.Arguments = args_with_password;\n p.Start();\n string stdout = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n stdout += p.StandardOutput.ReadToEnd();\n\n string error = p.StandardError.ReadToEnd();\n\n if (error != \"\")\n {\n Util.write_to_log(error);\n Util.write_to_log(stdout);\n }\n\n if (error != \"\")\n {\n string msg = \"ERROR:\";\n msg += \"<div style='color:red; font-weight: bold; font-size: 10pt;'>\";\n msg += \"<br>Error executing svn.exe command from web server.\";\n msg += \"<br>\" + error;\n msg += \"<br>Arguments passed to svn.exe (except user/password):\" + args_without_password;\n if (error.Contains(\"File not found\"))\n {\n msg += \"<br><br>***** Has this file been deleted or renamed? See the following links:\";\n msg += \"<br><a href=http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html>http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html</a>\";\n msg += \"<br><a href=http://subversion.open.collab.net/articles/best-practices.html>http://subversion.open.collab.net/articles/best-practices.html</a>\";\n msg += \"</div>\";\n }\n return msg;\n }\n else\n {\n return stdout;\n }\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32474/"
] |
I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered.
I am using C# and .NET Framework 3.5sp1. Any help much appreciated.
Thanks,
Bryan
```
public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = @"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
```
|
You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line
```
si.StartInfo.Arguments = "dir";
```
replaced with
```
si.StartInfo.Arguments = "/c dir";
```
and see if it works.
|
247,678 |
<p>I have a Perl application that parses MediaWiki SQL tables and displays data from multiple wiki pages. I need to be able to re-create the absolute image path to display the images, eg: <code>.../f/fc/Herbs.jpg/300px-Herbs.jpg</code> </p>
<p>From MediaWiki Manual:</p>
<blockquote>
<p>Image_Authorisation: "the [image] path can be calculated easily from the file name and..." </p>
</blockquote>
<p>How is the path calculated? </p>
|
[
{
"answer_id": 248086,
"author": "JDrago",
"author_id": 29060,
"author_profile": "https://Stackoverflow.com/users/29060",
"pm_score": 3,
"selected": true,
"text": "<p>One possible way would be to calculate the MD5 signature of the file (or the file ID in a database), and then build/find the path based on that.</p>\n\n<p>For example, say we get an MD5 signature like \"1ff8a7b5dc7a7d1f0ed65aaa29c04b1e\"</p>\n\n<p>The path might look like \"/1f/f\" or \"/1f/ff/8a\"</p>\n\n<p>The reason is that you don't want to have all the files in 1 folder, and you want to have the ability to \"partition\" them across different servers, or a SAN or whatever in an equally-spread-out way.</p>\n\n<p>The MD5 signature is a string of 16 \"hex\" characters. So our example of \"/1f/ff/8a\" gives us 256*256*256 folders to store the files in. That ought to be enough for anybody :)</p>\n\n<hr>\n\n<p>Update, due to popular demand:</p>\n\n<p><strong>NOTE</strong> - I just realized we are talking specifically about how MediaWiki does it. This is <strong>not</strong> now MediaWiki does it, but another way in which it <strong>could have been done</strong>.</p>\n\n<p>By \"MD5 signature\" I mean doing something like this (code examples in Perl):</p>\n\n<pre><code>use Digest::MD5 'md5_hex';\nmy $sig = md5_hex( $file->id );\n</code></pre>\n\n<p>$sig is now 32 alpha-numeric characters long: \"1ff8a7b5dc7a7d1f0ed65aaa29c04b1e\"</p>\n\n<p>Then build a folder structure like this:</p>\n\n<pre><code>my $path = '/usr/local/media';\nmap { mkdir($path, 0666); $path .= \"/$_\" } $sig =~ m/^(..)(..)(..)/;\nopen my $ofh, '>', \"$path/$sig\"\n or die \"Cannot open '$path/$sig' for writing: $!\";\nprint $ofh \"File contents\";\nclose($ofh);\n</code></pre>\n\n<p>Folder structure looks like</p>\n\n<pre><code>/\n usr/\n local/\n media/\n 1f/\n f8/\n a7/\n 1ff8a7b5dc7a7d1f0ed65aaa29c04b1e\n</code></pre>\n"
},
{
"answer_id": 254972,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 4,
"selected": false,
"text": "<p>The accepted answer is incorrect:</p>\n\n<ul>\n<li>The MD5 sum of a string is 32 hex characters (128 bits), not 16</li>\n<li>The file path is calculated from the MD5 sum of the filename, not the contents of the file itself</li>\n<li>The first directory in the path is the first character, and the second directory is the first and second characters. The directory path is not a combination of the first 3 or 6 characters.</li>\n</ul>\n\n<p>The MD5 sum of 'Herbs.jpg' is fceaa5e7250d5036ad8cede5ce7d32d6. The first 2 characters are 'fc', giving the file path f/fc/, which is what is given in the example.</p>\n"
},
{
"answer_id": 255013,
"author": "gradbot",
"author_id": 17919,
"author_profile": "https://Stackoverflow.com/users/17919",
"pm_score": 2,
"selected": false,
"text": "<p>In PHP you can call the following function to get the URL. You may want to look at the php code to figure out how they calculate the path.</p>\n\n<pre><code>$url = wfFindFile(Title::makeTitle(NS_IMAGE, $fileName))->getURL();\n</code></pre>\n"
},
{
"answer_id": 35853041,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I created a small Bash script called <em>reorder.sh</em> which moves files from inside \"images\" to the specific sub folders:</p>\n\n<pre><code>#!/bin/bash\n\ncd /opt/mediawiki/mediawiki-cur/images\n\nfor i in `find -maxdepth 1 -type f ! -name .htaccess ! -name README ! -name reorder.sh -printf '%f\\n'`; do\n path1=$(echo -n $i | md5sum | head -c1) &&\n path2=$(echo -n $i | md5sum | head -c2) &&\n mkdir -p $path1/$path2/ &&\n mv $i $path1/$path2/;\ndone\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32477/"
] |
I have a Perl application that parses MediaWiki SQL tables and displays data from multiple wiki pages. I need to be able to re-create the absolute image path to display the images, eg: `.../f/fc/Herbs.jpg/300px-Herbs.jpg`
From MediaWiki Manual:
>
> Image\_Authorisation: "the [image] path can be calculated easily from the file name and..."
>
>
>
How is the path calculated?
|
One possible way would be to calculate the MD5 signature of the file (or the file ID in a database), and then build/find the path based on that.
For example, say we get an MD5 signature like "1ff8a7b5dc7a7d1f0ed65aaa29c04b1e"
The path might look like "/1f/f" or "/1f/ff/8a"
The reason is that you don't want to have all the files in 1 folder, and you want to have the ability to "partition" them across different servers, or a SAN or whatever in an equally-spread-out way.
The MD5 signature is a string of 16 "hex" characters. So our example of "/1f/ff/8a" gives us 256\*256\*256 folders to store the files in. That ought to be enough for anybody :)
---
Update, due to popular demand:
**NOTE** - I just realized we are talking specifically about how MediaWiki does it. This is **not** now MediaWiki does it, but another way in which it **could have been done**.
By "MD5 signature" I mean doing something like this (code examples in Perl):
```
use Digest::MD5 'md5_hex';
my $sig = md5_hex( $file->id );
```
$sig is now 32 alpha-numeric characters long: "1ff8a7b5dc7a7d1f0ed65aaa29c04b1e"
Then build a folder structure like this:
```
my $path = '/usr/local/media';
map { mkdir($path, 0666); $path .= "/$_" } $sig =~ m/^(..)(..)(..)/;
open my $ofh, '>', "$path/$sig"
or die "Cannot open '$path/$sig' for writing: $!";
print $ofh "File contents";
close($ofh);
```
Folder structure looks like
```
/
usr/
local/
media/
1f/
f8/
a7/
1ff8a7b5dc7a7d1f0ed65aaa29c04b1e
```
|
247,703 |
<p>Is there a (standardized) way to get the name of the current method using c++? </p>
<p>Using GNU GCC you can do this by using the macro <code>__FUNCTION__</code> and <code>__PRETTY_FUNCTION__</code> (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?</p>
|
[
{
"answer_id": 247707,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 0,
"selected": false,
"text": "<p>No, it is not supported by c++ standard.</p>\n"
},
{
"answer_id": 247721,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": true,
"text": "<p>The <code>__func__</code> identifier is part of the C99 standard and is in the C++0x draft.</p>\n\n<p>The identifier <code>__func__</code> is implicitly declared by the compiler as if the following were at the very start of each function body:</p>\n\n<pre><code>static const char __func__[] = \"function-name\";\n</code></pre>\n\n<p>where <code>function-name</code> is an implementation-defined string automatically provided by the compiler.</p>\n\n<p>Until support for those standards is available (or more widely available) you're stuck with compiler-specific gunk.</p>\n"
},
{
"answer_id": 247726,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 0,
"selected": false,
"text": "<p>It's called \"introspection\" and there is no such a thing in c++ standards. You should use an external library (boost I think supports it somehow).\nBut try figure out if the reason for using it is really a good one.</p>\n"
},
{
"answer_id": 247728,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<p>No...... but some things end up being non standard standards! </p>\n\n<p>see <a href=\"http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx</a> which outlines the ANSI standard stuff, and then microsofs which includes <em>FUNCTION</em></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23163/"
] |
Is there a (standardized) way to get the name of the current method using c++?
Using GNU GCC you can do this by using the macro `__FUNCTION__` and `__PRETTY_FUNCTION__` (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?
|
The `__func__` identifier is part of the C99 standard and is in the C++0x draft.
The identifier `__func__` is implicitly declared by the compiler as if the following were at the very start of each function body:
```
static const char __func__[] = "function-name";
```
where `function-name` is an implementation-defined string automatically provided by the compiler.
Until support for those standards is available (or more widely available) you're stuck with compiler-specific gunk.
|
247,706 |
<p>In Bash I'm executing a command and putting the result in a variable like this:</p>
<pre>export var=`svn ls`</pre>
<p>But if SVN fails for some reason--say it returns a non-zero error code--export still returns status code 0. How do I detect if the executed command fails?</p>
|
[
{
"answer_id": 247722,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 1,
"selected": false,
"text": "<p>I had similar problem, it can be done like this:</p>\n\n<pre>\nrm -f error_marker_file\nexport var=`svn ls || touch error_marker_file`\n\n[ -f error_marker_file ] && echo \"error in executing svn ls\"\n</pre>\n"
},
{
"answer_id": 247751,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "<pre><code>var=`svn ls`\nif [[ $? == 0 ]]\nthen\n export var\nelse\n unset var\nfi\n</code></pre>\n\n<p><code>$?</code> is the exit code of the last command executed, which is <code>svn ls</code> here.</p>\n\n<p>jmohr's solution is short and sweet. Adapted mildly,</p>\n\n<pre><code>var=`svn ls` && export var || unset var\n</code></pre>\n\n<p>would be approximately equivalent to the above (<code>export</code> of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use <code>unset</code> just to avoid <code>$var</code> possibly having a value even though it's not exported.</p>\n"
},
{
"answer_id": 247774,
"author": "jmohr",
"author_id": 16548,
"author_profile": "https://Stackoverflow.com/users/16548",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var=`svn ls` && export var\n</code></pre>\n"
},
{
"answer_id": 248223,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": -1,
"selected": false,
"text": "<pre><code>export FOO=$(your-command) || echo \"your-command failed\"\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] |
In Bash I'm executing a command and putting the result in a variable like this:
```
export var=`svn ls`
```
But if SVN fails for some reason--say it returns a non-zero error code--export still returns status code 0. How do I detect if the executed command fails?
|
```
var=`svn ls`
if [[ $? == 0 ]]
then
export var
else
unset var
fi
```
`$?` is the exit code of the last command executed, which is `svn ls` here.
jmohr's solution is short and sweet. Adapted mildly,
```
var=`svn ls` && export var || unset var
```
would be approximately equivalent to the above (`export` of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use `unset` just to avoid `$var` possibly having a value even though it's not exported.
|
247,708 |
<p>While the built-in analytics of MOSS2007 are nice to have - they are inadequate at the same time. Any ideas where I can look for a more comprehensive package? Am I missing something?</p>
<p>Thanks,
Carl</p>
|
[
{
"answer_id": 247722,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 1,
"selected": false,
"text": "<p>I had similar problem, it can be done like this:</p>\n\n<pre>\nrm -f error_marker_file\nexport var=`svn ls || touch error_marker_file`\n\n[ -f error_marker_file ] && echo \"error in executing svn ls\"\n</pre>\n"
},
{
"answer_id": 247751,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "<pre><code>var=`svn ls`\nif [[ $? == 0 ]]\nthen\n export var\nelse\n unset var\nfi\n</code></pre>\n\n<p><code>$?</code> is the exit code of the last command executed, which is <code>svn ls</code> here.</p>\n\n<p>jmohr's solution is short and sweet. Adapted mildly,</p>\n\n<pre><code>var=`svn ls` && export var || unset var\n</code></pre>\n\n<p>would be approximately equivalent to the above (<code>export</code> of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use <code>unset</code> just to avoid <code>$var</code> possibly having a value even though it's not exported.</p>\n"
},
{
"answer_id": 247774,
"author": "jmohr",
"author_id": 16548,
"author_profile": "https://Stackoverflow.com/users/16548",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var=`svn ls` && export var\n</code></pre>\n"
},
{
"answer_id": 248223,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": -1,
"selected": false,
"text": "<pre><code>export FOO=$(your-command) || echo \"your-command failed\"\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32480/"
] |
While the built-in analytics of MOSS2007 are nice to have - they are inadequate at the same time. Any ideas where I can look for a more comprehensive package? Am I missing something?
Thanks,
Carl
|
```
var=`svn ls`
if [[ $? == 0 ]]
then
export var
else
unset var
fi
```
`$?` is the exit code of the last command executed, which is `svn ls` here.
jmohr's solution is short and sweet. Adapted mildly,
```
var=`svn ls` && export var || unset var
```
would be approximately equivalent to the above (`export` of a valid identifier will never fail, unless you've done something horrible and run out of environment space). Take whatever you want -- I use `unset` just to avoid `$var` possibly having a value even though it's not exported.
|
247,718 |
<p>I am calling a SQL proc that has 3 OUTPUT params. After the call to the proc one of the params does not return a value when the other two do. Profiler shows that all 3 values are being returned.</p>
<p>The params are declared as follows in the proc...</p>
<pre><code>@UsrVariableID INT OUTPUT,
@OrganisationName NVARCHAR(256) OUTPUT,
@Visible bit OUTPUT
</code></pre>
<p>and the code that calls the proc is like this...</p>
<pre><code>cm.Parameters.AddWithValue("@OrganisationName", name);
cm.Parameters["@OrganisationName"].Direction = ParameterDirection.Output;
cm.Parameters.AddWithValue("@Visible", visible);
cm.Parameters["@Visible"].Direction = ParameterDirection.Output;
cm.ExecuteNonQuery();
name = cm.Parameters["@OrganisationName"].Value.ToString();
visible = bool.Parse(cm.Parameters["@Visible"].Value.ToString());
id = int.Parse(cm.Parameters["@UsrVariableID"].Value.ToString());
</code></pre>
<p>The param that fails is @OrganisationName.</p>
<p>I'm wondering if its because the param is of type string in the code but NVARCHAR in the proc.</p>
<p>Anyone got any ideas?</p>
|
[
{
"answer_id": 247755,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 2,
"selected": false,
"text": "<p>You could try declaring the parameters first (then set the values), and see if this make a difference.</p>\n\n<pre><code>cm.Parameters.Add[\"@OrganisationName\", SqlDbType.NVarChar, 256].Direction = ParameterDirection.Output\ncm.Parameters[\"@OrganisationName\"].Value = name\n</code></pre>\n\n<p>But to me there doesn't look like anything wrong with what you have posted.</p>\n\n<p>Incidently, if you shouldn't need the .Parse(.ToString()) you should only need to cast.</p>\n\n<pre><code>visible = bool.Parse(cm.Parameters[\"@Visible\"].Value.ToString());</code></pre>\n\n<p>becomes</p>\n\n<pre><code>visible = (bool)cm.Parameters[\"@Visible\"].Value;</code></pre>\n"
},
{
"answer_id": 247771,
"author": "chilltemp",
"author_id": 28736,
"author_profile": "https://Stackoverflow.com/users/28736",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure about MS SQL, but in .NET-->Oracle you need to specify the string buffer size.</p>\n\n<pre><code>cm.Parameters[\"@OrganisationName\"].Size = 256;\n</code></pre>\n"
},
{
"answer_id": 247822,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 4,
"selected": true,
"text": "<p>With output parameters that have variable length data types (nvarchar, varchar, etc), I've found that being more explicit leads to better results. In the case you've posted, a type is not specified on the C# side. I would probably change things to look something like the following:</p>\n\n<pre><code>SqlParameter theOrganizationNameParam = new SqlParameter( \"@OrganisationName\", SqlDbType.NVarChar, 256 );\ntheOrganizationNameParam.Direction = ParameterDirection.Output;\ncm.Parameters.Add( theOrganizationNameParam );\ncm.ExecuteNonQuery();\nname = theOrganizationNameParam.Value;\n</code></pre>\n\n<p>With this you can guarantee the output paratmer has the correct data type, and therefore can access the <strong>Value</strong> property without and exception being thrown.</p>\n\n<p>Hope this sheds some light.</p>\n"
},
{
"answer_id": 249606,
"author": "Simon Keep",
"author_id": 1127460,
"author_profile": "https://Stackoverflow.com/users/1127460",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks everyone, As suggested by Ady and Scott explicly declaring the type in the parameter declaration solved it.I picked Scotts answer as it was more concise.</p>\n"
},
{
"answer_id": 829395,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use ParameterDirection.InputOutput instead - this works</p>\n\n<p>See last comment in here for more info - <a href=\"http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic28087.aspx\" rel=\"nofollow noreferrer\">http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic28087.aspx</a></p>\n"
},
{
"answer_id": 829429,
"author": "User",
"author_id": 62830,
"author_profile": "https://Stackoverflow.com/users/62830",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, it's not about declaring the type.</p>\n\n<p>For output parameters with varying size, it is necessary to specify the parameter size.</p>\n\n<pre><code>cm.Parameters[\"@OrganisationName\"].Size = 50;\n</code></pre>\n\n<p>I've read somewhere there was a bug in implementation that raises an exception whenever the size is not specified for certain data types.</p>\n\n<p>The whole thing makes it badly suitable for returning parameters with unknown size, like nvarchar(max). I'd recommend return values via SELECT rather that via output parameters.</p>\n"
},
{
"answer_id": 3196596,
"author": "Eduardo",
"author_id": 180642,
"author_profile": "https://Stackoverflow.com/users/180642",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, i tried here a lot of things and the only thing that works is: you need to specify the SIZE of string.</p>\n\n<p>I have a storedprocedure that returns a string nvarchar(7) and at the C#.NET side i specified the size=255 and this is working for me to receive a string of 7 chars....</p>\n\n<p>I didn't like this because the code should be more expert...anyways...</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] |
I am calling a SQL proc that has 3 OUTPUT params. After the call to the proc one of the params does not return a value when the other two do. Profiler shows that all 3 values are being returned.
The params are declared as follows in the proc...
```
@UsrVariableID INT OUTPUT,
@OrganisationName NVARCHAR(256) OUTPUT,
@Visible bit OUTPUT
```
and the code that calls the proc is like this...
```
cm.Parameters.AddWithValue("@OrganisationName", name);
cm.Parameters["@OrganisationName"].Direction = ParameterDirection.Output;
cm.Parameters.AddWithValue("@Visible", visible);
cm.Parameters["@Visible"].Direction = ParameterDirection.Output;
cm.ExecuteNonQuery();
name = cm.Parameters["@OrganisationName"].Value.ToString();
visible = bool.Parse(cm.Parameters["@Visible"].Value.ToString());
id = int.Parse(cm.Parameters["@UsrVariableID"].Value.ToString());
```
The param that fails is @OrganisationName.
I'm wondering if its because the param is of type string in the code but NVARCHAR in the proc.
Anyone got any ideas?
|
With output parameters that have variable length data types (nvarchar, varchar, etc), I've found that being more explicit leads to better results. In the case you've posted, a type is not specified on the C# side. I would probably change things to look something like the following:
```
SqlParameter theOrganizationNameParam = new SqlParameter( "@OrganisationName", SqlDbType.NVarChar, 256 );
theOrganizationNameParam.Direction = ParameterDirection.Output;
cm.Parameters.Add( theOrganizationNameParam );
cm.ExecuteNonQuery();
name = theOrganizationNameParam.Value;
```
With this you can guarantee the output paratmer has the correct data type, and therefore can access the **Value** property without and exception being thrown.
Hope this sheds some light.
|
247,724 |
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
|
[
{
"answer_id": 247730,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 0,
"selected": false,
"text": "<p>os.system(\"open file.xls\")</p>\n"
},
{
"answer_id": 247740,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 3,
"selected": false,
"text": "<p>or </p>\n\n<pre><code>os.system(\"start excel.exe <path/to/file>\")\n</code></pre>\n\n<p>(presuming it's in the path, and you're on windows)</p>\n\n<p>and also on Windows, just <code>start <filename></code> works, too - if it's an associated extension already (as xls would be)</p>\n"
},
{
"answer_id": 247761,
"author": "crftr",
"author_id": 18213,
"author_profile": "https://Stackoverflow.com/users/18213",
"pm_score": 3,
"selected": false,
"text": "<p>I like <code>popen2</code> for the ability to monitor the process.</p>\n\n<pre><code>excelProcess = popen2.Popen4(\"start excel %s\" % (excelFile))\nstatus = excelProcess.wait()\n</code></pre>\n\n<p><a href=\"https://docs.python.org/2/library/popen2.html\" rel=\"nofollow noreferrer\">https://docs.python.org/2/library/popen2.html</a></p>\n\n<p><strong>EDIT</strong>: be aware that calling <code>wait()</code> will block until the process returns. Depending on your script, this may not be your desired behavior.</p>\n"
},
{
"answer_id": 248080,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 5,
"selected": true,
"text": "<p>While the <code>Popen</code> answers are reasonable for the general case, I would recommend <code>win32api</code> for this specific case, if you want to do something useful with it:</p>\n\n<p>It goes something like this:</p>\n\n<pre><code>from win32com.client import Dispatch\nxl = Dispatch('Excel.Application')\nwb = xl.Workbooks.Open('C:\\\\Documents and Settings\\\\GradeBook.xls')\nxl.Visible = True # optional: if you want to see the spreadsheet\n</code></pre>\n\n<p>Taken from <a href=\"https://mail.python.org/pipermail/python-list/2005-June/315330.html\" rel=\"nofollow noreferrer\">a mailing list post</a> but there are plenty of examples around.</p>\n"
},
{
"answer_id": 249571,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>subprocess</strong> module intends to replace several other, older modules and functions, such as:</p>\n\n<ul>\n<li>os.system</li>\n<li>os.spawn*</li>\n<li>os.popen*</li>\n<li>popen2.*</li>\n<li>commands.*</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>import subprocess\n\nprocess_one = subprocess.Popen(['gqview', '/home/toto/my_images'])\n\nprint process_one.pid\n</code></pre>\n"
},
{
"answer_id": 6351029,
"author": "codedude",
"author_id": 709115,
"author_profile": "https://Stackoverflow.com/users/709115",
"pm_score": 2,
"selected": false,
"text": "<p>As others have stated, I would suggest os.system. In case anyone is looking for a Mac-compatible solution, here is an example:</p>\n\n<pre><code>import os\nos.system(\"open /Applications/Safari.app\")\n</code></pre>\n"
},
{
"answer_id": 54100051,
"author": "microbenny",
"author_id": 2886382,
"author_profile": "https://Stackoverflow.com/users/2886382",
"pm_score": 0,
"selected": false,
"text": "<p>I like <code>os.startfile(\"path to file\")</code> as it opens the file as if you've double clicked to open.</p>\n\n<p>I found that with <code>os.system(\"start excel filename\")</code> it opened it like a file opened from the web and you had to enable editing.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
|
While the `Popen` answers are reasonable for the general case, I would recommend `win32api` for this specific case, if you want to do something useful with it:
It goes something like this:
```
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls')
xl.Visible = True # optional: if you want to see the spreadsheet
```
Taken from [a mailing list post](https://mail.python.org/pipermail/python-list/2005-June/315330.html) but there are plenty of examples around.
|
247,738 |
<p>If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?</p>
<p>e.g.</p>
<pre><code>vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
</code></pre>
|
[
{
"answer_id": 247744,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 2,
"selected": false,
"text": "<p>yes. </p>\n\n<p>it should alway be contiguous</p>\n"
},
{
"answer_id": 247746,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3\" rel=\"noreferrer\">Yes it's contiguous</a></p>\n"
},
{
"answer_id": 247759,
"author": "Adam Holmberg",
"author_id": 20688,
"author_profile": "https://Stackoverflow.com/users/20688",
"pm_score": 4,
"selected": false,
"text": "<p>Storage is always contiguous, but it may move as the vector's capacity is changed. </p>\n\n<p>If you had a pointer, reference, or iterator on element zero (or any element) before a capacity-changing operation, it is invalidated and must be reassigned.</p>\n"
},
{
"answer_id": 247762,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 2,
"selected": false,
"text": "<p><code>std::vector</code> guarantees that the items are stored in a contiguous array, and is therefore the preferred replacement of arrays and can also be used to interface with platform-dependent low-level code (like Win32 API calls). To get a pointer to the array use:</p>\n\n<pre><code>&myVector.front();\n</code></pre>\n"
},
{
"answer_id": 247764,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Yes, that is a valid assumption (*).</strong></p>\n\n<p>From the C++03 standard (23.2.4.1):</p>\n\n<blockquote>\n <p>The elements of a vector are stored\n contiguously, meaning that if v is a\n vector where T is some\n type other than bool, then it obeys\n the identity &v[n] == &v[0] + n for\n all 0 <= n < v.size().</p>\n</blockquote>\n\n<p>(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.</p>\n"
},
{
"answer_id": 247902,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "<p>The C++03 standard added wording to make it clear that vector elements must be contiguous.</p>\n\n<p>C++03 23.2.4 Paragraph 1 contains the following language which is <em>not</em> in the C++98 standard document:</p>\n\n<blockquote>\n <p>The elements of a <code>vector</code> are stored\n contiguously, meaning that if <code>v</code> is a\n <code>vector<T, Allocator></code> where <code>T</code> is\n some type other than <code>bool</code>, then it\n obeys the identity <code>&v[n] == &v[0] +\n n</code> for all <code>0 <= n < v.size()</code>.</p>\n</blockquote>\n\n<p>Herb Sutter talks about this change in one of his blog entries, <a href=\"http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/\" rel=\"noreferrer\">Cringe not: Vectors are guaranteed to be contiguous</a>:</p>\n\n<blockquote>\n <p>... contiguity is in fact part of the\n vector abstraction. It’s so important,\n in fact, that when it was discovered\n that the C++98 standard didn’t\n completely guarantee contiguity, the\n C++03 standard was amended to\n explicitly add the guarantee.</p>\n</blockquote>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?
e.g.
```
vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
```
|
**Yes, that is a valid assumption (\*).**
From the C++03 standard (23.2.4.1):
>
> The elements of a vector are stored
> contiguously, meaning that if v is a
> vector where T is some
> type other than bool, then it obeys
> the identity &v[n] == &v[0] + n for
> all 0 <= n < v.size().
>
>
>
(\*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.
|
247,743 |
<p>I already know: "Don't use css expressions!" My question is not about whether I should be using an expression or if there is an alternative; my question is simply: <strong>Can I get a css expression to only be evaluated in versions of IE prior to version 7 without using conditional comments?</strong></p>
<p>I occasionally use an underscore hack to hide a rule from IE7 but IE7 seems to evaluate expressions anyway. For example, <code>_width:700px;</code> is ignored by IE7 but <code>_width:expression('700px');</code> is still evaluated.</p>
<p>I know that someone will try to tell me to just use a conditional comment to include the rule, but I am looking for a way to do this without placing a single style rule into a separate file.</p>
<p>A note for those of you who still don't want to let it go: I've chosen to use a css expression, but I didn't do so lightly. I understand the implications and I am using an expression that only evaluates once. Stop worrying about my bad decisions and just answer the question already... ;-)</p>
|
[
{
"answer_id": 247763,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "<p>You can try <a href=\"http://rafael.adm.br/css_browser_selector/\" rel=\"nofollow noreferrer\">Rafael Lima's CSS Selector</a>. It uses Javascript, but you can do things like:</p>\n\n<pre><code>.ie6 .myClass {}\n.ie7 .myClass {}\n.ie .myClass{}\n</code></pre>\n"
},
{
"answer_id": 247855,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 1,
"selected": false,
"text": "<p>I used to use !important to make non-ie browsers use a different style but then IE7 started supporting it. What I have found is that IE7 will apply a style marked !ie-only (or anything not !important) and other browsers will ignore the style as they don't recognise that. </p>\n\n<p>If you need three different styles this might work but not great is you want to adhere to standards though. <em>(normally I don't try the mix of !important and !ie-only and just have !ie-only.)</em></p>\n\n<pre><code>#myDiv {\n height: 3.0em !important; /* non-ie */\n height: 2.6em !ie-only; /* ie7 */\n height: 2.4em; /* ie < 7 */\n}\n</code></pre>\n"
},
{
"answer_id": 247907,
"author": "alexp206",
"author_id": 666,
"author_profile": "https://Stackoverflow.com/users/666",
"pm_score": 0,
"selected": false,
"text": "<p>This answer may be what you are looking for: \n<a href=\"https://stackoverflow.com/questions/213309/in-line-css-ie-hack#213458\">In-line CSS IE hack</a></p>\n"
},
{
"answer_id": 248021,
"author": "adgoudz",
"author_id": 30527,
"author_profile": "https://Stackoverflow.com/users/30527",
"pm_score": 3,
"selected": true,
"text": "<p>I always use the star \"hack\" to target IE6 specifically, but it does require your browser to be in <strong>standards compliant</strong> mode (see below).</p>\n\n<pre><code>/* IE6 only */ \n* html .myClass {\n width: 500px;\n}\n</code></pre>\n\n<p>I like it because it doesn't rely on parsing inconsistencies in browsers and it validates according to <a href=\"http://jigsaw.w3.org/css-validator/#validate_by_input\" rel=\"nofollow noreferrer\">W3C</a>. </p>\n\n<p>As for being in standards compliant mode, you should always add a valid DOCTYPE to your pages as it results in fewer CSS bugs and browser idiosyncrasies. For an explanation of quirksmode and standards compliant mode, check out this <a href=\"http://www.quirksmode.org/css/quirksmode.html\" rel=\"nofollow noreferrer\">article</a>.</p>\n\n<p>You can use this example below to play around with expressions in each browser. I tested it in FF, IE6, and IE7 and it worked as expected. I only wish that SO had syntax highlighting to recognize CSS expressions and mark them as red so you can be reminded that they are evil. Might I ask why you are deciding to use CSS expressions in the first place? A lot of people try to use them to achieve min-width in IE6 but that's not the right solution. If that's the problem you're trying to solve, I've written up <a href=\"https://stackoverflow.com/questions/191429/css-two-50-fluid-columns-not-respecting-min-width#230152\">an answer in a separate question</a> demonstrating a valid CSS solution for min-width in IE6.</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n<head>\n <style type=\"text/css\">\n\n .ie6 {\n display: none;\n }\n\n * html .ie6 {\n display: expression(\"block\");\n }\n\n * html .ie7 {\n display: expression(\"none\");\n }\n\n </style>\n</head>\n<body>\n<div class=\"ie6\">\n This is IE6\n</div>\n<div class=\"ie7\">\n This is Firefox or IE7+\n</div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 7358842,
"author": "chris5marsh",
"author_id": 869117,
"author_profile": "https://Stackoverflow.com/users/869117",
"pm_score": 2,
"selected": false,
"text": "<p>You don't have to use conditional comments to add a new file. You could easily add a conditional comment to add a class to the <code>body</code> tag, as follows:</p>\n\n<pre><code><!--[if lte IE 7]>\n<body class=\"ie7\">\n<![endif]-->\n<!--[if gt IE 7]>-->\n<body>\n<!--<![endif]-->\n</code></pre>\n\n<p>Then in your CSS you can simply define a different style for IE7 on any element you like:</p>\n\n<pre><code>#content {\n width:720px;\n}\n\n.ie7 #content {\n width:700px;\n}\n</code></pre>\n\n<p>You still load the same stylesheet, but you can style elements based on their browser.</p>\n\n<p>You could even extend this to have differnt styles for IE6, 7 and non-IE browsers.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5628/"
] |
I already know: "Don't use css expressions!" My question is not about whether I should be using an expression or if there is an alternative; my question is simply: **Can I get a css expression to only be evaluated in versions of IE prior to version 7 without using conditional comments?**
I occasionally use an underscore hack to hide a rule from IE7 but IE7 seems to evaluate expressions anyway. For example, `_width:700px;` is ignored by IE7 but `_width:expression('700px');` is still evaluated.
I know that someone will try to tell me to just use a conditional comment to include the rule, but I am looking for a way to do this without placing a single style rule into a separate file.
A note for those of you who still don't want to let it go: I've chosen to use a css expression, but I didn't do so lightly. I understand the implications and I am using an expression that only evaluates once. Stop worrying about my bad decisions and just answer the question already... ;-)
|
I always use the star "hack" to target IE6 specifically, but it does require your browser to be in **standards compliant** mode (see below).
```
/* IE6 only */
* html .myClass {
width: 500px;
}
```
I like it because it doesn't rely on parsing inconsistencies in browsers and it validates according to [W3C](http://jigsaw.w3.org/css-validator/#validate_by_input).
As for being in standards compliant mode, you should always add a valid DOCTYPE to your pages as it results in fewer CSS bugs and browser idiosyncrasies. For an explanation of quirksmode and standards compliant mode, check out this [article](http://www.quirksmode.org/css/quirksmode.html).
You can use this example below to play around with expressions in each browser. I tested it in FF, IE6, and IE7 and it worked as expected. I only wish that SO had syntax highlighting to recognize CSS expressions and mark them as red so you can be reminded that they are evil. Might I ask why you are deciding to use CSS expressions in the first place? A lot of people try to use them to achieve min-width in IE6 but that's not the right solution. If that's the problem you're trying to solve, I've written up [an answer in a separate question](https://stackoverflow.com/questions/191429/css-two-50-fluid-columns-not-respecting-min-width#230152) demonstrating a valid CSS solution for min-width in IE6.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.ie6 {
display: none;
}
* html .ie6 {
display: expression("block");
}
* html .ie7 {
display: expression("none");
}
</style>
</head>
<body>
<div class="ie6">
This is IE6
</div>
<div class="ie7">
This is Firefox or IE7+
</div>
</body>
</html>
```
|
247,768 |
<p>I am using JSF frontend for a page where an image is uploaded or deleted. Clicking on the upload or delete button causes a postback and the page to reload with the updated status. This however, resets the scroll position of the page. How should I go about retaining the scrollback of this page on the postback actions.</p>
|
[
{
"answer_id": 247802,
"author": "shadit",
"author_id": 9925,
"author_profile": "https://Stackoverflow.com/users/9925",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Apache MyFaces Tomahawk, you can set the parameter AUTOSCROLL then make sure AutoScrollPhaseListener is enabled.</p>\n\n<p>I'm not sure this functionality is specified by JSF, but instead is something extra implemented by Apache MyFaces Tomahawk.</p>\n\n<p>Also, be aware that prior to version 1.1.6, there is a cross-site scripting vulnerability in the AUTOSCROLL implementation.</p>\n"
},
{
"answer_id": 3717736,
"author": "Fede",
"author_id": 318583,
"author_profile": "https://Stackoverflow.com/users/318583",
"pm_score": 1,
"selected": false,
"text": "<p>You can do that with an actionListener. For example, in your page (page.jsf for example):</p>\n\n<pre><code><f:view> \n <h:form>\n <h:commandLink actionListener=\"#{bean.method}\">\n <h:outputText value=\"Submit\" />\n <f:param name=\"anchor\" value=\"image\" />\n </h:commandLink>\n </h:form>\n <div id='result'>\n <h1><a name='image'>Image</a></h1> \n </div>\n</f:view>\n</code></pre>\n\n<p>And the managed bean looks like:</p>\n\n<pre><code>public class Bean {\n\n public void method(ActionEvent actionEvent) {\n\n // Get parameter\n String ancla = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(\"anchor\");\n\n try {\n FacesContext.getCurrentInstance().getExternalContext().redirect(\"page.jsf#\" + anchor);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 23684416,
"author": "mehmet cinar",
"author_id": 1891090,
"author_profile": "https://Stackoverflow.com/users/1891090",
"pm_score": 0,
"selected": false,
"text": "<p>you can use jquery.. Using cookies..\nin ready function</p>\n\n<pre><code> $(function(){\n\n //set window scroll position if cookie is set\n window.scroll(0,getCookie('myCookie'));\n //unset cookie after setting scroll position\n deleteCookie('myCookie'); \n\n //make this class objects keep page scroll position\n jQuery(window).unload(function() {\n setCookie('myCookie', getPageScroll());\n });\n //-------------------\n\n\n\n });\n</code></pre>\n\n<p>after ready function add this functions..</p>\n\n<pre><code>function setCookie(name,value) {\n\n var date = new Date();\n date.setTime(date.getTime()+(10*1000));\n var expires = \"; expires=\"+date.toGMTString();\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n}\n\nfunction getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n}\n\nfunction deleteCookie(name) {\n setCookie(name,\"\",-1);\n}\n</code></pre>\n\n<p>i wish this help you..</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using JSF frontend for a page where an image is uploaded or deleted. Clicking on the upload or delete button causes a postback and the page to reload with the updated status. This however, resets the scroll position of the page. How should I go about retaining the scrollback of this page on the postback actions.
|
You can do that with an actionListener. For example, in your page (page.jsf for example):
```
<f:view>
<h:form>
<h:commandLink actionListener="#{bean.method}">
<h:outputText value="Submit" />
<f:param name="anchor" value="image" />
</h:commandLink>
</h:form>
<div id='result'>
<h1><a name='image'>Image</a></h1>
</div>
</f:view>
```
And the managed bean looks like:
```
public class Bean {
public void method(ActionEvent actionEvent) {
// Get parameter
String ancla = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("anchor");
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("page.jsf#" + anchor);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Hope this helps
|
247,770 |
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p>
<p>How do I retrieve a module's path in python?</p>
|
[
{
"answer_id": 248066,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 5,
"selected": false,
"text": "<p>This was trivial.</p>\n\n<p>Each module has a <code>__file__</code> variable that shows its relative path from where you are right now.</p>\n\n<p>Therefore, getting a directory for the module to notify it is simple as:</p>\n\n<pre><code>os.path.dirname(__file__)\n</code></pre>\n"
},
{
"answer_id": 248862,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 11,
"selected": true,
"text": "<pre><code>import a_module\nprint(a_module.__file__)\n</code></pre>\n\n<p>Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:</p>\n\n<pre><code>import os\npath = os.path.abspath(a_module.__file__)\n</code></pre>\n\n<p>You can also try:</p>\n\n<pre><code>path = os.path.dirname(a_module.__file__)\n</code></pre>\n\n<p>To get the module's directory.</p>\n"
},
{
"answer_id": 4431672,
"author": "vinoth",
"author_id": 540842,
"author_profile": "https://Stackoverflow.com/users/540842",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import os\npath = os.path.abspath(__file__)\ndir_path = os.path.dirname(path)\n</code></pre>\n"
},
{
"answer_id": 6416114,
"author": "mcstrother",
"author_id": 222515,
"author_profile": "https://Stackoverflow.com/users/222515",
"pm_score": 6,
"selected": false,
"text": "<p>As the other answers have said, the best way to do this is with <code>__file__</code> (demonstrated again below). However, there is an important caveat, which is that <code>__file__</code> does NOT exist if you are running the module on its own (i.e. as <code>__main__</code>).</p>\n\n<p>For example, say you have two files (both of which are on your PYTHONPATH):</p>\n\n<pre><code>#/path1/foo.py\nimport bar\nprint(bar.__file__)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>#/path2/bar.py\nimport os\nprint(os.getcwd())\nprint(__file__)\n</code></pre>\n\n<p>Running foo.py will give the output:</p>\n\n<pre><code>/path1 # \"import bar\" causes the line \"print(os.getcwd())\" to run\n/path2/bar.py # then \"print(__file__)\" runs\n/path2/bar.py # then the import statement finishes and \"print(bar.__file__)\" runs\n</code></pre>\n\n<p>HOWEVER if you try to run bar.py on its own, you will get:</p>\n\n<pre><code>/path2 # \"print(os.getcwd())\" still works fine\nTraceback (most recent call last): # but __file__ doesn't exist if bar.py is running as main\n File \"/path2/bar.py\", line 3, in <module>\n print(__file__)\nNameError: name '__file__' is not defined \n</code></pre>\n\n<p>Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.</p>\n"
},
{
"answer_id": 9759993,
"author": "uri",
"author_id": 1277124,
"author_profile": "https://Stackoverflow.com/users/1277124",
"pm_score": 3,
"selected": false,
"text": "<p>So I spent a fair amount of time trying to do this with py2exe\nThe problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system's path.</p>\n\n<p>Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:</p>\n\n<pre><code>import os,sys\nif hasattr(sys,'frozen'): # only when running in py2exe this exists\n base = sys.prefix\nelse: # otherwise this is a regular python script\n base = os.path.dirname(os.path.realpath(__file__))\n</code></pre>\n"
},
{
"answer_id": 12154601,
"author": "Tomas Tomecek",
"author_id": 909579,
"author_profile": "https://Stackoverflow.com/users/909579",
"pm_score": 8,
"selected": false,
"text": "<p>There is <code>inspect</code> module in python.</p>\n\n<h2><a href=\"http://docs.python.org/library/inspect.html\">Official documentation</a></h2>\n\n<blockquote>\n <p>The inspect module provides several useful functions to help get\n information about live objects such as modules, classes, methods,\n functions, tracebacks, frame objects, and code objects. For example,\n it can help you examine the contents of a class, retrieve the source\n code of a method, extract and format the argument list for a function,\n or get all the information you need to display a detailed traceback.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>>>> import os\n>>> import inspect\n>>> inspect.getfile(os)\n'/usr/lib64/python2.7/os.pyc'\n>>> inspect.getfile(inspect)\n'/usr/lib64/python2.7/inspect.pyc'\n>>> os.path.dirname(inspect.getfile(inspect))\n'/usr/lib64/python2.7'\n</code></pre>\n"
},
{
"answer_id": 16826913,
"author": "jpgeek",
"author_id": 454246,
"author_profile": "https://Stackoverflow.com/users/454246",
"pm_score": 6,
"selected": false,
"text": "<p>I will try tackling a few variations on this question as well:</p>\n<ol>\n<li>finding the path of the called script</li>\n<li>finding the path of the currently executing script</li>\n<li>finding the directory of the called script</li>\n</ol>\n<p>(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)</p>\n<h2>Caveats of Using <code>__file__</code></h2>\n<p>For a module that you have imported:</p>\n<pre><code>import something\nsomething.__file__ \n</code></pre>\n<p>will return the <strong>absolute</strong> path of the module. However, given the folowing script foo.py:</p>\n<pre><code>#foo.py\nprint '__file__', __file__\n</code></pre>\n<p>Calling it with 'python foo.py' Will return simply 'foo.py'. If you add a shebang:</p>\n<pre><code>#!/usr/bin/python \n#foo.py\nprint '__file__', __file__\n</code></pre>\n<p>and call it using ./foo.py, it will return './foo.py'. Calling it from a different directory, (eg put foo.py in directory bar), then calling either</p>\n<pre><code>python bar/foo.py\n</code></pre>\n<p>or adding a shebang and executing the file directly:</p>\n<pre><code>bar/foo.py\n</code></pre>\n<p>will return 'bar/foo.py' (the <strong>relative</strong> path).</p>\n<h2>Finding the directory</h2>\n<p>Now going from there to get the directory, <code>os.path.dirname(__file__)</code> can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex.</p>\n<pre><code># foo.py\nimport os\nprint '__file__ is:', __file__\nprint 'os.path.dirname(__file__) is:', os.path.dirname(__file__)\n</code></pre>\n<p>will output:</p>\n<pre><code>__file__ is: foo.py\nos.path.dirname(__file__) is: \n</code></pre>\n<p>In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current <strong>file</strong> (as opposed to the <strong>file</strong> of an imported module). To get around this, you can wrap it in a call to abspath:</p>\n<pre><code># foo.py\nimport os\nprint 'os.path.abspath(__file__) is:', os.path.abspath(__file__)\nprint 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__))\n</code></pre>\n<p>which outputs something like:</p>\n<pre><code>os.path.abspath(__file__) is: /home/user/bar/foo.py\nos.path.dirname(os.path.abspath(__file__)) is: /home/user/bar\n</code></pre>\n<p>Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file_import_testing_link pointing to file_import_testing.py, with the following content:</p>\n<pre><code>import os\nprint 'abspath(__file__)',os.path.abspath(__file__)\nprint 'realpath(__file__)',os.path.realpath(__file__)\n</code></pre>\n<p>executing will print absolute paths something like:</p>\n<pre><code>abspath(__file__) /home/user/file_test_link\nrealpath(__file__) /home/user/file_test.py\n</code></pre>\n<p>file_import_testing_link -> file_import_testing.py</p>\n<h2>Using inspect</h2>\n<p>@SummerBreeze mentions using the <a href=\"http://docs.python.org/2/library/inspect.html\" rel=\"noreferrer\">inspect</a> module.</p>\n<p>This seems to work well, and is quite concise, for imported modules:</p>\n<pre><code>import os\nimport inspect\nprint 'inspect.getfile(os) is:', inspect.getfile(os)\n</code></pre>\n<p>obediently returns the absolute path. For finding the path of the currently executing script:</p>\n<pre><code>inspect.getfile(inspect.currentframe())\n</code></pre>\n<p>(thanks @jbochi)</p>\n<pre><code>inspect.getabsfile(inspect.currentframe()) \n</code></pre>\n<p>gives the absolute path of currently executing script (thanks @Sadman_Sakib).</p>\n"
},
{
"answer_id": 25319974,
"author": "MestreLion",
"author_id": 624066,
"author_profile": "https://Stackoverflow.com/users/624066",
"pm_score": 2,
"selected": false,
"text": "<p>If the only caveat of using <code>__file__</code> is when current, relative directory is blank (ie, when running as a script from the same directory where the script is), then a trivial solution is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os.path\nmydir = os.path.dirname(__file__) or '.'\nfull = os.path.abspath(mydir)\nprint __file__, mydir, full\n</code></pre>\n\n<p>And the result:</p>\n\n<pre><code>$ python teste.py \nteste.py . /home/user/work/teste\n</code></pre>\n\n<p>The trick is in <code>or '.'</code> after the <code>dirname()</code> call. It sets the dir as <code>.</code>, which means <em>current directory</em> and is a valid directory for any path-related function.</p>\n\n<p>Thus, using <code>abspath()</code> is not truly needed. But if you use it anyway, the trick is not needed: <code>abspath()</code> accepts blank paths and properly interprets it as the current directory.</p>\n"
},
{
"answer_id": 25344804,
"author": "Lukas Greblikas",
"author_id": 1353644,
"author_profile": "https://Stackoverflow.com/users/1353644",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import module\nprint module.__path__\n</code></pre>\n\n<blockquote>\n <p>Packages support one more special attribute, <code>__path__</code>. This is\n initialized to be a list containing the name of the directory holding\n the package’s <code>__init__.py</code> before the code in that file is executed.\n This variable can be modified; doing so affects future searches for\n modules and subpackages contained in the package.</p>\n \n <p>While this feature is not often needed, it can be used to extend the\n set of modules found in a package.</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 27934408,
"author": "Robin Randall",
"author_id": 2426712,
"author_profile": "https://Stackoverflow.com/users/2426712",
"pm_score": 1,
"selected": false,
"text": "<p>If you wish to do this dynamically in a \"program\" try this code:<br>\nMy point is, you may not know the exact name of the module to \"hardcode\" it.\nIt may be selected from a list or may not be currently running to use __file__.</p>\n\n<p>(I know, it will not work in Python 3)</p>\n\n<pre><code>global modpath\nmodname = 'os' #This can be any module name on the fly\n#Create a file called \"modname.py\"\nf=open(\"modname.py\",\"w\")\nf.write(\"import \"+modname+\"\\n\")\nf.write(\"modpath = \"+modname+\"\\n\")\nf.close()\n#Call the file with execfile()\nexecfile('modname.py')\nprint modpath\n<module 'os' from 'C:\\Python27\\lib\\os.pyc'>\n</code></pre>\n\n<p>I tried to get rid of the \"global\" issue but found cases where it did not work\nI think \"execfile()\" can be emulated in Python 3\nSince this is in a program, it can easily be put in a method or module for reuse.</p>\n"
},
{
"answer_id": 28976381,
"author": "PlasmaBinturong",
"author_id": 4614641,
"author_profile": "https://Stackoverflow.com/users/4614641",
"pm_score": 6,
"selected": false,
"text": "<p>I don't get why no one is talking about this, but to me the simplest solution is using <strong>imp.find_module(\"modulename\")</strong> (documentation <a href=\"https://docs.python.org/2/library/imp.html?highlight=import#module-imp\">here</a>):</p>\n\n<pre><code>import imp\nimp.find_module(\"os\")\n</code></pre>\n\n<p>It gives a tuple with the path in second position:</p>\n\n<pre><code>(<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,\n'/usr/lib/python2.7/os.py',\n('.py', 'U', 1))\n</code></pre>\n\n<p>The advantage of this method over the \"inspect\" one is that you don't need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example.</p>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>In python3, <code>importlib</code> module should do:</p>\n\n<p>Doc of <code>importlib.util.find_spec</code>:</p>\n\n<blockquote>\n <p>Return the spec for the specified module.</p>\n \n <p>First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].<strong>spec</strong> is returned. If that happens to be\n set to None, then ValueError is raised. If the module is not in\n sys.modules, then sys.meta_path is searched for a suitable spec with the\n value of 'path' given to the finders. None is returned if no spec could\n be found.</p>\n \n <p>If the name is for submodule (contains a dot), the parent module is\n automatically imported.</p>\n \n <p>The name and package arguments work the same as importlib.import_module().\n In other words, relative module names (with leading dots) work.</p>\n</blockquote>\n"
},
{
"answer_id": 30192316,
"author": "Al Conrad",
"author_id": 3457624,
"author_profile": "https://Stackoverflow.com/users/3457624",
"pm_score": 1,
"selected": false,
"text": "<p>From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.</p>\n\n<pre><code>some_dir/\n maincli.py\n top_package/\n __init__.py\n level_one_a/\n __init__.py\n my_lib_a.py\n level_two/\n __init__.py\n hello_world.py\n level_one_b/\n __init__.py\n my_lib_b.py\n</code></pre>\n\n<p>So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.py:</p>\n\n<pre><code>import sys\nimport os\nimport imp\n\n\nclass ConfigurationException(Exception):\n pass\n\n\n# inside of my_lib_a.py\ndef get_maincli_path():\n maincli_path = os.path.abspath(imp.find_module('maincli')[1])\n # top_package = __package__.split('.')[0]\n # mod = sys.modules.get(top_package)\n # modfile = mod.__file__\n # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))\n # maincli_path = os.path.join(pkg_in_dir, 'maincli.py')\n\n if not os.path.exists(maincli_path):\n err_msg = 'This script expects that \"maincli.py\" be installed to the '\\\n 'same directory: \"{0}\"'.format(maincli_path)\n raise ConfigurationException(err_msg)\n\n return maincli_path\n</code></pre>\n\n<p>Based on posting by PlasmaBinturong I modified the code.</p>\n"
},
{
"answer_id": 32026782,
"author": "Jossef Harush Kadouri",
"author_id": 3191896,
"author_profile": "https://Stackoverflow.com/users/3191896",
"pm_score": 4,
"selected": false,
"text": "<h2>Command Line Utility</h2>\n\n<p>You can tweak it to a command line utility,</p>\n\n<pre><code>python-which <package name>\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/pjVSO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/pjVSO.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Create <code>/usr/local/bin/python-which</code></p>\n\n<pre><code>#!/usr/bin/env python\n\nimport importlib\nimport os\nimport sys\n\nargs = sys.argv[1:]\nif len(args) > 0:\n module = importlib.import_module(args[0])\n print os.path.dirname(module.__file__)\n</code></pre>\n\n<p>Make it executable </p>\n\n<pre><code>sudo chmod +x /usr/local/bin/python-which\n</code></pre>\n"
},
{
"answer_id": 49968449,
"author": "Jeyekomon",
"author_id": 1232660,
"author_profile": "https://Stackoverflow.com/users/1232660",
"pm_score": 2,
"selected": false,
"text": "<p>I'd like to contribute with one common scenario (in Python 3) and explore a few approaches to it.</p>\n\n<p>The built-in function <a href=\"https://docs.python.org/3/library/functions.html#open\" rel=\"nofollow noreferrer\">open()</a> accepts either relative or absolute path as its first argument. The relative path is treated as <em>relative to the current working directory</em> though so it is recommended to pass the absolute path to the file.</p>\n\n<p>Simply said, if you run a script file with the following code, it is <strong>not</strong> guaranteed that the <code>example.txt</code> file will be created in the same directory where the script file is located:</p>\n\n<pre><code>with open('example.txt', 'w'):\n pass\n</code></pre>\n\n<p>To fix this code we need to get the path to the script and make it absolute. To ensure the path to be absolute we simply use the <a href=\"https://docs.python.org/3/library/os.path.html#os.path.realpath\" rel=\"nofollow noreferrer\">os.path.realpath()</a> function. To get the path to the script there are several common functions that return various path results:</p>\n\n<ul>\n<li><code>os.getcwd()</code></li>\n<li><code>os.path.realpath('example.txt')</code></li>\n<li><code>sys.argv[0]</code></li>\n<li><code>__file__</code></li>\n</ul>\n\n<p>Both functions <a href=\"https://docs.python.org/3/library/os.html#os.getcwd\" rel=\"nofollow noreferrer\">os.getcwd()</a> and <a href=\"https://docs.python.org/3/library/os.path.html#os.path.realpath\" rel=\"nofollow noreferrer\">os.path.realpath()</a> return path results based on the <em>current working directory</em>. Generally not what we want. The first element of the <a href=\"https://docs.python.org/3/library/sys.html#sys.argv\" rel=\"nofollow noreferrer\">sys.argv</a> list is the <em>path of the root script</em> (the script you run) regardless of whether you call the list in the root script itself or in any of its modules. It might come handy in some situations. The <a href=\"https://docs.python.org/3/reference/import.html#__file__\" rel=\"nofollow noreferrer\">__file__</a> variable contains path of the module from which it has been called.</p>\n\n<hr>\n\n<p>The following code correctly creates a file <code>example.txt</code> in the same directory where the script is located:</p>\n\n<pre><code>filedir = os.path.dirname(os.path.realpath(__file__))\nfilepath = os.path.join(filedir, 'example.txt')\n\nwith open(filepath, 'w'):\n pass\n</code></pre>\n"
},
{
"answer_id": 52081355,
"author": "Hassan Ashraf",
"author_id": 10047846,
"author_profile": "https://Stackoverflow.com/users/10047846",
"pm_score": 3,
"selected": false,
"text": "<p>you can just import your module\nthen hit its name and you'll get its full path</p>\n\n<pre><code>>>> import os\n>>> os\n<module 'os' from 'C:\\\\Users\\\\Hassan Ashraf\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32\\\\lib\\\\os.py'>\n>>>\n</code></pre>\n"
},
{
"answer_id": 52679374,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 3,
"selected": false,
"text": "<p>If you would like to know absolute path from your script you can use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">Path</a> object:</p>\n\n<pre><code>from pathlib import Path\n\nprint(Path().absolute())\nprint(Path().resolve('.'))\nprint(Path().cwd())\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.cwd\" rel=\"noreferrer\">cwd() method</a></p>\n\n<blockquote>\n <p>Return a new path object representing the current directory (as returned by os.getcwd())</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve\" rel=\"noreferrer\">resolve() method</a></p>\n\n<blockquote>\n <p>Make the path absolute, resolving any symlinks. A new path object is returned:</p>\n</blockquote>\n"
},
{
"answer_id": 55446232,
"author": "fr_andres",
"author_id": 4511978,
"author_profile": "https://Stackoverflow.com/users/4511978",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to retrieve the package's root path from any of its modules, the following works (tested on Python 3.6):</p>\n\n<pre><code>from . import __path__ as ROOT_PATH\nprint(ROOT_PATH)\n</code></pre>\n\n<p>The main <code>__init__.py</code> path can also be referenced by using <code>__file__</code> instead.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 60005316,
"author": "Javi",
"author_id": 9033534,
"author_profile": "https://Stackoverflow.com/users/9033534",
"pm_score": 2,
"selected": false,
"text": "<p>If you installed it using pip, "pip show" works great ('Location')</p>\n<p>$ pip show detectron2</p>\n<pre><code>Name: detectron2\nVersion: 0.1\nSummary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.\nHome-page: https://github.com/facebookresearch/detectron2\nAuthor: FAIR\nAuthor-email: None\nLicense: UNKNOWN\nLocation: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages\nRequires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore\n</code></pre>\n<h3>Update:</h3>\n<p>$ python -m pip show mymodule</p>\n<p>(author: wisbucky)</p>\n"
},
{
"answer_id": 60155768,
"author": "shrewmouse",
"author_id": 2464381,
"author_profile": "https://Stackoverflow.com/users/2464381",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a quick bash script in case it's useful to anyone. I just want to be able to set an environment variable so that I can <code>pushd</code> to the code.</p>\n\n<pre><code>#!/bin/bash\nmodule=${1:?\"I need a module name\"}\n\npython << EOI\nimport $module\nimport os\nprint os.path.dirname($module.__file__)\nEOI\n</code></pre>\n\n<p>Shell example:</p>\n\n<pre><code>[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)\n[root@sri-4625-0004 ~]# echo $LXML\n/usr/lib64/python2.7/site-packages/lxml\n[root@sri-4625-0004 ~]#\n</code></pre>\n"
},
{
"answer_id": 64800657,
"author": "tupui",
"author_id": 6522112,
"author_profile": "https://Stackoverflow.com/users/6522112",
"pm_score": 3,
"selected": false,
"text": "<p>When you import a module, yo have access to plenty of information. Check out <code>dir(a_module)</code>. As for the path, there is a dunder for that: <code>a_module.__path__</code>. You can also just print the module itself.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> import a_module\n>>> print(dir(a_module))\n['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']\n>>> print(a_module.__path__)\n['/.../.../a_module']\n>>> print(a_module)\n<module 'a_module' from '/.../.../a_module/__init__.py'>\n</code></pre>\n"
},
{
"answer_id": 68976819,
"author": "wisbucky",
"author_id": 1081043,
"author_profile": "https://Stackoverflow.com/users/1081043",
"pm_score": -1,
"selected": false,
"text": "<p>If you used <code>pip</code>, then you can call <code>pip show</code>, but you must call it using the specific version of <code>python</code> that you are using. For example, these could all give different results:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ python -m pip show numpy\n$ python2.7 -m pip show numpy\n$ python3 -m pip show numpy\n\nLocation: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\n</code></pre>\n<p>Don't simply run <code>$ pip show numpy</code>, because there is no guarantee that it will be the same <code>pip</code> that different <code>python</code> versions are calling.</p>\n"
},
{
"answer_id": 70630024,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to retrieve the module path <strong>without loading</strong> it:</p>\n<pre><code>import importlib.util\n\nprint(importlib.util.find_spec("requests").origin)\n</code></pre>\n<p>Example output:</p>\n<pre><code>/usr/lib64/python3.9/site-packages/requests/__init__.py\n</code></pre>\n"
},
{
"answer_id": 73374657,
"author": "zwithouta",
"author_id": 10680954,
"author_profile": "https://Stackoverflow.com/users/10680954",
"pm_score": 0,
"selected": false,
"text": "<p>If your import is a site-package (e.g. <code>pandas</code>) I recommend this to get its directory (does not work if import is a module, like e.g. <code>pathlib</code>):</p>\n<pre class=\"lang-py prettyprint-override\"><code>from importlib import resources # part of core Python\nimport pandas as pd\n\npackage_dir = resources.path(package=pd, resource="").__enter__()\n</code></pre>\n<p>In general <a href=\"https://docs.python.org/3.7/library/importlib.html#module-importlib.resources\" rel=\"nofollow noreferrer\">importlib.resources</a> can be considered when a task is about accessing paths/resources of a site package.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python?
|
```
import a_module
print(a_module.__file__)
```
Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:
```
import os
path = os.path.abspath(a_module.__file__)
```
You can also try:
```
path = os.path.dirname(a_module.__file__)
```
To get the module's directory.
|
247,772 |
<pre><code>a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}
</code></pre>
<p>Am I right to say that this is an array of size 3 where the key value pairs are <code>0->4</code>, <code>1->3</code>, and <code>2->2</code>?</p>
<p>If so, I find this representation awfully confusing. At first, I thought it was a listing of values (or the array contained <code>{0, 4, 1, 3, 2, 2}</code>), but I figured that the <code>a:3</code>: was the size of the array. And if <code>3</code> was the size, then both the keys and values appeared in the brackets with no way of clearly identifying a key/value pair without counting off.</p>
<p>To clarify where I'm coming from:</p>
<p>Why did the PHP developers choose to serialize in this manner? What advantage does this have over, let's say the way var_dump and/or var_export displays its data?</p>
|
[
{
"answer_id": 247784,
"author": "JamShady",
"author_id": 11905,
"author_profile": "https://Stackoverflow.com/users/11905",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use the <a href=\"http://uk.php.net/unserialize\" rel=\"nofollow noreferrer\">unserialize()</a> function to restore the data to how it was before?</p>\n"
},
{
"answer_id": 247788,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "<p>Yes that's <code>array(4, 3, 2)</code></p>\n\n<p><code>a</code> for array, <code>i</code> for integer as key then value. You would have to count to get to a specific one, but PHP always deserialises the whole lot, so it has a count anyway.</p>\n\n<p>Edit: It's not too confusing when you get used to it, but it can be somewhat long-winded compared to, e.g. JSON</p>\n\n<blockquote>\n <p>Note: var_export() does not handle\n circular references as it would be\n close to impossible to generate\n parsable PHP code for that. If you\n want to do something with the full\n representation of an array or object,\n use serialize().</p>\n</blockquote>\n"
},
{
"answer_id": 247804,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 3,
"selected": true,
"text": "<pre><code>$string=\"a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}\";\n$array=unserialize($string);\nprint_r($array);\n</code></pre>\n\n<p>outpts:</p>\n\n<pre><code>Array\n(\n [0] => 4\n [1] => 3\n [2] => 2\n)\n</code></pre>\n\n<p>If think the point is that PHP does not differentiate between integer indexed arrays and string indexed hashtables. The serialization format can be used for hashtables exactly the same way: <code>a:<<size>>:{<<keytype>>:<<key>>;<<valuetype>>:<<value>>;...}</code></p>\n\n<p>As the format is not intended to be human readable but rather to provide a common format to represent all PHP variable types (with exception of resources), I think it's more simple to use the given format because the underlying variable can be reconstructed by reading the string character by character.</p>\n"
},
{
"answer_id": 247913,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 1,
"selected": false,
"text": "<p>Serialized PHP data is not really intended to be human readable - that is not a goal of the format as far as I know.</p>\n\n<p>I think the biggest reason the format looks the way it does is for brevity, and its form may also have underpinnings tied to the speed at which it can be processed.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
```
a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}
```
Am I right to say that this is an array of size 3 where the key value pairs are `0->4`, `1->3`, and `2->2`?
If so, I find this representation awfully confusing. At first, I thought it was a listing of values (or the array contained `{0, 4, 1, 3, 2, 2}`), but I figured that the `a:3`: was the size of the array. And if `3` was the size, then both the keys and values appeared in the brackets with no way of clearly identifying a key/value pair without counting off.
To clarify where I'm coming from:
Why did the PHP developers choose to serialize in this manner? What advantage does this have over, let's say the way var\_dump and/or var\_export displays its data?
|
```
$string="a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}";
$array=unserialize($string);
print_r($array);
```
outpts:
```
Array
(
[0] => 4
[1] => 3
[2] => 2
)
```
If think the point is that PHP does not differentiate between integer indexed arrays and string indexed hashtables. The serialization format can be used for hashtables exactly the same way: `a:<<size>>:{<<keytype>>:<<key>>;<<valuetype>>:<<value>>;...}`
As the format is not intended to be human readable but rather to provide a common format to represent all PHP variable types (with exception of resources), I think it's more simple to use the given format because the underlying variable can be reconstructed by reading the string character by character.
|
247,779 |
<p>I have essentially a survey that is shown, and people answer questions a lot like a test,
and there are different paths, it is pretty easy so far, but i wanted to make it more dynamic, so that i can have a generic rule that is for the test with all the paths, to make the evaluator easier to work with currently i just allow AND's, and each OR essentially becomes another Rule in the set, </p>
<p>QuestionID, then i form a bunch of AND rules like so
<code><pre>
<rule id="1">
<true>
<question ID=123>
<question ID=124>
</true>
<false>
<question ID=127>
<question ID=128>
</false>
</rule>
<rule id="2"><true>
<question ID=123>
<question ID=125>
</true>
<false>
<question ID=127>
</false>
</rule>
</pre></code></p>
<p>this rule 1 says if question 123, and 124 are answered true, and 127, 128 are false, they pass. OR (rule 2) is if 123 and 125 are true and 127 is false, they pass as well.
This gets tedious if there are many combinations, so i want to implement OR in the logic, I am just not sure what best approach is for this problem.</p>
<p>I think rules engine is too complicated, there must be an easier way, perhaps constructing a graph like in LINQ and then evaluating to see if they pass, </p>
<p>thanks!</p>
<p>--not an compsci major.</p>
|
[
{
"answer_id": 247836,
"author": "Tim Robinson",
"author_id": 32133,
"author_profile": "https://Stackoverflow.com/users/32133",
"pm_score": 3,
"selected": true,
"text": "<p>This doesn't have to be complicated: you're most of the way already, since your and elements effectively implement an AND-type rule. I would introduce an element that can hold and elements.</p>\n\n<p>In your could, you could have:</p>\n\n<ul>\n<li>A RuleBase class, with a \"public abstract bool Evaluate()\" method</li>\n<li>TrueRule, FalseRule and OrRule classes, which contain lists of RuleBase objects</li>\n<li>A QuestionRule class, which refers to a specific question</li>\n</ul>\n\n<p>You would implement the Evaluate method on each of these as follows:</p>\n\n<ul>\n<li><strong>TrueRule:</strong> returns true only if all the contained rules return true from Evaluate</li>\n<li><strong>FalseRule:</strong> returns true only if all the contained rules return false from Evaluate</li>\n<li><strong>OrRule:</strong> returns true if at least one of the contained rules returns true from Evaluate</li>\n<li><strong>QuestionRule:</strong> returns the answer to the original question</li>\n</ul>\n\n<p>This class hierarchy implements a simple abstract syntax tree (AST). LINQ, in the form of the System.Expressions.Expression class, does pretty much the same thing, but it's helpful to write your own if it's not obvious how everything fits together.</p>\n"
},
{
"answer_id": 247853,
"author": "toddk",
"author_id": 17640,
"author_profile": "https://Stackoverflow.com/users/17640",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I totally understand the problem you are trying to solve but you could use a simple XPath to get at the ID's:</p>\n\n<p>This would give you all of the \"true\" ID's where the rule ID = 1: \n/rule[@id=\"1\"]/true//@ID</p>\n\n<p>Same as above only it gives you the false ID's:\n/rule[@id=\"1\"]/false//@ID</p>\n\n<p>Lastly a link to an introduction to XPath in .NET\n<a href=\"http://www.developer.com/xml/article.php/3383961\" rel=\"nofollow noreferrer\">http://www.developer.com/xml/article.php/3383961</a></p>\n\n<p>Good Luck</p>\n"
},
{
"answer_id": 248058,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "<p>I'd suggest putting the answers on the questions, rather than using <code>true</code> and <code>false</code> to group the questions. I think that it makes for XML that's easier to read, which is debatable. What's not debatable is that it makes it possible to evaluate a <code>question</code> element independently, i.e. without any knowledge of the context in which you're trying to evaluate it. That makes for simpler code.</p>\n\n<p>I'd also take a page from XML Schema and implement your OR logic as a <code>choice</code> element. A <code>choice</code> element is true if any of its children are true. You can, of course, nest them:</p>\n\n<pre><code><rule id=\"1\">\n <question id=\"123\" answer=\"true\" />\n <question id=\"124\" answer=\"false\" />\n <choice id=\"1\">\n <question id=\"125\" answer='true' />\n <choice id=\"2\">\n <question id=\"126\" answer='false' />\n <question id=\"127\" answer='false' />\n </choice>\n </choice>\n</rule>\n</code></pre>\n\n<p>This leaves you with four pretty simple methods to implement, each of which is used by the one preceding it:</p>\n\n<ul>\n<li><code>bool GetProvidedAnswer(int questionID)</code></li>\n<li><code>bool IsQuestionCorrect(XmlElement question)</code></li>\n<li><code>bool IsChoiceCorrect(XmlElement choice)</code></li>\n<li><code>bool IsRuleSatisfied(XmlElement rule)</code></li>\n</ul>\n\n<p>The structure of the XML makes these methods pretty simple to implement:</p>\n\n<pre><code> bool IsRuleSatisfied(XmlElement rule)\n {\n bool satisfied = true;\n foreach (XmlElement child in rule.SelectNodes(\"*\"))\n {\n if (child.Name == \"question\")\n {\n satisfied = satisfied && IsQuestionCorrect(child);\n }\n if (child.Name == \"choice\")\n {\n satisfed = satisfied && IsChoiceCorrect(child);\n }\n if (!satisfied)\n {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>It might be worth adding a <code>List<XmlElement></code> to the parameters of the <code>IsFooCorrect</code> methods. (If the rule engine is in a class, you could make it a class field.) Make `all of the methods add the current element to the list when an answer's wrong. You can then examine the contents of that list to know exactly why a rule failed.</p>\n"
},
{
"answer_id": 5700845,
"author": "Arash Aghlara",
"author_id": 713118,
"author_profile": "https://Stackoverflow.com/users/713118",
"pm_score": 1,
"selected": false,
"text": "<p>If you use a proper Rule Engine that supports inferencing it would be more efficient and extensible.</p>\n\n<p>Take a look at <a href=\"http://www.flexrule.com\" rel=\"nofollow\">http://www.flexrule.com</a> which is a flexible, extensible rule engine that supports three types of rule. Procedural, Inference and Rule-Flow rules can be externalized from your application and get executed using this framework.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111/"
] |
I have essentially a survey that is shown, and people answer questions a lot like a test,
and there are different paths, it is pretty easy so far, but i wanted to make it more dynamic, so that i can have a generic rule that is for the test with all the paths, to make the evaluator easier to work with currently i just allow AND's, and each OR essentially becomes another Rule in the set,
QuestionID, then i form a bunch of AND rules like so
````
<rule id="1">
<true>
<question ID=123>
<question ID=124>
</true>
<false>
<question ID=127>
<question ID=128>
</false>
</rule>
<rule id="2"><true>
<question ID=123>
<question ID=125>
</true>
<false>
<question ID=127>
</false>
</rule>
````
this rule 1 says if question 123, and 124 are answered true, and 127, 128 are false, they pass. OR (rule 2) is if 123 and 125 are true and 127 is false, they pass as well.
This gets tedious if there are many combinations, so i want to implement OR in the logic, I am just not sure what best approach is for this problem.
I think rules engine is too complicated, there must be an easier way, perhaps constructing a graph like in LINQ and then evaluating to see if they pass,
thanks!
--not an compsci major.
|
This doesn't have to be complicated: you're most of the way already, since your and elements effectively implement an AND-type rule. I would introduce an element that can hold and elements.
In your could, you could have:
* A RuleBase class, with a "public abstract bool Evaluate()" method
* TrueRule, FalseRule and OrRule classes, which contain lists of RuleBase objects
* A QuestionRule class, which refers to a specific question
You would implement the Evaluate method on each of these as follows:
* **TrueRule:** returns true only if all the contained rules return true from Evaluate
* **FalseRule:** returns true only if all the contained rules return false from Evaluate
* **OrRule:** returns true if at least one of the contained rules returns true from Evaluate
* **QuestionRule:** returns the answer to the original question
This class hierarchy implements a simple abstract syntax tree (AST). LINQ, in the form of the System.Expressions.Expression class, does pretty much the same thing, but it's helpful to write your own if it's not obvious how everything fits together.
|
247,800 |
<p>I don't think this is possible, but if is then I need it :)</p>
<p>I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008.</p>
<p>The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated.</p>
<p>I tried making another partial class and redefining the default constructor, but that doesn't work. I then tried using the override and new keywords, but that doesn't work.</p>
<p>I know I could inherit from the partial class, but that would mean I'd have to change all of our source code to point to the new parent class. I would rather not have to do this.</p>
<p>Any ideas, work arounds, or hacks? </p>
<pre><code>//Auto-generated class
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public MyWebService() {
string myString = "auto-generated constructor";
//other code...
}
}
}
//Manually created class in order to override the default constructor
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public override MyWebService() { //this doesn't work
string myString = "overridden constructor";
//other code...
}
}
}
</code></pre>
|
[
{
"answer_id": 247808,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "<p>Nothing that I can think of. The \"best\" way I can come up with is to add a ctor with a dummy parameter and use that:</p>\n\n<pre><code>public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol \n{\n public override MyWebService(int dummy) \n { \n string myString = \"overridden constructor\";\n //other code...\n }\n}\n\n\nMyWebService mws = new MyWebService(0);\n</code></pre>\n"
},
{
"answer_id": 247809,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 6,
"selected": true,
"text": "<p>This is not possible.\nPartial classes are essentially parts of the same class; no method can be defined twice or overridden, and that includes the constructor.</p>\n\n<p>You could call a method in the constructor, and only implement it in the other part file.</p>\n"
},
{
"answer_id": 247814,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "<p>You can't do this. I suggest using a partial method which you can then create a definition for. Something like:</p>\n\n<pre><code>public partial class MyClass{ \n\n public MyClass(){ \n ... normal construction goes here ...\n AfterCreated(); \n }\n\n public partial void OnCreated();\n}\n</code></pre>\n\n<p>The rest should be pretty self explanatory.</p>\n\n<p>EDIT: </p>\n\n<p>I would also like to point out that you should be defining an interface for this service, which you can then program to, so you don't have to have references to the actual implementation. If you did this then you'd have a few other options.</p>\n"
},
{
"answer_id": 247874,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>I am thinking you might be able to do this with <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">PostSharp</a>, and it looks like someone has done just what you <a href=\"http://www.postsharp.org/forum/post1873.html\" rel=\"nofollow noreferrer\">want for methods in generated partial classes</a>. I don't know if this will readily translate to the ability to write a method and have its body replace the constructor as I haven't given it a shot yet but it seems worth a shot.</p>\n\n<p>Edit: <a href=\"http://www.codeproject.com/KB/cs/LinFuPart6.aspx\" rel=\"nofollow noreferrer\">this is along the same lines</a> and also looks interesting.</p>\n"
},
{
"answer_id": 2031936,
"author": "Tom Chantler",
"author_id": 234415,
"author_profile": "https://Stackoverflow.com/users/234415",
"pm_score": 6,
"selected": false,
"text": "<p>I had a similar problem, with my generated code being created by a DBML file (I'm using Linq-to-SQL classes).</p>\n<p>In the generated class it calls a partial void called OnCreated() at the end of the constructor.</p>\n<p>Long story short, if you want to keep the important constructor stuff the generated class does for you (which you probably should do), then in your partial class create the following:</p>\n<pre><code>partial void OnCreated()\n{\n // Do the extra stuff here;\n}\n</code></pre>\n"
},
{
"answer_id": 2569167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Hmmm,\nI think one elegant solution would be the following:</p>\n\n<pre><code>//* AutogenCls.cs file\n//* Let say the file is auto-generated ==> it will be overridden each time when\n//* auto-generation will be triggered.\n//*\n//* Auto-generated class, let say via xsd.exe\n//*\npartial class AutogenCls\n{\n public AutogenCls(...)\n {\n }\n}\n\n\n\n//* AutogenCls_Cunstomization.cs file\n//* The file keeps customization code completely separated from \n//* auto-generated AutogenCls.cs file.\n//*\npartial class AutogenCls\n{\n //* The following line ensures execution at the construction time\n MyCustomization m_MyCustomizationInstance = new MyCustomization ();\n\n //* The following inner&private implementation class implements customization.\n class MyCustomization\n {\n MyCustomization ()\n {\n //* IMPLEMENT HERE WHATEVER YOU WANT TO EXECUTE DURING CONSTRUCTION TIME\n }\n }\n}\n</code></pre>\n\n<p>This approach has some drawbacks (as everything):</p>\n\n<ol>\n<li><p>It is not clear when exactly will be executed the constructor of the MyCustomization inner class during whole construction procedure of the AutogenCls class.</p></li>\n<li><p>If there will be necessary to implement IDiposable interface for the MyCustomization class to correctly handle disposing of unmanaged resources of the MyCustomization class, I don't know (yet) how to trigger the MyCustomization.Dispose() method without touching the AutogenCls.cs file ... (but as I told 'yet' :)</p></li>\n</ol>\n\n<p>But this approach offers great separation from auto-generated code - whole customization is separated in different src code file.</p>\n\n<p>enjoy :)</p>\n"
},
{
"answer_id": 4562379,
"author": "nreyntje",
"author_id": 365989,
"author_profile": "https://Stackoverflow.com/users/365989",
"pm_score": 1,
"selected": false,
"text": "<p>This is in my opinion a design flaw in the language. They should have allowed multiple implementations of one partial method, that would have provided a nice solution.\nIn an even nicer way the constructor (also a method) can then also be simply be marked partial and multiple constructors with the same signature would run when creating an object.</p>\n\n<p>The most simple solution is probably to add one partial 'constructor' method per extra partial class:</p>\n\n<pre><code>public partial class MyClass{ \n\n public MyClass(){ \n ... normal construction goes here ...\n OnCreated1(); \n OnCreated2(); \n ...\n }\n\n public partial void OnCreated1();\n public partial void OnCreated2();\n}\n</code></pre>\n\n<p>If you want the partial classes to be agnostic about each other, you can use reflection:</p>\n\n<pre><code>// In MyClassMyAspect1.cs\npublic partial class MyClass{ \n\n public void MyClass_MyAspect2(){ \n ... normal construction goes here ...\n\n }\n\n}\n\n// In MyClassMyAspect2.cs\npublic partial class MyClass{ \n\n public void MyClass_MyAspect1(){ \n ... normal construction goes here ...\n }\n}\n\n// In MyClassConstructor.cs\npublic partial class MyClass : IDisposable { \n\n public MyClass(){ \n GetType().GetMethods().Where(x => x.Name.StartsWith(\"MyClass\"))\n .ForEach(x => x.Invoke(null));\n }\n\n public void Dispose() {\n GetType().GetMethods().Where(x => x.Name.StartsWith(\"DisposeMyClass\"))\n .ForEach(x => x.Invoke(null));\n }\n\n}\n</code></pre>\n\n<p>But really they should just add some more language constructs to work with partial classes.</p>\n"
},
{
"answer_id": 5076590,
"author": "Edward",
"author_id": 158675,
"author_profile": "https://Stackoverflow.com/users/158675",
"pm_score": 0,
"selected": false,
"text": "<p>For a Web service proxy generated by Visual Studio, you cannot add your own constructor in the partial class (well you can, but it does not get called). Instead, you can use the [OnDeserialized] attribute (or [OnDeserializing]) to hook in your own code at the point where the web proxy class is instantiated.</p>\n\n<pre><code>using System.Runtime.Serialization;\n\npartial class MyWebService\n{\n [OnDeserialized]\n public void OnDeserialized(StreamingContext context)\n {\n // your code here\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7572035,
"author": "rrreee",
"author_id": 967448,
"author_profile": "https://Stackoverflow.com/users/967448",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, this is now possible, now that partial methods have been added. Here's the doc: </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/wa80x488.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/wa80x488.aspx</a></p>\n\n<p>Basically, the idea is that you can declare and call a method in one file where you are defining the partial class, but not actually define the method in that file. In the other file, you can then define the method. If you are building an assembly where the method is not defined, then the ORM will remove all calls to the function.</p>\n\n<p>So in the case above it would look like this:</p>\n\n<p>//Auto-generated class</p>\n\n<pre><code>namespace MyNamespace {\n public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {\n public MyWebService() {\n string myString = \"auto-generated constructor\";\n OtherCode();\n }\n }\n}\n\npartial void OtherCode();\n</code></pre>\n\n<p>//Manually created class in order to override the default constructor</p>\n\n<pre><code>partial void OtherCode()\n{\n //do whatever extra stuff you wanted.\n}\n</code></pre>\n\n<p>It is somewhat limited, and in this particular case, where you have a generated file that you'd need to alter, it might not be the right solution, but for others who stumbled on this trying to override functionality in partial classes, this can be quite helpful.</p>\n"
},
{
"answer_id": 9274766,
"author": "Shadi",
"author_id": 628592,
"author_profile": "https://Stackoverflow.com/users/628592",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes you don't have access or it's not allowed to change the default constructor, for this reason you cannot have the default constructor to call any methods.</p>\n\n<p>In this case you can create another constructor with a dummy parameter, and make this new constructor to call the default constructor using \": this()\"</p>\n\n<pre><code>public SomeClass(int x) : this()\n{\n //Your extra initialization here\n}\n</code></pre>\n\n<p>And when you create a new instance of this class you just pass dummy parameter like this:</p>\n\n<pre><code>SomeClass objSomeClass = new SomeClass(0);\n</code></pre>\n"
},
{
"answer_id": 17152019,
"author": "Doctor Jones",
"author_id": 39277,
"author_profile": "https://Stackoverflow.com/users/39277",
"pm_score": 2,
"selected": false,
"text": "<p>The problem that the OP has got is that the web reference proxy doesn't generate any partial methods that you can use to intercept the constructor.</p>\n\n<p>I ran into the same problem, and I can't just upgrade to WCF because the web service that I'm targetting doesn't support it.</p>\n\n<p>I didn't want to manually amend the autogenerated code because it'll get flattened if anyone ever invokes the code generation.</p>\n\n<p>I tackled the problem from a different angle. I knew my initialization needed doing before a request, it didn't really need to be done at construction time, so I just overrode the GetWebRequest method like so.</p>\n\n<pre><code>protected override WebRequest GetWebRequest(Uri uri)\n{\n //only perform the initialization once\n if (!hasBeenInitialized)\n {\n Initialize();\n }\n\n return base.GetWebRequest(uri);\n}\n\nbool hasBeenInitialized = false;\n\nprivate void Initialize()\n{\n //do your initialization here...\n\n hasBeenInitialized = true;\n}\n</code></pre>\n\n<p>This is a nice solution because it doesn't involve hacking the auto generated code, and it fits the OP's exact use case of performing initialization login for a SoapHttpClientProtocol auto generated proxy.</p>\n"
},
{
"answer_id": 57999465,
"author": "msulis",
"author_id": 9317,
"author_profile": "https://Stackoverflow.com/users/9317",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not quite addressing the OP, but if you happen to be generating classes with the EntityFramework Reverse POCO Generator, there's a partial method called in the constructor which is handy for initializing things you're adding via partial classes on your own...</p>\n\n<p>Generated by tool:</p>\n\n<pre><code> [System.CodeDom.Compiler.GeneratedCode(\"EF.Reverse.POCO.Generator\", \"2.37.3.0\")]\n public partial class Library {\n public string City { get; set; }\n public Library() {\n InitializePartial();\n }\n partial void InitializePartial();\n }\n</code></pre>\n\n<p>added by you:</p>\n\n<pre><code> public partial class Library {\n List<Book> Books { get; set; }\n partial void InitializePartial() {\n Books = new List<Book>();\n }\n }\n\n public class Book {\n public string Title { get; set; }\n }\n</code></pre>\n"
},
{
"answer_id": 74291487,
"author": "l33t",
"author_id": 419761,
"author_profile": "https://Stackoverflow.com/users/419761",
"pm_score": 0,
"selected": false,
"text": "<p>A bit late to the game, but this is indeed possible. Kind of.</p>\n<p>I recently performed the trick below in a code generator of mine, and the result is satisfying. Yes, a dummy argument is required, but it will not cause any major concerns. For consistency, you may want to apply some rules:</p>\n<p><strong>Rules</strong></p>\n<ol>\n<li>Manually created constructor must be <code>protected</code>.</li>\n<li>Generated constructor must be <code>public</code>, with the same arguments as the protected one plus an extra <strong>optional</strong> dummy argument.</li>\n<li>The generated constructor calls the original constructor with all the supplied arguments.</li>\n</ol>\n<p>This works for regular construction as well as reflection:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var s1 = new MyWebService();\n\nvar s2 = (MyWebService?)Activator.CreateInstance(\n typeof(MyWebService),\n BindingFlags.CreateInstance | BindingFlags.Public);\n</code></pre>\n<p>And for <code>IoC</code>, it should also work (verified in <code>DryIoc</code>). The container resolves the injected arguments, skipping the optional ones:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var service = container.Resolve<MyWebService>();\n</code></pre>\n<p><strong>Sample code</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>// <auto-generated />\npublic partial class MyWebService\n{\n public MyWebService(object? dummyArgument = default)\n : this()\n {\n // Auto-generated constructor\n }\n}\n\n// Manually created\npublic partial class MyWebService\n{\n protected MyWebService()\n {\n }\n}\n</code></pre>\n<p>The above <strong>works for any number of constructor arguments</strong>. As for the dummy arguments, we could invent a special type (maybe an <code>enum</code>) further restricting possible abuse of this extra argument.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
I don't think this is possible, but if is then I need it :)
I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008.
The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated.
I tried making another partial class and redefining the default constructor, but that doesn't work. I then tried using the override and new keywords, but that doesn't work.
I know I could inherit from the partial class, but that would mean I'd have to change all of our source code to point to the new parent class. I would rather not have to do this.
Any ideas, work arounds, or hacks?
```
//Auto-generated class
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public MyWebService() {
string myString = "auto-generated constructor";
//other code...
}
}
}
//Manually created class in order to override the default constructor
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public override MyWebService() { //this doesn't work
string myString = "overridden constructor";
//other code...
}
}
}
```
|
This is not possible.
Partial classes are essentially parts of the same class; no method can be defined twice or overridden, and that includes the constructor.
You could call a method in the constructor, and only implement it in the other part file.
|
247,818 |
<p>Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values.
For example, in a <code>std::multimap< string, int ></code> I store </p>
<pre><code>{"Group1", 1},
{"Group1", 2},
{"Group1", 3},
{"Group2", 10},
{"Group2", 11},
{"Group2", 12}
</code></pre>
<p>Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use <code>lower_bound</code>, <code>upper_bound</code> to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.</p>
|
[
{
"answer_id": 247852,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 4,
"selected": false,
"text": "<p>If you already know the keys, you can use <code>multimap::equal_range</code> to get the iterators to the beginning and end of the group; use any standard algorithm to get the desired results from the range. If you don't know the keys, you can start at <code>begin()</code> and iterate through them yourself, comparing keys to find the start of each new group.</p>\n"
},
{
"answer_id": 247859,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 6,
"selected": true,
"text": "<pre><code>pair<Iter, Iter> range = my_multimap.equal_range(\"Group1\");\nint total = accumulate(range.first, range.second, 0);\n</code></pre>\n\n<p>Is one way.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so:</p>\n\n<pre><code>template <typename Pair>\nstruct Less : public std::binary_function<Pair, Pair, bool>\n{\n bool operator()(const Pair &x, const Pair &y) const\n {\n return x.first < y.first;\n }\n};\n\nIter first = mmap.begin();\nIter last = adjacent_find(first, mmap.end(), Less<MultimapType::value_type>());\n</code></pre>\n"
},
{
"answer_id": 248009,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": -1,
"selected": false,
"text": "<p>Not a multimap answer, but you can do things like the following if you so choose.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <boost/assign/list_of.hpp>\n#include <boost/foreach.hpp>\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\n\nint main() {\n typedef map<string, vector<int> > collection;\n collection m;\n m[\"Group 1\"] = list_of(1)(2)(3);\n m[\"Group 2\"] = list_of(10)(11)(12);\n collection::iterator g2 = m.find(\"Group 2\");\n if (g2 != m.end()) {\n BOOST_FOREACH(int& i, g2->second) {\n cout << i << \"\\n\";\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 249401,
"author": "Dean Michael",
"author_id": 11274,
"author_profile": "https://Stackoverflow.com/users/11274",
"pm_score": 1,
"selected": false,
"text": "<p>You can use an alternate container that can contain the aggregate sums of each group. To do this you might do something like:</p>\n\n<pre><code>template <class KeyType, class ValueType>\nstruct group_add {\n typedef map<KeyType, ValueType> map_type;\n map_type & aggregates;\n explicit group_add(map_type & aggregates_)\n : aggregates(aggregates_) { };\n void operator() (map_type::value_type const & element) {\n aggregates[element.first] += element.second;\n };\n};\n\ntemplate <class KeyType, class ValueType>\ngroup_add<KeyType, ValueType>\nmake_group_adder(map<KeyType, ValueType> & map_) {\n return group_add<KeyType, ValueType>(map_);\n};\n\n// ...\nmultimap<string, int> members;\n// populate members\nmap<string, int> group_aggregates;\nfor_each(members.begin(), members.end(),\n make_group_adder(group_aggregates));\n// group_aggregates now has the sums per group\n</code></pre>\n\n<p>Of course, if you have Lambda's (in C++0x) it could be simpler:</p>\n\n<pre><code>multimap<string, int> members;\nmap<string, int> group_aggregates;\nfor_each(members.begin(), members.end(),\n [&group_aggregates](multimap<string, int>::value_type const & element) {\n group_aggregates[element.first] += element.second;\n }\n );\n</code></pre>\n"
},
{
"answer_id": 1196243,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>// samekey.cpp -- Process groups with identical keys in a multimap\n\n#include <iostream>\n#include <string>\n#include <map>\nusing namespace std;\n\ntypedef multimap<string, int> StringToIntMap;\ntypedef StringToIntMap::iterator mapIter;\n\nint main ()\n{\n StringToIntMap mymap;\n\n mymap.insert(make_pair(\"Group2\", 11));\n mymap.insert(make_pair(\"Group1\", 3));\n mymap.insert(make_pair(\"Group2\", 10));\n mymap.insert(make_pair(\"Group1\", 1));\n mymap.insert(make_pair(\"Group2\", 12));\n mymap.insert(make_pair(\"Group1\", 2));\n\n cout << \"mymap contains:\" << endl;\n\n mapIter m_it, s_it;\n\n for (m_it = mymap.begin(); m_it != mymap.end(); m_it = s_it)\n {\n string theKey = (*m_it).first;\n\n cout << endl;\n cout << \" key = '\" << theKey << \"'\" << endl;\n\n pair<mapIter, mapIter> keyRange = mymap.equal_range(theKey);\n\n // Iterate over all map elements with key == theKey\n\n for (s_it = keyRange.first; s_it != keyRange.second; ++s_it)\n {\n cout << \" value = \" << (*s_it).second << endl;\n }\n }\n\n return 0;\n\n} // end main\n\n// end samekey.cpp\n</code></pre>\n"
},
{
"answer_id": 33490177,
"author": "Hayek.Yu",
"author_id": 2259906,
"author_profile": "https://Stackoverflow.com/users/2259906",
"pm_score": 0,
"selected": false,
"text": "<pre><code>equal_range\n</code></pre>\n\n<p>Syntax:</p>\n\n<pre><code>#include <map>\npair<iterator, iterator> equal_range( const key_type& key );\n</code></pre>\n\n<p>The function <code>equal_range()</code> returns two iterators - one to the first element that contains key, another to a point just after the last element that contains key. </p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32492/"
] |
Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values.
For example, in a `std::multimap< string, int >` I store
```
{"Group1", 1},
{"Group1", 2},
{"Group1", 3},
{"Group2", 10},
{"Group2", 11},
{"Group2", 12}
```
Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use `lower_bound`, `upper_bound` to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.
|
```
pair<Iter, Iter> range = my_multimap.equal_range("Group1");
int total = accumulate(range.first, range.second, 0);
```
Is one way.
**Edit:**
If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so:
```
template <typename Pair>
struct Less : public std::binary_function<Pair, Pair, bool>
{
bool operator()(const Pair &x, const Pair &y) const
{
return x.first < y.first;
}
};
Iter first = mmap.begin();
Iter last = adjacent_find(first, mmap.end(), Less<MultimapType::value_type>());
```
|
247,819 |
<p>I have an application built in Flex Builder 3. It has a fair amount of mxml and as3 code which uses some other custom compenents. I have looked at the documentation on building components which shows how to make a simple mxml or action script component that extends something like a combobox, but I'm lost as to how to take a whole existing and independently functioning Application and turn it into a reusable component. </p>
<p>Basically, I'd just like to create multiple instances of this app inside of another flex project.</p>
<p>Anyone able to provide a little guidance?</p>
|
[
{
"answer_id": 247890,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "<p>If you simply want some \"parent\" Flex application to embed several instances of this autonomous child application, then you should see Adobe's <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html\" rel=\"nofollow noreferrer\">\"Embedding Asset Types\"</a> documentation, which describes how to embed one SWF file in another.</p>\n\n<p>From the documentation:</p>\n\n<blockquote>\n <p>You typically embed a Flex application\n when you do not require the embedding\n application to interact with the\n embedded application. If the embedding\n application requires interactivity\n with the embedded application, you\n might consider implementing it as a\n custom component, rather than as a\n separate application.</p>\n</blockquote>\n\n<p>If you <em>do</em> require interaction between the embedded application and the parent application, you can look into the <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html\" rel=\"nofollow noreferrer\">SWFLoader</a> control.</p>\n"
},
{
"answer_id": 248376,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 3,
"selected": true,
"text": "<p>The easy thing to do is to swap the Application mxml tag with a VBox tag...thus making it act like a component. </p>\n\n<p>e.g. If this were your application:</p>\n\n<pre>\n<code>\n//Foo.mxml\n<mx:Appliction xmlns:mx=\"http://www.adobe.com/2006/mxml\">\n <mx:Label text = \"foo\" />\n</mx:Appliction>\n</code>\n</pre>\n\n<p>change it to:</p>\n\n<pre>\n<code>\n//Foo.mxml\n<mx:VBox>\n <mx:Label text = \"foo\" />\n</mx:VBox>\n</code>\n</pre>\n\n<p>and then you can do something like this:</p>\n\n<pre>\n<code>\n//App.mxml\n<mx:Appliction \n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:local=\"your.package.scheme.*\"\n>\n <local:Foo />\n\n</mx:Appliction>\n</code>\n</pre>\n\n<p>You may have to make some public properties if you need to pass in any data to the component...</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an application built in Flex Builder 3. It has a fair amount of mxml and as3 code which uses some other custom compenents. I have looked at the documentation on building components which shows how to make a simple mxml or action script component that extends something like a combobox, but I'm lost as to how to take a whole existing and independently functioning Application and turn it into a reusable component.
Basically, I'd just like to create multiple instances of this app inside of another flex project.
Anyone able to provide a little guidance?
|
The easy thing to do is to swap the Application mxml tag with a VBox tag...thus making it act like a component.
e.g. If this were your application:
```
//Foo.mxml
<mx:Appliction xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Label text = "foo" />
</mx:Appliction>
```
change it to:
```
//Foo.mxml
<mx:VBox>
<mx:Label text = "foo" />
</mx:VBox>
```
and then you can do something like this:
```
//App.mxml
<mx:Appliction
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="your.package.scheme.*"
>
<local:Foo />
</mx:Appliction>
```
You may have to make some public properties if you need to pass in any data to the component...
|
247,833 |
<p>I have a Visual Basic .NET program which needs to open and close an Excel spreadsheet. Opening and reading the spreadsheet work fine, but trying to close the Excel 2007 application causes it to hang. It seems to close, but if you look in the task manager the application is still running. The code that I'm using to close it is</p>
<pre><code>wbkData.Close(saveChanges:=False)
appExcel.Quit()
wbkData = Nothing
appExcel = Nothing
</code></pre>
<p>How can I get Excel to close properly?</p>
|
[
{
"answer_id": 247841,
"author": "Eric Ness",
"author_id": 18891,
"author_profile": "https://Stackoverflow.com/users/18891",
"pm_score": 0,
"selected": false,
"text": "<p>I found a <a href=\"http://blogs.msdn.com/excel/archive/2006/06/19/636534.aspx\" rel=\"nofollow noreferrer\">solution in the MSDN Excel Blog</a> which worked for me. It's explained as</p>\n\n<blockquote>\n <p>There are two problems with the above:</p>\n \n <p>(1) Although the code appears to\n dispose of the 'wbkData' object first,\n etc., the code above does not actually\n <em>enforce</em> this as the .NET Garbage Collection procedure can dispose of\n its objects in any order. (GC is\n non-deterministic in order, not just\n non-deterministic in timing.)</p>\n \n <p>(2) Commands such as 'wsh =\n wbkData.Workssheets.Item(1)' -- or\n lines like it -- are very common and\n will create an RCW object wrapping a\n 'Worksheets' object. You won't have a\n variable holding a reference to it, so\n you don't generally think about it,\n but this RCW object will not be\n disposed until the next Garbage\n Collection. However, the code above\n calls GC.Collect() <em>last</em>, and so the\n RCW is still holding a reference to\n this 'Worksheets' object when\n appExcel.Quit() is called. Excel hangs\n as a result.</p>\n</blockquote>\n\n<p>The final code looks like</p>\n\n<pre><code>GC.Collect()\nGC.WaitForPendingFinalizers()\n\nwbkData.Close(SaveChanges:=False)\nSystem.Runtime.InteropServices.Marshal.FinalReleaseComObject(wbkData) : wbkData = Nothing\nappExcel.Quit()\nSystem.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExcel) : appExcel = Nothing\n</code></pre>\n"
},
{
"answer_id": 248040,
"author": "hearn",
"author_id": 30096,
"author_profile": "https://Stackoverflow.com/users/30096",
"pm_score": 3,
"selected": false,
"text": "<p>The answer to your question has been covered here i think:\n<a href=\"https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c\">How to properly clean up excel interop objects in c</a></p>\n\n<p>i cant see from your code sample, but basically, always assign your excel objects to local variables, never going 'two dots down', like this:</p>\n\n<pre><code>//FAIL\n\nWorkbook wkBook = xlApp.Workbooks.Open(@\"C:\\mybook.xls\");\n</code></pre>\n\n<p>instead ref each obj individually:</p>\n\n<pre><code>//WIN\n\nWorksheets sheets = xlApp.Worksheets;\nWorksheet sheet = sheets.Open(@\"C:\\mybook.xls\");\n...\nMarshal.ReleaseComObject(sheets);\nMarshal.ReleaseComObject(sheet);\n</code></pre>\n\n<p>.NET creates a wrapper for the COM object that is invisible to you and is not released until the GC weaves its magic.</p>\n\n<p>Until I discovered this, I was running the hacky code below in an ASP.NET application each time i created a new workbook that that checks the age of the excel.exe process and kills any that are over a minute old:</p>\n\n<pre><code>//force kill any excel processes over one minute old.\ntry\n{\n Process[] procs = Process.GetProcessesByName(\"EXCEL\");\n foreach (Process p in procs)\n {\n if (p.StartTime.AddMinutes(1) < DateTime.Now)\n {\n p.Kill(); \n } \n } \n}\ncatch (Exception)\n{} \n</code></pre>\n"
},
{
"answer_id": 248629,
"author": "Mike Rosenblum",
"author_id": 10429,
"author_profile": "https://Stackoverflow.com/users/10429",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote that post you <a href=\"http://blogs.msdn.com/excel/archive/2006/06/19/636534.aspx\" rel=\"nofollow noreferrer\">mentioned on the Excel Team Blog</a>...</p>\n\n<p>I also discussed this issue previously on StackOverflow for the question <a href=\"https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c#159419\">How to properly clean up Excel interop objects in C#</a>.</p>\n\n<p>The first answer for that question was marked as \"correct\" and got 11 votes, but I assure you that that policy is extremely difficult to utilize properly in practice. If one ever slips anywhere and uses \"two dots\", or iterates cells via a for each loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang -- and there will be no way to find the cause of that in the code.</p>\n\n<p>Instead, the cleanup procedure you are adopting is definitely the way to go.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18891/"
] |
I have a Visual Basic .NET program which needs to open and close an Excel spreadsheet. Opening and reading the spreadsheet work fine, but trying to close the Excel 2007 application causes it to hang. It seems to close, but if you look in the task manager the application is still running. The code that I'm using to close it is
```
wbkData.Close(saveChanges:=False)
appExcel.Quit()
wbkData = Nothing
appExcel = Nothing
```
How can I get Excel to close properly?
|
The answer to your question has been covered here i think:
[How to properly clean up excel interop objects in c](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c)
i cant see from your code sample, but basically, always assign your excel objects to local variables, never going 'two dots down', like this:
```
//FAIL
Workbook wkBook = xlApp.Workbooks.Open(@"C:\mybook.xls");
```
instead ref each obj individually:
```
//WIN
Worksheets sheets = xlApp.Worksheets;
Worksheet sheet = sheets.Open(@"C:\mybook.xls");
...
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(sheet);
```
.NET creates a wrapper for the COM object that is invisible to you and is not released until the GC weaves its magic.
Until I discovered this, I was running the hacky code below in an ASP.NET application each time i created a new workbook that that checks the age of the excel.exe process and kills any that are over a minute old:
```
//force kill any excel processes over one minute old.
try
{
Process[] procs = Process.GetProcessesByName("EXCEL");
foreach (Process p in procs)
{
if (p.StartTime.AddMinutes(1) < DateTime.Now)
{
p.Kill();
}
}
}
catch (Exception)
{}
```
|
247,834 |
<p>The scriptaculous wiki has a demo (<a href="http://github.com/madrobby/scriptaculous/wikis/effect-slidedown" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/effect-slidedown</a>) that shows the SlideDown effect in use. However I need to have the same link to slide down if a certain DIV is hidden and SlideUp if that DIV is showing.</p>
<p>How do I achieve this?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 247845,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "<p>Wrap it in a function, call the function instead.</p>\n\n<pre><code>function slideMe(myDiv) {\n\n if(Element.visible(myDiv)) {\n //slide up\n\n }\n\n else {\n\n //slide down\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248012,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": true,
"text": "<p>Use <a href=\"http://github.com/madrobby/scriptaculous/wikis/effect-toggle\" rel=\"noreferrer\">Effect.toggle</a>.</p>\n\n<pre><code>Effect.toggle('element_id', 'slide');\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32495/"
] |
The scriptaculous wiki has a demo (<http://github.com/madrobby/scriptaculous/wikis/effect-slidedown>) that shows the SlideDown effect in use. However I need to have the same link to slide down if a certain DIV is hidden and SlideUp if that DIV is showing.
How do I achieve this?
Thanks.
|
Use [Effect.toggle](http://github.com/madrobby/scriptaculous/wikis/effect-toggle).
```
Effect.toggle('element_id', 'slide');
```
|
247,837 |
<p>I found a while ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until the class constructor or load has been called. The reason was performance - but are there other reasons to do or not do this? Are there exceptions to this rule?</p>
<p><strong>ie: this is what I do based on what I think the best practice is:</strong></p>
<pre><code>public class SomeClass
{
private PersonObject _person;
public SomeClass()
{
_person = new PersonObject("Smitface");
}
}
</code></pre>
<p><strong>opposed to:</strong></p>
<pre><code>public class SomeClass
{
private PersonObject _person = new PersonObject("Smitface");
public SomeClass()
{
}
}
</code></pre>
|
[
{
"answer_id": 247838,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer the latter, but only becuase I find it neater. </p>\n\n<p>It's personal preference really, they both do the same thing.</p>\n"
},
{
"answer_id": 247843,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "<p>Honestly, if you look at the IL, all that happens in the second case is the compiler moves the initialization to the constructor for you.</p>\n\n<p>Personally, I like to see all initialization done in the constructor. If I'm working on a throwaway prototype project, I don't mind having the initialization and declaration in the same spot, but for my \"I want to keep this\" projects I do it all in the constructor.</p>\n"
},
{
"answer_id": 247844,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": -1,
"selected": false,
"text": "<p>I prefer to initialize variables as soon as possible, since it avoids (some) null errors.</p>\n\n<p>Edit: Obviously in this simplified example there is no difference, however in the general case I believe it is good practice to initialize class variables when they are declared, if possible. This makes it impossible to refer to the variable before it it initialized, which eliminates some errors which would be possible when you initialize fields in the constructor.</p>\n\n<p>As you get more class variables and the initialization sequence in the constructor gets more complex, it gets easier to introduce bugs where one initialization depends on another initialization which haven't happend yet.</p>\n"
},
{
"answer_id": 247847,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the context of how the variable will be used. Naturally constants and static or readonly should be initialized on declaration, otherwise they typically should be initialized in the constructor. That way you can swap out design patterns for how your objects are instatiated fairly easy without having to worry about when the variables will be initialized.</p>\n"
},
{
"answer_id": 247848,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": "<p>The first declaration is actually cleaner. The second conceals the fact the constructor initializes the class in the static constructor. If for any reason the constructor fails, the whole type is unusable for the rest of the applicaiton.</p>\n"
},
{
"answer_id": 247867,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 5,
"selected": true,
"text": "<p>If you set your variable outside of the constructor then there is no error handling (handeling) available. While in your example it makes no difference, but there are many cases that you may want to have some sort of error handling. In that case using your first option would be correct.</p>\n\n<p>Nescio talked about what implication this would have on your applicaiton if there were some constructor failures.</p>\n\n<p>For that reason, I always use Option #1.</p>\n"
},
{
"answer_id": 247896,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 0,
"selected": false,
"text": "<p>I like to initialize in the constructor because that way it all happens in one place, and also because it makes it easier if you decide to create an overloaded constructor later on.</p>\n\n<p>Also, it helps to remind me of things that I'll want to clean up in a deconstructor.</p>\n"
},
{
"answer_id": 247905,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>the latter can take advantage of lazy instantiation, i.e. it won't initialize the variable until it is referenced</p>\n"
},
{
"answer_id": 247927,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 0,
"selected": false,
"text": "<p>i think this type of question is stylistic only, so who cares what way you do it. the language allows both, so other people are going to do both. don't make bad assumptions.</p>\n"
},
{
"answer_id": 248007,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, in spite of what others have said, it <strong>can be</strong> important whether your initialization is inside or outside the constructor, as there is different behaviour during object construction if the object is in a hierarchy (i.e. the order in which things get run is different).</p>\n\n<p>See <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx\" rel=\"nofollow noreferrer\">this post</a> and <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx\" rel=\"nofollow noreferrer\">this post</a> from Eric Lippert which explains the semantic difference between the two in more detail.</p>\n\n<p>So the answer is that in the majority of cases it doesn't make any difference, and it certainly doesn't make any difference in terms of performance, but in a minority of cases it <em>could</em> make a difference, and you should know why, and make a decision based on that.</p>\n"
},
{
"answer_id": 248583,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>You should generally prefer the <em>second variant</em>. It's more robust to changes in your code. Suppose you add a constructor. Now you have to remember to initialize your variables there as well, unless you use the second variant.</p>\n\n<p>Of course, this only counts if there are no compelling reasons to use in-constructor initialization (as mentioned by discorax).</p>\n"
},
{
"answer_id": 248803,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 2,
"selected": false,
"text": "<p>There's a common pattern called Dependency Injection or Inversion of Control (IOC) that offers exactly these two mechanisms for \"injecting\" a dependant object (like a DAL class) into a class that's furthur up the dependency chain (furthur from the database)</p>\n\n<p>In this pattern, using a ctor, you would</p>\n\n<p>public class SomeClass<br>\n{<br>\n private PersonObject per;</p>\n\n<pre><code> public SomeClass(PersonObject person) \n\n { \n per = person; \n } \n</code></pre>\n\n<p>}</p>\n\n<p>private PersonObject Joe = new PersonObject(\"Smitface\");</p>\n\n<p>SomeClass MyObj = new SomeClass(Joe);</p>\n\n<p>Now you could for example, pass in a real DAL class for production call\nor a test DAL class in a unit test method... </p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
I found a while ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until the class constructor or load has been called. The reason was performance - but are there other reasons to do or not do this? Are there exceptions to this rule?
**ie: this is what I do based on what I think the best practice is:**
```
public class SomeClass
{
private PersonObject _person;
public SomeClass()
{
_person = new PersonObject("Smitface");
}
}
```
**opposed to:**
```
public class SomeClass
{
private PersonObject _person = new PersonObject("Smitface");
public SomeClass()
{
}
}
```
|
If you set your variable outside of the constructor then there is no error handling (handeling) available. While in your example it makes no difference, but there are many cases that you may want to have some sort of error handling. In that case using your first option would be correct.
Nescio talked about what implication this would have on your applicaiton if there were some constructor failures.
For that reason, I always use Option #1.
|
247,856 |
<pre><code>List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();
</code></pre>
<p>List is populated here, then sorted:</p>
<pre><code>nameList.Sort();
</code></pre>
<p>Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):</p>
<pre><code>foreach (string name in nameList){
ddl.Items.Add(new ListItem(nameList[name].ToString()));
}
</code></pre>
<p>No workie - any suggestions? It's giving me compile errors:</p>
<pre><code>Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments
Error - Argument '1': cannot convert from 'string' to 'int'
</code></pre>
|
[
{
"answer_id": 247865,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 5,
"selected": false,
"text": "<p>Why not just bind the DDL directly to the List like</p>\n\n<pre><code>DropDownList ddl = new DropDownList();\nddl.DataSource = nameList;\nddl.DataBind();\n</code></pre>\n"
},
{
"answer_id": 247868,
"author": "Mike Burton",
"author_id": 22225,
"author_profile": "https://Stackoverflow.com/users/22225",
"pm_score": 6,
"selected": true,
"text": "<p>Replace this:</p>\n\n<pre><code> ddl.Items.Add(new ListItem(nameList[name].ToString()));\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code> ddl.Items.Add(new ListItem(name));\n</code></pre>\n\n<p>Done like dinner.</p>\n"
},
{
"answer_id": 247870,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 0,
"selected": false,
"text": "<pre><code> foreach (string name in nameList){\n ddl.Items.Add(new ListItem(nameList[name].ToString()));\n }\n</code></pre>\n\n<p>Is your problem.</p>\n\n<p>it should look more like</p>\n\n<pre><code>foreach (string name in nameList){\n ddl.Items.Add(new ListItem(name.ToString()));\n}\n</code></pre>\n\n<p>But I actually like Marcus' suggestion a little better.</p>\n"
},
{
"answer_id": 247871,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 1,
"selected": false,
"text": "<p>That would be because List is not indexed by string (name) but by ints.</p>\n\n<pre><code>foreach (string name in nameList)\n{\n ddl.Items.Add(new ListItem(name));\n}\n</code></pre>\n\n<p>Will fix that.</p>\n"
},
{
"answer_id": 247881,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 0,
"selected": false,
"text": "<p>You get that error because the collection <code>nameList</code> is a <code>List</code> so you must access it using an index not a string (you use name).</p>\n\n<p>So you can write:</p>\n\n<pre><code>foreach (string name in nameList){\n ddl.Items.Add(name);\n}\n</code></pre>\n\n<p>BTW the best way to do this is:</p>\n\n<pre><code>ddl.DataSource = nameList;\nddl.DataBind();\n</code></pre>\n"
},
{
"answer_id": 8542070,
"author": "Tom",
"author_id": 814886,
"author_profile": "https://Stackoverflow.com/users/814886",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ddl.DataSource = nameList; \nddl.DataBind(); \n</code></pre>\n\n<p>Doesn't work if it's a SharePoint list - Error: Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource. Decided to chime in, in case any SharePoint developers thought this was for an SPList instead of List<string>, as was written above.</p>\n\n<p>There is a way to bind to an SPList, but you'd use an SPListItemCollection, or go one better and use an SPDataSource. For the SharePoint developers, see <a href=\"http://www.sharepointnutsandbolts.com/2008/06/spdatasource-every-sharepoint-developer.html\" rel=\"nofollow\">this blog by Chris O' Brien</a>.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
```
List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();
```
List is populated here, then sorted:
```
nameList.Sort();
```
Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):
```
foreach (string name in nameList){
ddl.Items.Add(new ListItem(nameList[name].ToString()));
}
```
No workie - any suggestions? It's giving me compile errors:
```
Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments
Error - Argument '1': cannot convert from 'string' to 'int'
```
|
Replace this:
```
ddl.Items.Add(new ListItem(nameList[name].ToString()));
```
with this:
```
ddl.Items.Add(new ListItem(name));
```
Done like dinner.
|
247,857 |
<p>I'm trying to think of a naming convention that accurately conveys what's going on within a class I'm designing. On a secondary note, I'm trying to decide between two almost-equivalent user APIs.</p>
<p>Here's the situation:</p>
<p>I'm building a scientific application, where one of the central data structures has three phases: 1) accumulation, 2) analysis, and 3) query execution.</p>
<p>In my case, it's a spatial modeling structure, internally using a KDTree to partition a collection of points in 3-dimensional space. Each point describes one or more attributes of the surrounding environment, with a certain level of confidence about the measurement itself.</p>
<p>After adding (a potentially large number of) measurements to the collection, the owner of the object will query it to obtain an interpolated measurement at a new data point somewhere within the applicable field.</p>
<p>The API will look something like this (the code is in Java, but that's not really important; the code is divided into three sections, for clarity):</p>
<pre><code>// SECTION 1:
// Create the aggregation object, and get the zillion objects to insert...
ContinuousScalarField field = new ContinuousScalarField();
Collection<Measurement> measurements = getMeasurementsFromSomewhere();
// SECTION 2:
// Add all of the zillion objects to the aggregation object...
// Each measurement contains its xyz location, the quantity being measured,
// and a numeric value for the measurement. For example, something like
// "68 degrees F, plus or minus 0.5, at point 1.23, 2.34, 3.45"
foreach (Measurement m : measurements) {
field.add(m);
}
// SECTION 3:
// Now the user wants to ask the model questions about the interpolated
// state of the model. For example, "what's the interpolated temperature
// at point (3, 4, 5)
Point3d p = new Point3d(3, 4, 5);
Measurement result = field.interpolateAt(p);
</code></pre>
<p>For my particular problem domain, it will be possible to perform a small amount of incremental work (partitioning the points into a balanced KDTree) during SECTION 2.</p>
<p>And there will be a small amount of work (performing some linear interpolations) that can occur during SECTION 3.</p>
<p>But there's a huge amount of work (constructing a kernel density estimator and performing a Fast Gauss Transform, using Taylor series and Hermite functions, but that's totally beside the point) that must be performed <strong>between</strong> sections 2 and 3.</p>
<p>Sometimes in the past, I've just used lazy-evaluation to construct the data structures (in this case, it'd be on the first invocation of the "interpolateAt" method), but then if the user calls the "field.add()" method again, I have to completely discard those data structures and start over from scratch.</p>
<p>In other projects, I've required the user to explicitly call an "object.flip()" method, to switch from "append mode" into "query mode". The nice this about a design like this is that the user has better control over the exact moment when the hard-core computation starts. But it can be a nuisance for the API consumer to keep track of the object's current mode. And besides, in the standard use case, the caller never adds another value to the collection after starting to issue queries; data-aggregation almost always fully precedes query preparation.</p>
<p>How have you guys handled designing a data structure like this?</p>
<p>Do you prefer to let an object lazily perform its heavy-duty analysis, throwing away the intermediate data structures when new data comes into the collection? Or do you require the programmer to explicitly flip the data structure from from append-mode into query-mode?</p>
<p>And do you know of any naming convention for objects like this? Is there a pattern I'm not thinking of?</p>
<hr>
<p>ON EDIT:</p>
<p>There seems to be some confusion and curiosity about the class I used in my example, named "ContinuousScalarField".</p>
<p>You can get a pretty good idea for what I'm talking about by reading these wikipedia pages:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/Scalar_field" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Scalar_field</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Vector_field" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Vector_field</a></p></li>
</ul>
<p>Let's say you wanted to create a topographical map (this is not my exact problem, but it's conceptually very similar). So you take a thousand altitude measurements over an area of one square mile, but your survey equipment has a margin of error of plus-or-minus 10 meters in elevation.</p>
<p>Once you've gathered all the data points, you feed them into a model which not only interpolates the values, but also takes into account the error of each measurement.</p>
<p>To draw your topo map, you query the model for the elevation of each point where you want to draw a pixel.</p>
<p>As for the question of whether a single class should be responsible for both appending and handling queries, I'm not 100% sure, but I think so.</p>
<p>Here's a similar example: HashMap and TreeMap classes allow objects to be both added and queried. There aren't separate interfaces for adding and querying.</p>
<p>Both classes are also similar to my example, because the internal data structures have to be maintained on an ongoing basis in order to support the query mechanism. The HashMap class has to periodically allocate new memory, re-hash all objects, and move objects from the old memory to the new memory. A TreeMap has to continually maintain tree balance, using the red-black-tree data structure.</p>
<p>The only difference is that my class will perform optimally if it can perform all of its calculations once it knows the data set is closed.</p>
|
[
{
"answer_id": 247891,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "<p>Your objects should have one role and responsibility. In your case should the ContinuousScalarField be responsible for interpolating?</p>\n\n<p>Perhaps you might be better off doing something like:</p>\n\n<pre><code>IInterpolator interpolator = field.GetInterpolator();\nMeasurement measurement = Interpolator.InterpolateAt(...);\n</code></pre>\n\n<p>I hope this makes sense, but without fully understanding your problem domain it's hard to give you a more coherent answer.</p>\n"
},
{
"answer_id": 247906,
"author": "Tim Robinson",
"author_id": 32133,
"author_profile": "https://Stackoverflow.com/users/32133",
"pm_score": 2,
"selected": false,
"text": "<p>If an object has two modes like this, I would suggest exposing two interfaces to the client. If the object is in append mode, then you make sure that the client can only ever use the IAppendable implementation. To flip to query mode, you add a method to IAppendable such as AsQueryable. To flip back, call IQueryable.AsAppendable.</p>\n\n<p>You can implement IAppendable and IQueryable on the same object, and keep track of the state in the same way internally, but having two interfaces makes it clear to the client what state the object is in, and forces the client to deliberately make the (expensive) switch.</p>\n"
},
{
"answer_id": 247911,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": -1,
"selected": false,
"text": "<p>You could have a state variable. Have a method for starting the high level processing, which will only work if the STATE is in SECTION-1. It will set the state to SECTION-2, and then to SECTION-3 when it is done computing. If there's a request to the program to interpolate a given point, it will check if the state is SECTION-3. If not, it will request the computations to begin, and then interpolate the given data.</p>\n\n<p>This way, you accomplish both - the program will perform its computations at the first request to interpolate a point, but can also be requested to do so earlier. This would be convenient if you wanted to run the computations overnight, for example, without needing to request an interpolation.</p>\n"
},
{
"answer_id": 247973,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>\"I've just used lazy-evaluation to construct the data structures\" -- <em>Good</em></p>\n\n<p>\"if the user calls the \"field.add()\" method again, I have to completely discard those data structures and start over from scratch.\" -- <em>Interesting</em></p>\n\n<p>\"in the standard use case, the caller never adds another value to the collection after starting to issue queries\" -- <em>Whoops, false alarm, actually not interesting</em>.</p>\n\n<p>Since lazy eval fits your use case, stick with it. That's a very heavily used model because it is so delightfully reliable and fits most use cases very well.</p>\n\n<p>The only reason for rethinking this is (a) the use case change (mixed adding and interpolation), or (b) performance optimization.</p>\n\n<p>Since use case changes are unlikely, you might consider the performance implications of breaking up interpolation. For example, during idle time, can you precompute some values? Or with each add is there a summary you can update?</p>\n\n<p>Also, a highly stateful (and not very meaningful) <code>flip</code> method isn't so useful to clients of your class. However, breaking interpolation into two parts might still be helpful to them -- and help you with optimization and state management.</p>\n\n<p>You could, for example, break interpolation into two methods.</p>\n\n<pre><code>public void interpolateAt( Point3d p );\npublic Measurement interpolatedMasurement();\n</code></pre>\n\n<p>This borrows the relational database Open and Fetch paradigm. Opening a cursor can do a lot of preliminary work, and may start executing the query, you don't know. Fetching the first row may do all the work, or execute the prepared query, or simply fetch the first buffered row. You don't really know. You only know that it's a two part operation. The RDBMS developers are free to optimize as they see fit.</p>\n"
},
{
"answer_id": 247985,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "<p>I generally prefer to have an explicit change, rather than lazily recomputing the result. This approach makes the performance of the utility more predictable, and it reduces the amount of work I have to do to provide a good user experience. For example, if this occurs in a UI, where do I have to worry about popping up an hourglass, etc.? Which operations are going to block for a variable amount of time, and need to be performed in a background thread?</p>\n\n<p>That said, rather than explicitly changing the state of one instance, I would recommend the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder Pattern</a> to produce a new object. For example, you might have an aggregator object that does a small amount of work as you add each sample. Then instead of your proposed <code>void flip()</code> method, I'd have a <code>Interpolator interpolator()</code> method that gets a copy of the current aggregation and performs all your heavy-duty math. Your <code>interpolateAt</code> method would be on this new Interpolator object.</p>\n\n<p>If your usage patterns warrant, you could do simple caching by keeping a reference to the interpolator you create, and return it to multiple callers, only clearing it when the aggregator is modified.</p>\n\n<p>This separation of responsibilities can help yield more maintainable and reusable object-oriented programs. An object that can return a <code>Measurement</code> at a requested <code>Point</code> is very abstract, and perhaps a lot of clients could use your Interpolator as one strategy implementing a more general interface.</p>\n\n<hr>\n\n<p>I think that the analogy you added is misleading. Consider an alternative analogy:</p>\n\n<pre><code>Key[] data = new Key[...];\ndata[idx++] = new Key(...); /* Fast! */\n...\nArrays.sort(data); /* Slow! */\n...\nboolean contains = Arrays.binarySearch(data, datum) >= 0; /* Fast! */\n</code></pre>\n\n<p>This can work like a set, and actually, it gives better performance than <code>Set</code> implementations (which are implemented with hash tables or balanced trees). </p>\n\n<p>A balanced tree can be seen as an efficient implementation of insertion sort. After every insertion, the tree is in a sorted state. The predictable time requirements of a balanced tree are due to the fact the cost of sorting is spread over each insertion, rather than happening on some queries and not others. </p>\n\n<p>The rehashing of hash tables does result in less consistent performance, and because of that, aren't appropriate for certain applications (perhaps a real-time microcontroller). But even the rehashing operation depends only on the load factor of the table, not the pattern of insertion and query operations.</p>\n\n<p>For your analogy to hold strictly, you would have to \"sort\" (do the hairy math) your aggregator with each point you add. But it sounds like that would be cost prohibitive, and that leads to the builder or factory method patterns. This makes it clear to your clients when they need to be prepared for the lengthy \"sort\" operation.</p>\n"
},
{
"answer_id": 13498390,
"author": "David Cary",
"author_id": 238320,
"author_profile": "https://Stackoverflow.com/users/238320",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Do you prefer to let an object lazily perform its heavy-duty analysis,\n throwing away the intermediate data structures when new data comes\n into the collection? Or do you require the programmer to explicitly\n flip the data structure from from append-mode into query-mode?</p>\n</blockquote>\n\n<p>I prefer using data structures that allow me to incrementally add to it with \"a little more work\" per addition, and to incrementally pull the data I need with \"a little more work\" per extraction.</p>\n\n<p>Perhaps if you do some \"interpolate_at()\" call in the upper-right corner of your region, you only need to do calculations involving the points in that upper-right corner,\nand it doesn't hurt anything to leave the other 3 quadrants \"open\" to new additions.\n(And so on down the recursive KDTree).</p>\n\n<p>Alas, that's not always possible -- sometimes the only way to add more data is to throw away all the previous intermediate and final results, and re-calculate everything again from scratch.</p>\n\n<p>The people who use the interfaces I design -- in particular, me -- are human and fallible.\nSo I don't like using objects where those people <em>must</em> remember to do things in a certain way, or else things go wrong -- because I'm always forgetting those things.</p>\n\n<p>If an object <em>must</em> be in the \"post-calculation state\" before getting data out of it,\ni.e. some \"do_calculations()\" function <em>must</em> be run before the interpolateAt() function gets valid data,\nI much prefer letting the interpolateAt() function check if it's already in that state,\nrunning \"do_calculations()\" and updating the state of the object if necessary,\nand then returning the results I expected.</p>\n\n<p>Sometimes I hear people describe such a data structure as \"freeze\" the data or \"crystallize\" the data or \"compile\" or \"put the data into an immutable data structure\".\nOne example is converting a (mutable) StringBuilder or StringBuffer into an (immutable) String.</p>\n\n<p>I can imagine that for some kinds of analysis, you expect to have <em>all</em> the data ahead of time,\nand pulling out some interpolated value before all the data has put in would give <em>wrong</em> results.\nIn that case, \nI'd prefer to set things up such that the \"add_data()\" function fails or throws an exception\nif it (incorrectly) gets called after any interpolateAt() call.</p>\n\n<p>I would consider defining a lazily-evaluated \"interpolated_point\" object that doesn't <em>really</em> evaluate the data right away, but only tells that program that sometime in the future that data at that point will be required.\nThe collection isn't actually frozen, so it's OK to continue adding more data to it,\nup until the point something actually extract the first real value from some \"interpolated_point\" object,\nwhich internally triggers the \"do_calculations()\" function and freezes the object.\nIt might speed things up if you know not only all the data, but also all the points that need to be interpolated, all ahead of time.\nThen you can throw away data that is \"far away\" from the interpolated points,\nand only do the heavy-duty calculations in regions \"near\" the interpolated points.</p>\n\n<p>For other kinds of analysis, you do the best you can with the data you have, but when more data comes in later, you want to use that new data in your later analysis.\nIf the only way to do that is to throw away all the intermediate results and recalculate everything from scratch, then that's what you have to do.\n(And it's best if the object automatically handled this, rather than requiring people to remember to call some \"clear_cache()\" and \"do_calculations()\" function every time).</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22979/"
] |
I'm trying to think of a naming convention that accurately conveys what's going on within a class I'm designing. On a secondary note, I'm trying to decide between two almost-equivalent user APIs.
Here's the situation:
I'm building a scientific application, where one of the central data structures has three phases: 1) accumulation, 2) analysis, and 3) query execution.
In my case, it's a spatial modeling structure, internally using a KDTree to partition a collection of points in 3-dimensional space. Each point describes one or more attributes of the surrounding environment, with a certain level of confidence about the measurement itself.
After adding (a potentially large number of) measurements to the collection, the owner of the object will query it to obtain an interpolated measurement at a new data point somewhere within the applicable field.
The API will look something like this (the code is in Java, but that's not really important; the code is divided into three sections, for clarity):
```
// SECTION 1:
// Create the aggregation object, and get the zillion objects to insert...
ContinuousScalarField field = new ContinuousScalarField();
Collection<Measurement> measurements = getMeasurementsFromSomewhere();
// SECTION 2:
// Add all of the zillion objects to the aggregation object...
// Each measurement contains its xyz location, the quantity being measured,
// and a numeric value for the measurement. For example, something like
// "68 degrees F, plus or minus 0.5, at point 1.23, 2.34, 3.45"
foreach (Measurement m : measurements) {
field.add(m);
}
// SECTION 3:
// Now the user wants to ask the model questions about the interpolated
// state of the model. For example, "what's the interpolated temperature
// at point (3, 4, 5)
Point3d p = new Point3d(3, 4, 5);
Measurement result = field.interpolateAt(p);
```
For my particular problem domain, it will be possible to perform a small amount of incremental work (partitioning the points into a balanced KDTree) during SECTION 2.
And there will be a small amount of work (performing some linear interpolations) that can occur during SECTION 3.
But there's a huge amount of work (constructing a kernel density estimator and performing a Fast Gauss Transform, using Taylor series and Hermite functions, but that's totally beside the point) that must be performed **between** sections 2 and 3.
Sometimes in the past, I've just used lazy-evaluation to construct the data structures (in this case, it'd be on the first invocation of the "interpolateAt" method), but then if the user calls the "field.add()" method again, I have to completely discard those data structures and start over from scratch.
In other projects, I've required the user to explicitly call an "object.flip()" method, to switch from "append mode" into "query mode". The nice this about a design like this is that the user has better control over the exact moment when the hard-core computation starts. But it can be a nuisance for the API consumer to keep track of the object's current mode. And besides, in the standard use case, the caller never adds another value to the collection after starting to issue queries; data-aggregation almost always fully precedes query preparation.
How have you guys handled designing a data structure like this?
Do you prefer to let an object lazily perform its heavy-duty analysis, throwing away the intermediate data structures when new data comes into the collection? Or do you require the programmer to explicitly flip the data structure from from append-mode into query-mode?
And do you know of any naming convention for objects like this? Is there a pattern I'm not thinking of?
---
ON EDIT:
There seems to be some confusion and curiosity about the class I used in my example, named "ContinuousScalarField".
You can get a pretty good idea for what I'm talking about by reading these wikipedia pages:
* <http://en.wikipedia.org/wiki/Scalar_field>
* <http://en.wikipedia.org/wiki/Vector_field>
Let's say you wanted to create a topographical map (this is not my exact problem, but it's conceptually very similar). So you take a thousand altitude measurements over an area of one square mile, but your survey equipment has a margin of error of plus-or-minus 10 meters in elevation.
Once you've gathered all the data points, you feed them into a model which not only interpolates the values, but also takes into account the error of each measurement.
To draw your topo map, you query the model for the elevation of each point where you want to draw a pixel.
As for the question of whether a single class should be responsible for both appending and handling queries, I'm not 100% sure, but I think so.
Here's a similar example: HashMap and TreeMap classes allow objects to be both added and queried. There aren't separate interfaces for adding and querying.
Both classes are also similar to my example, because the internal data structures have to be maintained on an ongoing basis in order to support the query mechanism. The HashMap class has to periodically allocate new memory, re-hash all objects, and move objects from the old memory to the new memory. A TreeMap has to continually maintain tree balance, using the red-black-tree data structure.
The only difference is that my class will perform optimally if it can perform all of its calculations once it knows the data set is closed.
|
I generally prefer to have an explicit change, rather than lazily recomputing the result. This approach makes the performance of the utility more predictable, and it reduces the amount of work I have to do to provide a good user experience. For example, if this occurs in a UI, where do I have to worry about popping up an hourglass, etc.? Which operations are going to block for a variable amount of time, and need to be performed in a background thread?
That said, rather than explicitly changing the state of one instance, I would recommend the [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern) to produce a new object. For example, you might have an aggregator object that does a small amount of work as you add each sample. Then instead of your proposed `void flip()` method, I'd have a `Interpolator interpolator()` method that gets a copy of the current aggregation and performs all your heavy-duty math. Your `interpolateAt` method would be on this new Interpolator object.
If your usage patterns warrant, you could do simple caching by keeping a reference to the interpolator you create, and return it to multiple callers, only clearing it when the aggregator is modified.
This separation of responsibilities can help yield more maintainable and reusable object-oriented programs. An object that can return a `Measurement` at a requested `Point` is very abstract, and perhaps a lot of clients could use your Interpolator as one strategy implementing a more general interface.
---
I think that the analogy you added is misleading. Consider an alternative analogy:
```
Key[] data = new Key[...];
data[idx++] = new Key(...); /* Fast! */
...
Arrays.sort(data); /* Slow! */
...
boolean contains = Arrays.binarySearch(data, datum) >= 0; /* Fast! */
```
This can work like a set, and actually, it gives better performance than `Set` implementations (which are implemented with hash tables or balanced trees).
A balanced tree can be seen as an efficient implementation of insertion sort. After every insertion, the tree is in a sorted state. The predictable time requirements of a balanced tree are due to the fact the cost of sorting is spread over each insertion, rather than happening on some queries and not others.
The rehashing of hash tables does result in less consistent performance, and because of that, aren't appropriate for certain applications (perhaps a real-time microcontroller). But even the rehashing operation depends only on the load factor of the table, not the pattern of insertion and query operations.
For your analogy to hold strictly, you would have to "sort" (do the hairy math) your aggregator with each point you add. But it sounds like that would be cost prohibitive, and that leads to the builder or factory method patterns. This makes it clear to your clients when they need to be prepared for the lengthy "sort" operation.
|
247,858 |
<p>In T-SQL, you can do this:</p>
<pre><code>SELECT ProductId, COALESCE(Price, 0)
FROM Products
</code></pre>
<p>How do you do the same thing in Access SQL? I see examples for doing it with Nz in VBA, but I'm looking for the SQL equivalent.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 247869,
"author": "pipTheGeek",
"author_id": 28552,
"author_profile": "https://Stackoverflow.com/users/28552",
"pm_score": 6,
"selected": true,
"text": "<p>Access supports the <code>Nz</code> function and allows you to use it in a query. Note though that <code>Nz</code> is the same as the T-SQL <code>ISNULL</code> function. It can not take an arbitrary number of parameters like <code>COALESCE</code> can.</p>\n"
},
{
"answer_id": 247872,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "<p>If it's in an Access query, you can try this:</p>\n\n<pre><code>\"Price = IIf([Price] Is Null,0,[Price])\"\n</code></pre>\n"
},
{
"answer_id": 247880,
"author": "Nathan DeWitt",
"author_id": 1753,
"author_profile": "https://Stackoverflow.com/users/1753",
"pm_score": 3,
"selected": false,
"text": "<p>Looks like I can just use:</p>\n\n<pre><code>SELECT ProductId, Nz(Price, 0)\nFROM Products\n</code></pre>\n\n<p>Seems to be working just fine.</p>\n"
},
{
"answer_id": 23369347,
"author": "Art Mendenhall",
"author_id": 3585999,
"author_profile": "https://Stackoverflow.com/users/3585999",
"pm_score": 1,
"selected": false,
"text": "<p>Using <code>IsNull()</code>, <code>Nz()</code>, and the data conversion functions are built-in VBA functions and will only slow down your queries in versions prior to 2003. As far as datatyping goes use <code>CCur()</code> to guarantee your data type, but only if you need to do strong comparisons or simply set the format property to Currency on the column. It is the IF statement that slows things the most, as it adds yet another function to your routine</p>\n\n<p>using this solution: <code>Nz([Price], CCur(0))</code></p>\n\n<p>the only time <code>CCur()</code> will execute is when Price Is Null, so overall this is probably the fastest.</p>\n\n<p>The point is that the <em>least number of total functions used</em>, the faster your queries will execute.</p>\n"
},
{
"answer_id": 27714315,
"author": "user4406949",
"author_id": 4406949,
"author_profile": "https://Stackoverflow.com/users/4406949",
"pm_score": -1,
"selected": false,
"text": "<p>COALESCE or NULLIF function are the standard used on sql server for a good migration to access. ISNULLor IIF or CHOOSE are nonstandard function.</p>\n"
},
{
"answer_id": 40508353,
"author": "iDevlop",
"author_id": 78522,
"author_profile": "https://Stackoverflow.com/users/78522",
"pm_score": 3,
"selected": false,
"text": "<p>Using <code>Iif(Price is null, 0, Price)</code> should give you the best performance (see <a href=\"http://allenbrowne.com/QueryPerfIssue.html\" rel=\"nofollow noreferrer\">Allen Browne's performance tips</a>). However SQL Server <code>Coalesce()</code> has the great advantage over <code>Iif()</code> and <code>Nz()</code> that it can handle several parameters in a cascade. So I created this quick VBA equivalent:</p>\n\n<pre><code>Function Coalesce(ParamArray varValues()) As Variant\n'returns the first non null value, similar to SQL Server Coalesce() function\n'Patrick Honorez --- www.idevlop.com\n Dim i As Long\n Coalesce = Null\n For i = LBound(varValues) To UBound(varValues)\n If Not IsNull(varValues(i)) Then\n Coalesce = varValues(i)\n Exit Function\n End If\n Next\nEnd Function\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753/"
] |
In T-SQL, you can do this:
```
SELECT ProductId, COALESCE(Price, 0)
FROM Products
```
How do you do the same thing in Access SQL? I see examples for doing it with Nz in VBA, but I'm looking for the SQL equivalent.
Thanks.
|
Access supports the `Nz` function and allows you to use it in a query. Note though that `Nz` is the same as the T-SQL `ISNULL` function. It can not take an arbitrary number of parameters like `COALESCE` can.
|
247,875 |
<p>When is memory allocated in the .NET compact framework? If there is a difference between value and reference types, please detail. Documentation or steps to confirm are appreciated.</p>
<p>In particular, consider this scenario...</p>
<pre><code>private MyClass item; // here?
public void MyMethod()
{
item = new MyClass(); // or here?
}
</code></pre>
|
[
{
"answer_id": 247898,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 4,
"selected": true,
"text": "<p>There are 3 different ways memory is allocated.</p>\n\n<p><strong>Static:</strong></p>\n\n<p>These are bound and allocated at compile time. Global static variables for example.</p>\n\n<p><strong>Stack Dynamic:</strong></p>\n\n<p>These are bound during runtime and pushed onto the stack. Such as a local variable in a function call.</p>\n\n<p><strong>Heap Dynamic:</strong></p>\n\n<p>Now heap dynamic also has a few different 'sub categories' such as implicit and explicit, but I won't go into that detail. </p>\n\n<p>When you declare</p>\n\n<pre><code>private MyClass item; // here?\n</code></pre>\n\n<p>a reference to MyClass is pushed onto the stack. It is only a reference and nothing more. Its value is null at that point.</p>\n\n<pre><code>public void MyMethod()\n{\n item = new MyClass(); // or here?\n}\n</code></pre>\n\n<p>It is at that point where memory is explicitly allocated on the heap by calling 'new MyClass()' and item then references it.</p>\n\n<p>So in actuality, you have 2 variables after you call MyMethod. A refernce type named item, and an unnamed variable on the heap which item references that is of type MyClass.</p>\n"
},
{
"answer_id": 247926,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>This is something of a trick question, which makes me like it a lot more than I thought I would. :)</p>\n\n<p>Let's start with the basics:</p>\n\n<p>Declaring a variable does not directly allocate memory* for it on reference types. It <strong>does</strong> do so on value types, because value types are initialized at the point of declaration. For reference types, storage for the object is allocated at the point of entering their constructors.</p>\n\n<p>*When does this not apply? </p>\n\n<ul>\n<li>On the first usage of a given class (which may well be your first line), any class-level static data is initialized, and if the class has a static constructor (which presumably allocates memory), it will be called as well. Therefore, you may actually allocate some memory (for the static members) at a variable declaration.</li>\n<li>Technically, declaring your reference type variable <strong>does</strong> allocate some memory, on the stack (as Nicholas Mancuso mentioned) -- the memory allocated is the stack-level storage for the reference to the object. (Admittedly, said reference is <code>null</code>, but once you initialize your object, a valid reference will exist in the allocated memory.)</li>\n</ul>\n\n<p>I highly recommend this <a href=\"http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91\" rel=\"nofollow noreferrer\">C-Sharp Corner article</a> regarding stack and heap allocation for more information.</p>\n"
},
{
"answer_id": 248785,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 0,
"selected": false,
"text": "<p>I highly recommend that you look at the MSDN Webcase on <a href=\"https://msevents.microsoft.com/cui/WebCastRegistrationConfirmation.aspx?culture=en-US&RegistrationID=1299365950&Validate=false\" rel=\"nofollow noreferrer\">Compact Framework Memory Management</a>. It's not exactly the same as how it works on the desktop, and this talk covers it with a whole lot of detail and graphics to aid in understanding the GC Heap.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] |
When is memory allocated in the .NET compact framework? If there is a difference between value and reference types, please detail. Documentation or steps to confirm are appreciated.
In particular, consider this scenario...
```
private MyClass item; // here?
public void MyMethod()
{
item = new MyClass(); // or here?
}
```
|
There are 3 different ways memory is allocated.
**Static:**
These are bound and allocated at compile time. Global static variables for example.
**Stack Dynamic:**
These are bound during runtime and pushed onto the stack. Such as a local variable in a function call.
**Heap Dynamic:**
Now heap dynamic also has a few different 'sub categories' such as implicit and explicit, but I won't go into that detail.
When you declare
```
private MyClass item; // here?
```
a reference to MyClass is pushed onto the stack. It is only a reference and nothing more. Its value is null at that point.
```
public void MyMethod()
{
item = new MyClass(); // or here?
}
```
It is at that point where memory is explicitly allocated on the heap by calling 'new MyClass()' and item then references it.
So in actuality, you have 2 variables after you call MyMethod. A refernce type named item, and an unnamed variable on the heap which item references that is of type MyClass.
|
247,909 |
<p>I have a lot of constants that are somehow related, at some point I need to pair them, something like this:</p>
<pre><code>const
key1 = '1';
key2 = '2';
key3 = '3';
value1 = 'a';
value2 = 'b';
value3 = 'c';
</code></pre>
<p>I want to avoid doing:</p>
<pre><code>if MyValue = key1 then Result := value1;
</code></pre>
<p>I know how to do it with string lists using:</p>
<pre><code>MyStringList.Add(key1 + '=' + value1);
Result := MyStringList.Values[key1];
</code></pre>
<p>But, is there any simpler way to do this?</p>
|
[
{
"answer_id": 247935,
"author": "Jozz",
"author_id": 12351,
"author_profile": "https://Stackoverflow.com/users/12351",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, assignment can be done this way instead, avoiding manual string concatenation:</p>\n\n<pre><code>MyStringList.Values[Key1] := Value1;\n</code></pre>\n"
},
{
"answer_id": 247960,
"author": "vIceBerg",
"author_id": 17766,
"author_profile": "https://Stackoverflow.com/users/17766",
"pm_score": 2,
"selected": false,
"text": "<p>Do a wrapper around your \"value\"</p>\n\n<pre>\nTMyValue = class\n value: String;\nend;</pre>\n\n<p>Then use this:</p>\n\n<pre>\nmyValue := TMyValue.Create;\nmyValue.Value = Value1;\n\nMyStringList.AddObject(Key1, Value1);\n</pre>\n\n<p>Then, you can sort your list, do a IndexOf(Key1) and retrieve the object.</p>\n\n<p>That way, your list is sorted and the search is very fast.</p>\n"
},
{
"answer_id": 255070,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a multi-dimensional constant array with an enumeration for at least one of the dimensions:</p>\n\n<p>Define it like this:</p>\n\n<pre><code>type\n TKVEnum = (tKey, tValue); // You could give this a better name\nconst\n Count = 3;\n KeyValues: array [1..Count, TKVEnum] of string =\n // This is each of your name / value paris\n (('1', 'a'), ('2', 'b'), ('3', 'd')); \n</code></pre>\n\n<p>Then you use it like this:</p>\n\n<pre><code>if MyValue = KeyValues[1, TKVEnum.tKey] then \n Result := KeyValues[1, TKVEnum.tValue]\n</code></pre>\n\n<p>You could use a <strong>For</strong> loop on it too. This is just as efficient as doing them as individual constant strings, but gives you the added advantage that they are intrinsically associated. </p>\n\n<p>Instead of defining the first dimension numerically, I would suggest </p>\n\n<pre><code>type\n TConstPairs = (tcUsername, tcDatabase, tcEtcetera);\n</code></pre>\n\n<p>But I guess that totally depends on what you constants represent.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
I have a lot of constants that are somehow related, at some point I need to pair them, something like this:
```
const
key1 = '1';
key2 = '2';
key3 = '3';
value1 = 'a';
value2 = 'b';
value3 = 'c';
```
I want to avoid doing:
```
if MyValue = key1 then Result := value1;
```
I know how to do it with string lists using:
```
MyStringList.Add(key1 + '=' + value1);
Result := MyStringList.Values[key1];
```
But, is there any simpler way to do this?
|
Yes, assignment can be done this way instead, avoiding manual string concatenation:
```
MyStringList.Values[Key1] := Value1;
```
|
247,918 |
<p>I have two combos; provinces and cities.
I would like to change cities value when the province combo value changes. Here is my code</p>
<pre><code><div class="cities form">
<?php
$v = $ajax->remoteFunction(array('url' => '/cities/','update' => 'divcity'));
print $form-> input('Province.province_id', array('type' => 'select', 'options'=> $provinces, 'onChange' => $v));
?>
<div id="divcity">
<?php
echo $form->input('Cities.cities_name');
?>
</div>
</code></pre>
<p>Every time I change province combo, it call <code>cities/index.ctp</code>. anybody want to help?
really thank for your help
wawan</p>
|
[
{
"answer_id": 248206,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 2,
"selected": false,
"text": "<p>The 'url' => '/cities/' is calling the default index action of the cities controller.</p>\n\n<p>This automatically renders the cities/index.ctp view.</p>\n\n<p>Have you included the RequestHandler component in the cities controller?</p>\n\n<p>This can be used to detect Ajax requests and then render a different view.</p>\n"
},
{
"answer_id": 282684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You need to first include the <a href=\"http://book.cakephp.org/view/174/Request-Handling\" rel=\"nofollow noreferrer\">RequestHandler Component</a> at the top of the CitiesController, then write a function to list cities, optionally requiring a Province's id.</p>\n\n<p>I think you'll end up having something like this:</p>\n\n<pre><code><?php\n// In the view\n$v = $ajax->remoteFunction(array('url' => '/cities/list','update' => 'divcity'));\nprint $form-> input('Province.province_id', array('type' => 'select', 'options'=> $provinces, 'onChange' => $v));\n\n// In CitiesController\nfunction list($province_id = null) {\n // use $this->City->find('list', array('fields'=>array('City.id', 'City.name'))) \n // to generate a list of cities, based on the providence id if required\n if($this->RequestHandler->isAjax()) {\n $this->layout = 'ajax';\n $this->render();\n }\n} ?>\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have two combos; provinces and cities.
I would like to change cities value when the province combo value changes. Here is my code
```
<div class="cities form">
<?php
$v = $ajax->remoteFunction(array('url' => '/cities/','update' => 'divcity'));
print $form-> input('Province.province_id', array('type' => 'select', 'options'=> $provinces, 'onChange' => $v));
?>
<div id="divcity">
<?php
echo $form->input('Cities.cities_name');
?>
</div>
```
Every time I change province combo, it call `cities/index.ctp`. anybody want to help?
really thank for your help
wawan
|
The 'url' => '/cities/' is calling the default index action of the cities controller.
This automatically renders the cities/index.ctp view.
Have you included the RequestHandler component in the cities controller?
This can be used to detect Ajax requests and then render a different view.
|
247,922 |
<p>I have the following code in my Django application:</p>
<pre><code>if 'book' in authorForm.changed_data:
#Do something here...
</code></pre>
<p>I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 248200,
"author": "Alex Koshelev",
"author_id": 19772,
"author_profile": "https://Stackoverflow.com/users/19772",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm... Try this:</p>\n\n<pre><code>if authorForm.is_valid() and 'book' in authorForm.changed_data:\n new_value = authorForm.cleaned_data['book']\n</code></pre>\n"
},
{
"answer_id": 3086204,
"author": "Huuuze",
"author_id": 10040,
"author_profile": "https://Stackoverflow.com/users/10040",
"pm_score": 1,
"selected": true,
"text": "<p>The short answer to my original question is \"No\".</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
I have the following code in my Django application:
```
if 'book' in authorForm.changed_data:
#Do something here...
```
I realize Django can tell me which values have changed in my form by utilizing the "changed\_data" list object, but I'd like to know the new values of the fields that have changed.
Any thoughts?
|
The short answer to my original question is "No".
|
247,929 |
<p>I have to connect my rails app in a legacy Postgre database. It uses schemas so in a SQL its is common to use something like </p>
<pre><code>SELECT * FROM "Financial".budget
</code></pre>
<p>I want to write a Budget model but I don't know how to set the table name in this case. I've tried the following:</p>
<ul>
<li>set_table_name 'budget'</li>
<li>set_table_name '"Financial".budget'</li>
</ul>
<p>None have worket.</p>
|
[
{
"answer_id": 248729,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 0,
"selected": false,
"text": "<p>Look at your logs -- what SQL is Rails generating with your various options?</p>\n"
},
{
"answer_id": 248788,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 0,
"selected": false,
"text": "<pre><code>set_table_name \"Financial.budget\"\n</code></pre>\n"
},
{
"answer_id": 251151,
"author": "Patryk Kordylewski",
"author_id": 30927,
"author_profile": "https://Stackoverflow.com/users/30927",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps extending the search path with your schema will help you?</p>\n\n<pre><code>SET SEARCH_PATH TO \"Financial\", public;\n</code></pre>\n\n<p>Then you could write your query unqualified without the schema:</p>\n\n<pre><code>SELECT * FROM budget;\n</code></pre>\n"
},
{
"answer_id": 275162,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 2,
"selected": false,
"text": "<p>I had similar issue with Oracle adapter. By default ActiveRecord always quotes table names in SQL and therefore if you specify</p>\n\n<pre><code>set_table_name \"Financial.budget\"\n</code></pre>\n\n<p>then generated SQL will be</p>\n\n<pre><code>SELECT * FROM \"Financial.budget\"\n</code></pre>\n\n<p>which will not work.</p>\n\n<p>To solve this issue you need to monkey patch PostgreSQL adapter. Put into your environment.rb or in separate initializer the following code:</p>\n\n<pre><code>ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do\n # abstract_adapter calls quote_column_name from quote_table_name, so prevent that\n def quote_table_name(name)\n name\n end\nend\n</code></pre>\n\n<p>Now you should define in your model class</p>\n\n<pre><code>set_table_name \"Financial.budget\"\n</code></pre>\n\n<p>and generated SQL will be</p>\n\n<pre><code>SELECT * FROM Financial.budget\n</code></pre>\n"
},
{
"answer_id": 797592,
"author": "Ricardo Acras",
"author_id": 19224,
"author_profile": "https://Stackoverflow.com/users/19224",
"pm_score": 3,
"selected": true,
"text": "<p>Now, this bug seems to be solved in 2-3-stable. Take a look at <a href=\"http://weblog.rubyonrails.org/2009/4/24/this-week-in-edge-rails\" rel=\"nofollow noreferrer\">this post</a></p>\n"
},
{
"answer_id": 3239094,
"author": "Sam",
"author_id": 42059,
"author_profile": "https://Stackoverflow.com/users/42059",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ActiveRecord::Base.establish_connection(\n :schema_search_path => 'Financial,public'\n)\n</code></pre>\n\n<p>If you're using Postgres, the above is probably \"good enough\" for most situations.</p>\n"
},
{
"answer_id": 12316228,
"author": "Sergey Potapov",
"author_id": 1013173,
"author_profile": "https://Stackoverflow.com/users/1013173",
"pm_score": 0,
"selected": false,
"text": "<p>We designed a gem to make ActiveRecord work with PostgreSQL. Here is a small usage example:\n<a href=\"http://greyblake.com/blog/2012/09/06/pg-power-activerecord-extension-for-postgresql/\" rel=\"nofollow\">http://greyblake.com/blog/2012/09/06/pg-power-activerecord-extension-for-postgresql/</a></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
I have to connect my rails app in a legacy Postgre database. It uses schemas so in a SQL its is common to use something like
```
SELECT * FROM "Financial".budget
```
I want to write a Budget model but I don't know how to set the table name in this case. I've tried the following:
* set\_table\_name 'budget'
* set\_table\_name '"Financial".budget'
None have worket.
|
Now, this bug seems to be solved in 2-3-stable. Take a look at [this post](http://weblog.rubyonrails.org/2009/4/24/this-week-in-edge-rails)
|
247,936 |
<p>Lately I've been in the habit of assigning integer values to constants and simply using the constant name as a means of identifying its purpose. However, in some cases this has resulted in the need to write a function like typeToString($const) when a string representation is needed. Obviously this is inefficient and unneccesary, but is only an issue every once and a while.</p>
<p>So my question is, are there any other tradeoffs I should consider? Which case is considered to be cleaner/more standards-compliant? Also, is the performance difference negligable for most cases?</p>
<p><strong>Case 1: (faster when a string version is not needed?)</strong></p>
<pre><code>class Foo {
const USER_TYPE_ADMIN = 0;
const USER_TYPE_USER = 1;
const USER_TYPE_GUEST = 2;
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
public function typeToString() {
switch($this->userType) {
case self::USER_TYPE_ADMIN:
return 'admin';
break;
case self::USER_TYPE_USER:
return 'user';
break;
case self::USER_TYPE_GUEST:
return 'guest';
break;
default:
return 'unknown';
break;
}
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->typeToString();
// Displays "guest"
</code></pre>
<p><strong>Case 2:(faster/easier when a string version is needed)</strong></p>
<pre><code>class Foo {
const USER_TYPE_ADMIN = 'admin';
const USER_TYPE_USER = 'user';
const USER_TYPE_GUEST = 'guest';
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->userType();
// Displays "guest"
</code></pre>
|
[
{
"answer_id": 247945,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using const integers I generally just go with strings if I need to print them. So I'd do something like <code>$foo = new Foo('guest');</code>. I can still validate the input in the constructor and I can mark it up whenever I need it.</p>\n"
},
{
"answer_id": 247951,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": false,
"text": "<p>I'll be honest, I don't know if there's a performance \"hit\" of any kind when you define your constants natively as strings - but if there is one at all I'm willing to bet that it's so small it would be difficult to measure.</p>\n\n<p>Personally, if the constant's value is meaningful as a literal, then just assign it that value. If the constant's value is meaningful only as an option selector (or some other <em>indication</em> of value), then use integers or whatever you choose appropriate.</p>\n"
},
{
"answer_id": 247953,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 1,
"selected": false,
"text": "<p>I think string constants are the best choice in this case. Code looks better.</p>\n\n<p>Of course if you need last bit of performance, use integer constants. But only after you verify with a profiler that string comparisons are the bottleneck. Anyway, in most applications there are many more expensive things, like database access etc.</p>\n"
},
{
"answer_id": 247963,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<p>The performance difference will be negligible unless you're storing a lot of them.\nI'd write the <code>toString()</code> method more concisely:</p>\n\n<pre><code>$strings = array\n(\n self::USER_TYPE_ADMIN => 'admin',\n self::USER_TYPE_USER => 'user',\n);\n\nif (!isset($strings[$type]))\n return 'unknown';\n\nreturn $strings[$type];\n</code></pre>\n\n<p>Also, you could make the <code>$strings</code> array a <code>static</code>.</p>\n"
},
{
"answer_id": 248746,
"author": "Nikola Stjelja",
"author_id": 32582,
"author_profile": "https://Stackoverflow.com/users/32582",
"pm_score": -1,
"selected": false,
"text": "<p>In the example you write you could drop all the methods and make the class static and you would have created your self an Enumerator. Like this:</p>\n\n<pre>\nclass Enumeration{\n public static const One=1;\n public static const Two=2;\n public static const Three=3;\n}\n\n</pre>\n\n<p>One other handy way to use constants is to use them as application configuration. They are much faster performance wise then parsing an xml file for configuration.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
Lately I've been in the habit of assigning integer values to constants and simply using the constant name as a means of identifying its purpose. However, in some cases this has resulted in the need to write a function like typeToString($const) when a string representation is needed. Obviously this is inefficient and unneccesary, but is only an issue every once and a while.
So my question is, are there any other tradeoffs I should consider? Which case is considered to be cleaner/more standards-compliant? Also, is the performance difference negligable for most cases?
**Case 1: (faster when a string version is not needed?)**
```
class Foo {
const USER_TYPE_ADMIN = 0;
const USER_TYPE_USER = 1;
const USER_TYPE_GUEST = 2;
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
public function typeToString() {
switch($this->userType) {
case self::USER_TYPE_ADMIN:
return 'admin';
break;
case self::USER_TYPE_USER:
return 'user';
break;
case self::USER_TYPE_GUEST:
return 'guest';
break;
default:
return 'unknown';
break;
}
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->typeToString();
// Displays "guest"
```
**Case 2:(faster/easier when a string version is needed)**
```
class Foo {
const USER_TYPE_ADMIN = 'admin';
const USER_TYPE_USER = 'user';
const USER_TYPE_GUEST = 'guest';
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->userType();
// Displays "guest"
```
|
The performance difference will be negligible unless you're storing a lot of them.
I'd write the `toString()` method more concisely:
```
$strings = array
(
self::USER_TYPE_ADMIN => 'admin',
self::USER_TYPE_USER => 'user',
);
if (!isset($strings[$type]))
return 'unknown';
return $strings[$type];
```
Also, you could make the `$strings` array a `static`.
|
247,946 |
<p>I have a .NET UserControl (FFX 3.5). This control contains several child Controls - a Panel, a couple Labels, a couple TextBoxes, and yet another custom Control. I want to handle a right click anywhere on the base Control - so a right click on any child control (or child of a child in the case of the Panel). I'd like to do it so that it's maintainable if someone makes changes to the Control without having to wire in handlers for new Controls for example.</p>
<p>First I tried overriding the WndProc, but as I suspected, I only get messages for clicks on the Form directly, not any of its children. As a semi-hack, I added the following after InitializeComponent:</p>
<pre><code> foreach (Control c in this.Controls)
{
c.MouseClick += new MouseEventHandler(
delegate(object sender, MouseEventArgs e)
{
// handle the click here
});
}
</code></pre>
<p>This now gets clicks for controls that support the event, but Labels, for example, still don't get anything. Is there a simple way to do this that I'm overlooking?</p>
|
[
{
"answer_id": 248017,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "<p>If the labels are in a subcontrol then you'd have to do this recursively:</p>\n\n<pre><code>void initControlsRecursive(ControlCollection coll)\n { \n foreach (Control c in coll) \n { \n c.MouseClick += (sender, e) => {/* handle the click here */}); \n initControlsRecursive(c.Controls);\n }\n }\n\n/* ... */\ninitControlsRecursive(Form.Controls);\n</code></pre>\n"
},
{
"answer_id": 38375366,
"author": "Szabolcs Antal",
"author_id": 2036220,
"author_profile": "https://Stackoverflow.com/users/2036220",
"pm_score": 1,
"selected": false,
"text": "<p>To handle a <em>MouseClick</em> event for right click on all the controls on a custom <em>UserControl</em>:</p>\n\n<pre><code>public class MyClass : UserControl\n{\n public MyClass()\n {\n InitializeComponent();\n\n MouseClick += ControlOnMouseClick;\n if (HasChildren)\n AddOnMouseClickHandlerRecursive(Controls);\n }\n\n private void AddOnMouseClickHandlerRecursive(IEnumerable controls)\n {\n foreach (Control control in controls)\n {\n control.MouseClick += ControlOnMouseClick;\n\n if (control.HasChildren)\n AddOnMouseClickHandlerRecursive(control.Controls);\n }\n }\n\n private void ControlOnMouseClick(object sender, MouseEventArgs args)\n {\n if (args.Button != MouseButtons.Right)\n return;\n\n var contextMenu = new ContextMenu(new[] { new MenuItem(\"Copy\", OnCopyClick) });\n contextMenu.Show((Control)sender, new Point(args.X, args.Y));\n }\n\n private void OnCopyClick(object sender, EventArgs eventArgs)\n {\n MessageBox.Show(\"Copy menu item was clicked.\");\n }\n}\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13154/"
] |
I have a .NET UserControl (FFX 3.5). This control contains several child Controls - a Panel, a couple Labels, a couple TextBoxes, and yet another custom Control. I want to handle a right click anywhere on the base Control - so a right click on any child control (or child of a child in the case of the Panel). I'd like to do it so that it's maintainable if someone makes changes to the Control without having to wire in handlers for new Controls for example.
First I tried overriding the WndProc, but as I suspected, I only get messages for clicks on the Form directly, not any of its children. As a semi-hack, I added the following after InitializeComponent:
```
foreach (Control c in this.Controls)
{
c.MouseClick += new MouseEventHandler(
delegate(object sender, MouseEventArgs e)
{
// handle the click here
});
}
```
This now gets clicks for controls that support the event, but Labels, for example, still don't get anything. Is there a simple way to do this that I'm overlooking?
|
If the labels are in a subcontrol then you'd have to do this recursively:
```
void initControlsRecursive(ControlCollection coll)
{
foreach (Control c in coll)
{
c.MouseClick += (sender, e) => {/* handle the click here */});
initControlsRecursive(c.Controls);
}
}
/* ... */
initControlsRecursive(Form.Controls);
```
|
247,948 |
<p>Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?</p>
<pre class="lang-ruby prettyprint-override"><code>if !my_string || my_string.length == 0
return true
else
return false
end
</code></pre>
<p>In C# there's the handy</p>
<pre class="lang-csharp prettyprint-override"><code>string.IsNullOrEmpty(myString)
</code></pre>
<p>Anything similar to that in Ruby?</p>
|
[
{
"answer_id": 247971,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>Every class has a <code>nil?</code> method:</p>\n\n<pre><code>if a_variable.nil?\n # the variable has a nil value\nend\n</code></pre>\n\n<p>And strings have the <code>empty?</code> method:</p>\n\n<pre><code>if a_string.empty?\n # the string is empty\n}\n</code></pre>\n\n<p>Remember that a string does <em>not</em> equal <code>nil</code> when it is empty, so use the <code>empty?</code> method to check if a string is empty.</p>\n"
},
{
"answer_id": 247981,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p><code>nil?</code> can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:</p>\n\n<pre><code>return my_string.nil? || my_string.empty?\n</code></pre>\n"
},
{
"answer_id": 248028,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 2,
"selected": false,
"text": "<p>Konrad Rudolph has the right answer.</p>\n\n<p>If it really bugs you, monkey patch the String class or add it to a class/module of your choice. It's really not a good practice to monkey patch core objects unless you have a really compelling reason though.</p>\n\n<pre><code>class String\n def self.nilorempty?(string)\n string.nil? || string.empty?\n end\nend\n</code></pre>\n\n<p>Then you can do <code>String.nilorempty? mystring</code></p>\n"
},
{
"answer_id": 248056,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 5,
"selected": false,
"text": "<p>An alternative to jcoby's proposal would be:</p>\n\n<pre><code>class NilClass\n def nil_or_empty?\n true\n end\nend\n\nclass String\n def nil_or_empty?\n empty?\n end\nend\n</code></pre>\n"
},
{
"answer_id": 248074,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>First of all, beware of that method:</p>\n\n<p>As <a href=\"http://weblogs.asp.net/jezell/archive/2003/04/10/5280.aspx\" rel=\"noreferrer\">Jesse Ezel</a> says:</p>\n\n<blockquote>\n <p><a href=\"http://blogs.gotdotnet.com/brada/commentview.aspx/ed33b21f-39a1-4eba-8c62-5e578d6d989a\" rel=\"noreferrer\">Brad Abrams</a></p>\n \n <blockquote>\n <p>\"The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.</p>\n </blockquote>\n \n <p>Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.</p>\n \n <p>The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are).\"</p>\n</blockquote>\n\n<p>And if you patch String class... be sure <a href=\"http://rubyforge.org/pipermail/poignant-stiffs/2004-May/000077.html\" rel=\"noreferrer\">NilClass has not been patch either</a>!</p>\n\n<pre><code>class NilClass\n def empty?; true; end\nend\n</code></pre>\n"
},
{
"answer_id": 248217,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 6,
"selected": false,
"text": "<p>If you are willing to require ActiveSupport you can just use the <code>#blank?</code> method, which is defined for both NilClass and String.</p>\n"
},
{
"answer_id": 248265,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 5,
"selected": false,
"text": "<p>As it was said here before Rails (ActiveSupport) have a handy <a href=\"http://api.rubyonrails.org/classes/Object.html#M000155\" rel=\"noreferrer\">blank?</a> method and it is implemented like this:</p>\n\n<pre><code>class Object\n def blank?\n respond_to?(:empty?) ? empty? : !self\n end\nend\n</code></pre>\n\n<p>Pretty easy to add to any ruby-based project.</p>\n\n<p>The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.</p>\n"
},
{
"answer_id": 251644,
"author": "Ezran",
"author_id": 32883,
"author_profile": "https://Stackoverflow.com/users/32883",
"pm_score": 9,
"selected": true,
"text": "<p>When I'm not worried about performance, I'll often use this:</p>\n\n<pre><code>if my_string.to_s == ''\n # It's nil or empty\nend\n</code></pre>\n\n<p>There are various variations, of course...</p>\n\n<pre><code>if my_string.to_s.strip.length == 0\n # It's nil, empty, or just whitespace\nend\n</code></pre>\n"
},
{
"answer_id": 1620240,
"author": "Satya Kalluri",
"author_id": 140693,
"author_profile": "https://Stackoverflow.com/users/140693",
"pm_score": 4,
"selected": false,
"text": "<p>variable.blank? will do it.\nIt returns true if the string is empty or if the string is nil.</p>\n"
},
{
"answer_id": 9915384,
"author": "Vinay Sahni",
"author_id": 354789,
"author_profile": "https://Stackoverflow.com/users/354789",
"pm_score": 6,
"selected": false,
"text": "<p>I like to do this as follows (in a non Rails/ActiveSupport environment):</p>\n\n<pre><code>variable.to_s.empty?\n</code></pre>\n\n<p>this works because:</p>\n\n<pre><code>nil.to_s == \"\"\n\"\".to_s == \"\"\n</code></pre>\n"
},
{
"answer_id": 25396972,
"author": "Todd A. Jacobs",
"author_id": 1301972,
"author_profile": "https://Stackoverflow.com/users/1301972",
"pm_score": 2,
"selected": false,
"text": "<h2>Check for Empty Strings in Plain Ruby While Avoiding NameError Exceptions</h2>\n\n<p>There are some good answers here, but you don't need ActiveSupport or monkey-patching to address the common use case here. For example:</p>\n\n<pre><code>my_string.to_s.empty? if defined? my_string\n</code></pre>\n\n<p>This will \"do the right thing\" if <em>my_string</em> is nil or an empty string, but will not raise a <a href=\"http://www.ruby-doc.org/core-2.1.2/NameError.html\" rel=\"nofollow\">NameError exception</a> if <em>my_string</em> is not defined. This is generally preferable to the more contrived:</p>\n\n<pre><code>my_string.to_s.empty? rescue NameError\n</code></pre>\n\n<p>or its more verbose ilk, because exceptions should really be saved for things you <em>don't</em> expect to happen. In this case, while it might be a common error, an undefined variable isn't really an exceptional circumstance, so it should be handled accordingly.</p>\n\n<p>Your mileage may vary.</p>\n"
},
{
"answer_id": 49233410,
"author": "mahemoff",
"author_id": 18706,
"author_profile": "https://Stackoverflow.com/users/18706",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to convert nil to an empty result on the fly:</p>\n\n<p><code>(my_string||'').empty?</code></p>\n"
},
{
"answer_id": 51532697,
"author": "snipsnipsnip",
"author_id": 188256,
"author_profile": "https://Stackoverflow.com/users/188256",
"pm_score": 0,
"selected": false,
"text": "<p>For code golfers:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>if my_string=~/./\n p 'non-empty string'\nelse\n p 'nil or empty string'\nend\n</code></pre>\n\n<p>Or if you're not a golfer (requires ruby 2.3 or later):</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>if my_string&.size&.positive?\n # nonzero? also works\n p 'non-empty string'\nelse\n p 'nil or empty string'\nend\n</code></pre>\n"
},
{
"answer_id": 51595744,
"author": "Nondv",
"author_id": 3891844,
"author_profile": "https://Stackoverflow.com/users/3891844",
"pm_score": 0,
"selected": false,
"text": "<p>In rails you can try <code>#blank?</code>.</p>\n\n<p>Warning: it will give you positives when string consists of spaces:</p>\n\n<pre><code>nil.blank? # ==> true\n''.blank? # ==> true\n' '.blank? # ==> true\n'false'.blank? # ==> false\n</code></pre>\n\n<p>Just wanted to point it out. Maybe it suits your needs</p>\n\n<p>UPD. why am i getting old questions in my feed?\nSorry for necroposting.</p>\n"
},
{
"answer_id": 52274364,
"author": "RichOrElse",
"author_id": 6913691,
"author_profile": "https://Stackoverflow.com/users/6913691",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried Refinements?</p>\n\n<pre><code>module Nothingness\n refine String do\n alias_method :nothing?, :empty?\n end\n\n refine NilClass do\n alias_method :nothing?, :nil?\n end\nend\n\nusing Nothingness\n\nreturn my_string.nothing?\n</code></pre>\n"
},
{
"answer_id": 61100635,
"author": "Dhivya Dandapani",
"author_id": 4253388,
"author_profile": "https://Stackoverflow.com/users/4253388",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using rails, you can use <code>#present?</code></p>\n\n<pre><code>require 'rails'\n\nnil.present? # ==> false (Works on nil)\n''.present? # ==> false (Works on strings)\n' '.present? # ==> false (Works on blank strings)\n[].present? # ==> false(Works on arrays)\nfalse.present? # ==> false (Works on boolean)\n</code></pre>\n\n<p>So, conversely to check for nil or zero length use <code>!present?</code></p>\n\n<pre><code>!(nil.present?) # ==> true\n!(''.present?) # ==> true\n!(' '.present?) # ==> true\n!([].present?) # ==> true\n!(false.present?) # ==> true\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650/"
] |
Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?
```ruby
if !my_string || my_string.length == 0
return true
else
return false
end
```
In C# there's the handy
```csharp
string.IsNullOrEmpty(myString)
```
Anything similar to that in Ruby?
|
When I'm not worried about performance, I'll often use this:
```
if my_string.to_s == ''
# It's nil or empty
end
```
There are various variations, of course...
```
if my_string.to_s.strip.length == 0
# It's nil, empty, or just whitespace
end
```
|
247,961 |
<p>Exception: Failed to compare two elements in the array.</p>
<pre><code>private void assignNames(DropDownList ddl, Hashtable names)
{
List<ListItem> nameList = new List<ListItem>();
if (ddl != null)
{
ddl.ClearSelection();
ddl.Items.Add(new ListItem("Select Author"));
foreach (string key in names.Keys)
{
nameList.Add(new ListItem(names[key].ToString(), key));
}
nameList.Sort();
}
</code></pre>
<p>So how can I use Sort() to compare on the "names" and not get stuck on the key?</p>
|
[
{
"answer_id": 247983,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 1,
"selected": false,
"text": "<p>what type of object is \"names\"?</p>\n\n<p>EDIT:\nFrom what I can tell you will have to specify an IComparer for this to work, not sure if I fully understand what you are trying to do though.</p>\n\n<p>EDIT:\nThis is way too complicated for what I \"feel\" your intent is, you basically want to populate a dropdown list with a sorted list of Author names.</p>\n\n<p>you should be able to have a </p>\n\n<pre><code>List<string> auhtorNames;\nauthorNames.Sort();\nddl.DataSource = authorNames;\nddl.DataBind();\n</code></pre>\n"
},
{
"answer_id": 247997,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 0,
"selected": false,
"text": "<p>Use ArrayList.Sort(IComparer) instead of ArrayList.Sort().</p>\n"
},
{
"answer_id": 247999,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "<p>ListItem is not Comparable. you could use a System.Collections.Specialized.OrderedDictionary instead.</p>\n"
},
{
"answer_id": 248008,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": true,
"text": "<p>Provide a <a href=\"http://msdn.microsoft.com/en-us/library/tfakywbh.aspx\" rel=\"noreferrer\"><code>Comparison<T></code></a> to instruct the <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"noreferrer\"><code>List</code></a> on how to sort the items.</p>\n\n<pre><code>nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {\n return thisItem.Text.CompareTo(otherItem.Text);\n});\n</code></pre>\n\n<p>You might also want to check for <code>null</code> to be complete, unless you already know there won't be any, as in this case.</p>\n"
},
{
"answer_id": 248050,
"author": "Jacob Adams",
"author_id": 32518,
"author_profile": "https://Stackoverflow.com/users/32518",
"pm_score": 2,
"selected": false,
"text": "<p>nameList=nameList.OrderBy(li => li.Text).ToList();</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
Exception: Failed to compare two elements in the array.
```
private void assignNames(DropDownList ddl, Hashtable names)
{
List<ListItem> nameList = new List<ListItem>();
if (ddl != null)
{
ddl.ClearSelection();
ddl.Items.Add(new ListItem("Select Author"));
foreach (string key in names.Keys)
{
nameList.Add(new ListItem(names[key].ToString(), key));
}
nameList.Sort();
}
```
So how can I use Sort() to compare on the "names" and not get stuck on the key?
|
Provide a [`Comparison<T>`](http://msdn.microsoft.com/en-us/library/tfakywbh.aspx) to instruct the [`List`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) on how to sort the items.
```
nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {
return thisItem.Text.CompareTo(otherItem.Text);
});
```
You might also want to check for `null` to be complete, unless you already know there won't be any, as in this case.
|
247,977 |
<p>I have this in some WSDL:</p>
<pre><code><element name="startDate" type="xsd:dateTime"/>
<element name="endDate" type="xsd:dateTime"/>
</code></pre>
<p>Which results in the following text in the SOAP envelope:</p>
<pre><code><startDate>2008-10-29T12:01:05</startDate>
<endDate>2008-10-29T12:38:59.65625-04:00</endDate>
</code></pre>
<p>Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?</p>
|
[
{
"answer_id": 248099,
"author": "Dan Finucane",
"author_id": 30026,
"author_profile": "https://Stackoverflow.com/users/30026",
"pm_score": 1,
"selected": false,
"text": "<p>What are you using to generate the date? If you are building this XML in your code rather than using some serializer (WCF or XmlSerializer) you could use System.Xml.XmlConvert to generate and interpret the date as follows:</p>\n\n<p>To create the string to put in the XML:</p>\n\n<pre><code>DateTime startDate = DateTime.Now;\nstring startDateString = System.Xml.XmlConvert.ToString(startDate);\n</code></pre>\n\n<p>To get the date out of the XML:</p>\n\n<pre><code>DateTime startDateFromXml = System.Xml.XmlConvert.ToDateTime(startDateString);\n</code></pre>\n\n<p>If you start with two DateTime instances that differ by 37 minutes and 54 seconds before you push them into XML they will still differ by 37 minutes and 54 seconds after you pull them out of the XML.</p>\n"
},
{
"answer_id": 249547,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "<p>I suspect your endDate value has the Kind property set to DateTimeKind.Local.</p>\n\n<p>You can change this to DateTimeKind.Unspecified as follows:</p>\n\n<pre><code>endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Unspecified)\n</code></pre>\n\n<p>after which I believe it will be serialized without the timezone offset.</p>\n\n<p>Note that you will get a DateTime with DateTimeKind.Local if you have initialized it using DateTime.Now or DateTime.Today, and DateTimeKind.Utc if you have initialized it using Datetime.UtcNow.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3275/"
] |
I have this in some WSDL:
```
<element name="startDate" type="xsd:dateTime"/>
<element name="endDate" type="xsd:dateTime"/>
```
Which results in the following text in the SOAP envelope:
```
<startDate>2008-10-29T12:01:05</startDate>
<endDate>2008-10-29T12:38:59.65625-04:00</endDate>
```
Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?
|
I suspect your endDate value has the Kind property set to DateTimeKind.Local.
You can change this to DateTimeKind.Unspecified as follows:
```
endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Unspecified)
```
after which I believe it will be serialized without the timezone offset.
Note that you will get a DateTime with DateTimeKind.Local if you have initialized it using DateTime.Now or DateTime.Today, and DateTimeKind.Utc if you have initialized it using Datetime.UtcNow.
|
247,991 |
<p>I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.</p>
<p>This view would be included in another, non-Drupal site.</p>
<p>I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.</p>
|
[
{
"answer_id": 248044,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>there are probably a number of ways around this, however, the \"easiest\" may be just setting your own custom theme, and having the page.tpl.php just be empty, or some random divs</p>\n\n<pre><code>// page.tpl.php\n<div id=\"page\"><?php print $content ?></div>\n</code></pre>\n\n<p>this method would basically just allow node.tpl.php to show (or any of drupal's form views, etc...) and would be an easy way to avoid modifying core, or having to alter the theme registry to avoid displaying page.tpl.php in the first place.</p>\n\n<p><strong>edit</strong>: see comments</p>\n\n<p>ok i played around with views a bit, it looks like it takes over and constructs it's own \"node.tpl.php\" (in a sense) for display within \"page.tpl.php\". on first glance, my gut feeling would be to hook into <code>theme_registry_alter()</code>.</p>\n\n<p>when you're looking at a views page, you have access to piles of information here, as well as the page.tpl.php paths/files. as such i would do something like:</p>\n\n<pre><code>function modulejustforalteration_theme_registry_alter(&$variables) {\n if (isset($variables['views_ui_list_views']) ) {\n // not sure if that's the best index to test for \"views\" but i imagine it'll work\n // as well as others\n $variables['page']['template'] = 'override_page'; \n }\n}\n</code></pre>\n\n<p>this should allow you to use a \"override_page.tpl.php\" template in your current theme in which you can remove anything you want (as my first answer above).</p>\n\n<p>a few things:</p>\n\n<ul>\n<li>as i said, not sure if <code>views_ui_list_views</code> is always available to check against, but it sounds like it should be set if we're looking at a view</li>\n<li>you can alter the <code>theme paths</code> of the <code>page</code> array if you prefer (to change the location of where drupal will look for page.tpl.php, instead of renaming it altogether)</li>\n<li>there doesn't appear to be any identifiers for this specific view, so this method might be an \"all views will be stripped\" approach. if you need to strip the page.tpl.php for a specific view only, perhaps hooking into <code>template_preprocess_page()</code> might be a better idea.</li>\n</ul>\n"
},
{
"answer_id": 248096,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand your question, you want to have nodes which contain all the HTML for a page, from DOCTYPE to </HTML>. What I would do is create a content type for those nodes -- \"fullhtml\" as its machine-readable name -- and then create a node template for it called node-fullhtml.tpl.php. You can't just dump the node's contents, as they've been HTML-sanitized. node.fullhtml.tpl.php would literally be just this:</p>\n\n<pre><code>echo htmlspecialchars_decode($content);\n</code></pre>\n\n<p>Then you'll need a way to override the standard page.tpl.php. I <em>think</em> what you could do is at the top of your page.tpl.php check the $node's content type, and bail out if it's fullhtml. Or, set a global variable in node-fullhtml.tpl.php that page.tpl.php would check for.</p>\n\n<p>I'm no Drupal expert, but that's how I'd do it. I'm talking off the cuff, so watch for devils in the details.</p>\n"
},
{
"answer_id": 248770,
"author": "Chris",
"author_id": 16960,
"author_profile": "https://Stackoverflow.com/users/16960",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you're in Drupal 6, the easiest way to do this is to put a <code>phptemplate_views_view_unformatted_VIEWNAME</code> call in <code>template.php</code> (assumes your view is unformatted - if it's something else, a list say, use the appropriate theme function). Theme the view results in this theme call then, instead of returning the results as you normally would, print them and return <code>NULL</code>. This will output the HTML directly. </p>\n\n<p>PS - make sure to clear your cache (at /admin/settings/performance) to see this work.</p>\n"
},
{
"answer_id": 338549,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I like the Drupal module. BUt, here's another way.</p>\n\n<p>copy page.tpl.php in your theme folder to a new file called page-VIEWNAME.tpl.php, where VIEWNAME is the machine-readible name of the view.</p>\n\n<p>Then edit page-VIEWNAME.tpl.php to suit.</p>\n"
},
{
"answer_id": 430746,
"author": "Andrew",
"author_id": 51534,
"author_profile": "https://Stackoverflow.com/users/51534",
"pm_score": 0,
"selected": false,
"text": "<p>I see you have already gone and made yourself a module, so this may no longer help, but it is fairly easy to get a view to expose an rss feed, which might be an easier way of getting at the content, especially if you want to include it on a different site. </p>\n"
},
{
"answer_id": 609338,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>I was looking for a way to pull node data via ajax and came up with the following solution for Drupal 6. After implementing the changes below, if you add ajax=1 in the URL (e.g. mysite.com/node/1?ajax=1), you'll get just the content and no page layout.</p>\n\n<p>in the template.php file for your theme:</p>\n\n<pre><code>function phptemplate_preprocess_page(&$vars) {\n\n if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {\n $vars['template_file'] = 'page-ajax';\n }\n\n}\n</code></pre>\n\n<p>then create page-ajax.tpl.php in your theme directory with this content:</p>\n\n<pre><code><?php print $content; ?>\n</code></pre>\n"
},
{
"answer_id": 779934,
"author": "greggles",
"author_id": 56791,
"author_profile": "https://Stackoverflow.com/users/56791",
"pm_score": 1,
"selected": false,
"text": "<p>There is also <a href=\"http://drupal.org/project/pagearray\" rel=\"nofollow noreferrer\">http://drupal.org/project/pagearray</a> which is a general solution...</p>\n\n<p>Also, @Scott Evernden's solution is a cross site scripting (XSS) security hole. Don't do that. Read the documentation on drupal.org about how to Handle Text in a Secure Fashion <a href=\"http://drupal.org/node/28984\" rel=\"nofollow noreferrer\">http://drupal.org/node/28984</a></p>\n"
},
{
"answer_id": 978817,
"author": "rinogo",
"author_id": 114558,
"author_profile": "https://Stackoverflow.com/users/114558",
"pm_score": 3,
"selected": false,
"text": "<p>For others who may hit this page, if you're just working with standard callbacks (not necessarily views), this is easy. In your callback function, instead of returning the code to render within the page, use the 'print' function.</p>\n\n<p>For example:</p>\n\n<pre><code>function mymodule_do_ajax($node)\n{\n $rval = <<<RVAL\n <table>\n <th>\n <td>Data</td>\n <td>Data</td>\n <td>Data</td>\n </th>\n <tr>\n <td>Cool</td>\n <td>Cool</td>\n <td>Cool</td>\n </tr>\n </table>\nRVAL;\n\n //return $rval; Nope! Will render via the templating engine.\n print $rval; //Much better. No wrapper.\n}\n</code></pre>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 2065936,
"author": "nerdbabe",
"author_id": 250920,
"author_profile": "https://Stackoverflow.com/users/250920",
"pm_score": 1,
"selected": false,
"text": "<p>A simple way to display content of a special content-type you wish to display without all the stuff of the <code>page.tpl.php</code>:<br>\nAdd the following snippet to your <code>template.php</code> file:</p>\n\n<pre><code>function mytheme_preprocess_page(&$vars) {\n if ($vars['node'] && arg(2) != 'edit') {\n $vars['template_files'][] = 'page-nodetype-'. $vars['node']->type;\n }\n}\n</code></pre>\n\n<p>Add a <code>page-nodetype-examplecontenttype.tpl.php</code> to your theme, like your <code>page.tpl.php</code> but without the stuff you don't want to display and with <code>print $content</code> in the body.</p>\n"
},
{
"answer_id": 2450102,
"author": "Itangalo",
"author_id": 294262,
"author_profile": "https://Stackoverflow.com/users/294262",
"pm_score": 2,
"selected": false,
"text": "<p>Hey, here's yet another way of doing it:</p>\n\n<p>1) Download and install Views Bonus Pack (<a href=\"http://drupal.org/project/views_bonus\" rel=\"nofollow noreferrer\">http://drupal.org/project/views_bonus</a>)\n2) Create a Views display \"Feed\" and use style \"XML\" (or something you think fits your needs better).\n3) If you're not satisfied with the standard XML output, you can change it by adjusting the template for the view. Check the \"theme\" settings to get suggestions for alternative template names for this specific view (so you'll still have the default XML output left for future use).</p>\n\n<p>Good luck!\n//Johan Falk, NodeOne, Sweden</p>\n"
},
{
"answer_id": 4924982,
"author": "Ufonion Labs",
"author_id": 606822,
"author_profile": "https://Stackoverflow.com/users/606822",
"pm_score": 2,
"selected": false,
"text": "<p>Based on answer of Philadelphia Web Design (thanks) and some googling (<a href=\"http://drupal.org/node/957250\" rel=\"nofollow\">http://drupal.org/node/957250</a>) here is what worked for me in <strong>Drupal 7</strong> to get chosen pages displayed without the template:</p>\n\n<pre><code>function pixture_reloaded_preprocess_page(&$vars)\n{\n if ( isset($_GET['vlozeno']) && $_GET['vlozeno'] == 1 ) {\n $vars['theme_hook_suggestions'][] = 'page__vlozeno';\n } \n}\n</code></pre>\n\n<p>instead of phptemplate, in D7 there has to be the name_of_your_theme in the name of the function. Also, I had to put two underscores __ in the php variable with the file name, but the actual template file name needs two dashes --</p>\n\n<p>content of page--vlozeno.tpl.php :</p>\n\n<pre><code><?php print render($page['content']); ?>\n</code></pre>\n\n<p>The output, however, still has got a lot of wrapping and theme's CSS references. Not sure how to output totally unthemed data...</p>\n"
},
{
"answer_id": 8396968,
"author": "jeroen",
"author_id": 306800,
"author_profile": "https://Stackoverflow.com/users/306800",
"pm_score": 4,
"selected": false,
"text": "<p>Based on the answer of Ufonion Labs I was able to completely remove all the HTML output around the page content in Drupal 7 by implementing both <code>hook_preprocess_page</code> and <code>hook_preprocess_html</code> in my themes template.php, like this:</p>\n\n<pre><code>function MY_THEME_preprocess_page(&$variables) {\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'page__embed';\n }\n}\n\nfunction MY_THEME_preprocess_html(&$variables) {\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'html__embed';\n }\n}\n</code></pre>\n\n<p>Then I added two templates to my theme: <code>html--embed.tpl.php</code>:</p>\n\n<pre><code><?php print $page; ?>\n</code></pre>\n\n<p>and <code>page--embed.tpl.php</code>:</p>\n\n<pre><code><?php print render($page['content']); ?>\n</code></pre>\n\n<p>Now when I open a node page, such as <a href=\"http://example.com/node/3\">http://example.com/node/3</a>, I see the complete page as usual, but when I add the response_type parameter, such as <a href=\"http://example.com/node/3?response_type=embed\">http://example.com/node/3?response_type=embed</a>, I <em>only</em> get the <code><div></code> with the page contents so it can be embedded in another page.</p>\n"
},
{
"answer_id": 8823037,
"author": "Nabil Kadimi",
"author_id": 358906,
"author_profile": "https://Stackoverflow.com/users/358906",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to do it which I find very handy is to add a menu item with a page callback function that doesn't return a string:</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Implementation of hook_menu.\n */\nfunction test_menu(){\n $items['test'] = array (\n /* [...] */ \n 'page callback' => 'test_callback',\n /* [...] */ \n );\n return $items;\n}\n\nfunction test_callback() {\n // echo or print whatever you want\n // embed views if you want\n // DO NOT RETURN A STRING\n return TRUE;\n} \n</code></pre>\n\n<p>-- Update</p>\n\n<p>It would be much better to use <code>exit();</code> instead of <code>return TRUE;</code> (see comment).</p>\n"
},
{
"answer_id": 11908461,
"author": "SwarmIntelligence",
"author_id": 1183175,
"author_profile": "https://Stackoverflow.com/users/1183175",
"pm_score": 3,
"selected": false,
"text": "<p>I know this question has already been answered, but I wanted to add my own solution which uses elements of Philadelphia Web Design's (PWD) answer and uses hook_theme_registry_alter, as suggested by Owen. Using this solution, you can load the template directly from a custom module.</p>\n\n<p>First, I added raw.tpl.php to a newly created 'templates' folder inside my module. The contents of raw.tpl.php are identical to PWD's page-ajax.tpl.php:</p>\n\n<pre><code><?php print $content; ?>\n</code></pre>\n\n<p>Next, I implemented hook_preprocess_page in my module in the same fashion as PWD (except that I modified the $_GET parameter and updated the template file reference:</p>\n\n<pre><code>function MY_MODULE_NAME_preprocess_page(&$vars) {\n if ( isset($_GET['raw']) && $_GET['raw'] == 1 ) {\n $vars['template_file'] = 'raw';\n }\n} \n</code></pre>\n\n<p>Finally, I implemented hook_theme_registry_alter to add my module's 'templates' directory to the theme registry (based on <a href=\"http://drupal.org/node/1105922#comment-4265700\">http://drupal.org/node/1105922#comment-4265700</a>):</p>\n\n<pre><code>function MY_MODULE_NAME_theme_registry_alter(&$theme_registry) {\n $modulepath = drupal_get_path('module','MY_MODULE_NAME');\n array_unshift($theme_registry['page']['theme paths'], $modulepath.'/templates');\n}\n</code></pre>\n\n<p>Now, when I add ?raw=1 to the view's URL path, it will use the specified template inside my module.</p>\n"
},
{
"answer_id": 25518051,
"author": "Alan Bondarchuk",
"author_id": 3204244,
"author_profile": "https://Stackoverflow.com/users/3204244",
"pm_score": 0,
"selected": false,
"text": "<p>On D7 you can use <a href=\"https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_execute_active_handler/7\" rel=\"nofollow\">menu_execute_active_handler</a></p>\n\n<pre><code>$build = menu_execute_active_handler('user', FALSE);\nreturn render($build);\n</code></pre>\n"
},
{
"answer_id": 51628323,
"author": "Wilhelm Stoker",
"author_id": 10164474,
"author_profile": "https://Stackoverflow.com/users/10164474",
"pm_score": 0,
"selected": false,
"text": "<p>jeroen's answer was what did for me after playing with it. I have a Drupal 7 site. </p>\n\n<ol>\n<li><p>First of all make sure you replace <code>MY_THEME</code> with your theme name. Yes it is obvious but most newbies miss this.</p></li>\n<li><p>I actually already had a <code>function MY_THEME_preprocess_page(&$variables) {</code>. Do not recreate the function then but add this code at the end of the function before you close it with <code>}</code>.</p></li>\n</ol>\n\n<hr>\n\n<pre><code>if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'page__embed';\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>My function used <code>$vars</code> not <code>$variables</code>, so I had to update that as well. Again obvious if you think look for it.</li>\n</ol>\n"
},
{
"answer_id": 51651047,
"author": "Wilhelm Stoker",
"author_id": 10164474,
"author_profile": "https://Stackoverflow.com/users/10164474",
"pm_score": 0,
"selected": false,
"text": "<p>My first answered allowed me to only display the node when I called it up in a web browser. However the ultimate goal of this is to embed the drupal node in an 3rd party site using iframe.</p>\n\n<p>Since the release of Drupal <a href=\"https://www.drupal.org/node/2735873\" rel=\"nofollow noreferrer\">Core 7.50 iframe is by default blocked to prevent Clickjacking</a> </p>\n\n<p>To get only the node to successfully embed in a 3rd party site you also need to override the x-frame default setting. Everything started working after I added the following in template.php</p>\n\n<pre><code>function MY_THEME_page_alter($page) {\n\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n header_remove('X-Frame-Options');\n } \n}\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902010/"
] |
I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.
This view would be included in another, non-Drupal site.
I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.
|
I was looking for a way to pull node data via ajax and came up with the following solution for Drupal 6. After implementing the changes below, if you add ajax=1 in the URL (e.g. mysite.com/node/1?ajax=1), you'll get just the content and no page layout.
in the template.php file for your theme:
```
function phptemplate_preprocess_page(&$vars) {
if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
$vars['template_file'] = 'page-ajax';
}
}
```
then create page-ajax.tpl.php in your theme directory with this content:
```
<?php print $content; ?>
```
|
248,011 |
<p><code>pre</code> tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?</p>
|
[
{
"answer_id": 248013,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 11,
"selected": true,
"text": "<p>The answer, from <a href=\"https://longren.io/wrapping-text-inside-pre-tags/\" rel=\"noreferrer\">this page</a> in CSS:</p>\n<pre><code>pre {\n white-space: pre-wrap; /* Since CSS 2.1 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n</code></pre>\n"
},
{
"answer_id": 248023,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 4,
"selected": false,
"text": "<p>You can either:</p>\n\n<pre><code>pre { white-space: normal; }\n</code></pre>\n\n<p>to maintain the monospace font but add word-wrap, or:</p>\n\n<pre><code>pre { overflow: auto; }\n</code></pre>\n\n<p>which will allow a fixed size with horizontal scrolling for long lines.</p>\n"
},
{
"answer_id": 248034,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 3,
"selected": false,
"text": "<p>Try using </p>\n\n<pre><code><pre style=\"white-space:normal;\">. \n</code></pre>\n\n<p>Or better throw CSS.</p>\n"
},
{
"answer_id": 6008351,
"author": "ekerner",
"author_id": 233060,
"author_profile": "https://Stackoverflow.com/users/233060",
"pm_score": 4,
"selected": false,
"text": "<p>I suggest forget the pre and just put it in a textarea.</p>\n\n<p>Your indenting will remain and your code wont get word-wrapped in the middle of a path or something. </p>\n\n<p>Easier to select text range in a text area too if you want to copy to clipboard.</p>\n\n<p>The following is a php excerpt so if your not in php then the way you pack the html special chars will vary.</p>\n\n<pre><code><textarea style=\"font-family:monospace;\" onfocus=\"copyClipboard(this);\"><?=htmlspecialchars($codeBlock);?></textarea>\n</code></pre>\n\n<p>For info on how to copy text to the clipboard in js see: <a href=\"https://stackoverflow.com/questions/400212/how-to-copy-to-clipboard-in-javascript\">How do I copy to the clipboard in JavaScript?</a> .</p>\n\n<p>However...</p>\n\n<p>I just inspected the stackoverflow code blocks and they wrap in a <code> tag wrapped in <pre> tag with css ...</p>\n\n<pre><code>code {\n background-color: #EEEEEE;\n font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;\n}\npre {\n background-color: #EEEEEE;\n font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;\n margin-bottom: 10px;\n max-height: 600px;\n overflow: auto;\n padding: 5px;\n width: auto;\n}\n</code></pre>\n\n<p>Also the content of the stackoverflow code blocks is syntax highlighted using (I think) <a href=\"http://code.google.com/p/google-code-prettify/\" rel=\"noreferrer\">http://code.google.com/p/google-code-prettify/</a> .</p>\n\n<p>Its a nice setup but Im just going with textareas for now.</p>\n"
},
{
"answer_id": 6098078,
"author": "Richard McKechnie",
"author_id": 525185,
"author_profile": "https://Stackoverflow.com/users/525185",
"pm_score": 8,
"selected": false,
"text": "<p>This works great to wrap text and maintain white-space within the <code>pre</code>-tag:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>pre {\n white-space: pre-wrap;\n}\n</code></pre>\n"
},
{
"answer_id": 17420314,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The following helped me:</p>\n\n<pre><code>pre {\n white-space: normal;\n word-wrap: break-word;\n}\n</code></pre>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 20618776,
"author": "Mason240",
"author_id": 615285,
"author_profile": "https://Stackoverflow.com/users/615285",
"pm_score": 6,
"selected": false,
"text": "<p>I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.</p>\n\n<pre><code> <div style=\"white-space: pre-wrap;\">content</div>\n</code></pre>\n"
},
{
"answer_id": 21241578,
"author": "user1433454",
"author_id": 1433454,
"author_profile": "https://Stackoverflow.com/users/1433454",
"pm_score": 4,
"selected": false,
"text": "<p>This is what I needed. It kept words from breaking but allowed for dynamic width in the pre area.</p>\n\n<pre><code>word-break: keep-all;\n</code></pre>\n"
},
{
"answer_id": 30299462,
"author": "rob_st",
"author_id": 1991146,
"author_profile": "https://Stackoverflow.com/users/1991146",
"pm_score": 2,
"selected": false,
"text": "<p>The <code><pre></code>-Element stands for \"pre-formatted-text\" and is intended to keep the formatting of the text (or whatever) between its tags. Therefore it is actually not inteded to have automatic word-wrapping or line-breaks within the <code><pre></code>-Tag</p>\n\n<blockquote>\n <p>Text in a element is displayed in a fixed-width font (usually Courier), and it <strong>preserves both spaces <em>and line breaks</em></strong>.</p>\n</blockquote>\n\n<p><a href=\"http://www.w3schools.com/tags/tag_pre.asp\" rel=\"nofollow\">source: w3schools.com</a>, emphasises made by myself.</p>\n"
},
{
"answer_id": 31466925,
"author": "feacco",
"author_id": 5035625,
"author_profile": "https://Stackoverflow.com/users/5035625",
"pm_score": 1,
"selected": false,
"text": "<p><strong>The Best Cross Browser Way worked for me to get line breaks and shows exact code or text:</strong> (chrome, internet explorer, Firefox)</p>\n\n<p>CSS:</p>\n\n<pre><code>xmp{ white-space:pre-wrap; word-wrap:break-word; }\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code><xmp> your text or code </xmp>\n</code></pre>\n"
},
{
"answer_id": 45783868,
"author": "vovahost",
"author_id": 1502079,
"author_profile": "https://Stackoverflow.com/users/1502079",
"pm_score": 5,
"selected": false,
"text": "<p>I combined @richelectron and @user1433454 answers. <br>\nIt works very well and preserves the text formatting. </p>\n\n<pre><code><pre style=\"white-space: pre-wrap; word-break: keep-all;\">\n\n</pre>\n</code></pre>\n"
},
{
"answer_id": 52130554,
"author": "Erin Delacroix",
"author_id": 10302071,
"author_profile": "https://Stackoverflow.com/users/10302071",
"pm_score": 6,
"selected": false,
"text": "<p>Most succinctly, this forces content to wrap inside of a <code>pre</code> tag without breaking words.</p>\n<pre><code>pre {\n white-space: pre-wrap;\n word-break: keep-all\n}\n</code></pre>\n"
},
{
"answer_id": 59185290,
"author": "Someone",
"author_id": 12260140,
"author_profile": "https://Stackoverflow.com/users/12260140",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>white-space: pre-wrap</code> and vendor prefixes for automatic line breaking inside <code>pre</code>s.</p>\n<p>Do not use <code>word-wrap: break-word</code> because this just, of course, breaks a word in half which is probably something you do not want.</p>\n"
},
{
"answer_id": 69546216,
"author": "Saleh Abdulaziz",
"author_id": 1895511,
"author_profile": "https://Stackoverflow.com/users/1895511",
"pm_score": 1,
"selected": false,
"text": "<p>in case your using prism or any code formatting library, then you will need to modify booth pre and code tags as follow:</p>\n<pre><code>pre {\n overflow-x: auto !important;\n white-space: pre-wrap !important; /* Since CSS 2.1 */\n white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */\n white-space: -pre-wrap !important; /* Opera 4-6 */\n white-space: -o-pre-wrap !important; /* Opera 7 */\n word-wrap: break-word !important; /* Internet Explorer 5.5+ */\n}\n\ncode{\n white-space: normal !important;\n}\n</code></pre>\n"
},
{
"answer_id": 70455437,
"author": "pbies",
"author_id": 1701812,
"author_profile": "https://Stackoverflow.com/users/1701812",
"pm_score": 1,
"selected": false,
"text": "<p><code><pre></code> does it's work, but for code there is <code><code></code> tag.</p>\n"
},
{
"answer_id": 72023541,
"author": "Nima Habibollahi",
"author_id": 1935499,
"author_profile": "https://Stackoverflow.com/users/1935499",
"pm_score": 1,
"selected": false,
"text": "<p>This is what you need to wrap text inside pre tag:</p>\n<pre><code>pre {\n white-space: pre-wrap; /* css-3 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
`pre` tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?
|
The answer, from [this page](https://longren.io/wrapping-text-inside-pre-tags/) in CSS:
```
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
```
|
248,031 |
<p>Hi I'm trying to get some practice with Linked Lists.</p>
<p>I Defined an Object class called <code>Student</code>:</p>
<pre><code>public class Student
{
protected string Student_Name;
protected int Student_ID;
protected int Student_Mark;
protected char Student_Grade;
public Student() // default Constructor
{
Student_Name = " ";
Student_ID = 0;
Student_Mark = 0;
Student_Grade = ' ';
}
public Student(string Sname, int Sid, int Smark, char Sgrade) // Constructor
{
int len = sname.Length;
Student_Name = sname.Substring(0, len);
//Student_Name = sname.Substring(0, sname.Length);
Student_ID = Sid;
Student_Mark = Smark;
Student_Grade = Sgrade;
}
}
</code></pre>
<p>and then a <code>Node</code> class:</p>
<pre><code>public class S_Node
{
public Student Element;
public S_Node Link;
public S_Node()
{
Element = new Student();
Link = null;
}
public Node(Student theElement)
{
Element = theElement;
Link = null;
}
}
</code></pre>
<p>and the <code>LinkedList</code>:</p>
<pre><code>public class S_LinkedList
{
protected S_Node header;
protected S_Node tail;
public S_LinkedList()
{
header = new S_Node();
Tail = new S_Node();
header.Link = Tail;
}
// METHODS which i don't know how to do it (never use linkedlist before)
}
</code></pre>
<p>I need to organize this data using a “linkedlist data structure type”.</p>
<p>Contain all methods of linkedlist as Adding nodes to the list as I've learned -->(Insert),Deleting nodes from the list,as I've learned -->((Remove),Traversing the lists I've learned -->((PrintList),Finding a node in the list as I've learned -->((Find , FindPrevious) the problem I'm selflearning and I've tried to search the net and read more from the stupid C# that was a disaster.
I've done too much that I'm so sad that i don't know how to complete it .</p>
<p>I'm trying hard to Use this classes to write an executable program and to Test it .</p>
<p>If you don't want to help in completing this program (hope not) at least show me some real examples or ideas , after all I'm a selflearner geek :-)</p>
|
[
{
"answer_id": 248049,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 1,
"selected": false,
"text": "<p>Actually I don't see a reason to write your own linked list in C# (other then learning how it works) since the .NET already contains LinkedList generic class.</p>\n"
},
{
"answer_id": 248057,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 0,
"selected": false,
"text": "<p>Your question, as I read it, is too vague. I would start by googling 'linked lists' or picking up a book on 'data structures'. When you run into a specific problem, ask it on here, and I'm sure someone will help you.</p>\n"
},
{
"answer_id": 248105,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 2,
"selected": false,
"text": "<p>I'll do one for you! You need to draw diagrams with each node as a box, and work out what code you need to use to change the list for each operation. See this for some inspiration:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Linked_list</a></p>\n\n<p>The diagrams there don't show the main list class as a box, which you should have, with two arrows coming out of it for the header and tail.</p>\n\n<p>Draw yourself some diagrams for the two cases in the Insert method to work out what's going on. One diagram for when there's nothing in the list and header is null, and another diagram for when there's something already in the list. Then from there work out the other operations.</p>\n\n<pre><code>public class S_LinkedList {\n\n protected S_Node header = null;\n\n protected S_Node tail = null;\n\n public S_LinkedList()\n {\n }\n\n // METHODS which i don't know how to do it (never use linkedlist before)\n void Insert(Student s)\n {\n if( header == null )\n {\n header = new S_Node(s);\n tail = header;\n }\n else\n {\n tail.Link = new S_Node(s);\n tail = tail.Link;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248106,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": 2,
"selected": false,
"text": "<p>The operations you are missing are:</p>\n\n<p><strong>Add:</strong></p>\n\n<p>set the link of the tail node to be the added node and set the tail to be the new node.</p>\n\n<p><strong>Remove/Delete:</strong></p>\n\n<p>is a bit tricky if you don't have a doubly linked list but with a singly linked list go throught he list from the head till you find the node you require keeping the previous node in a separate variable. When you find the node you are removing set the Link of the previous node to that nodes link. An optimization might be to check that it's not the link you are looking for.\nAlternatively make it a doubly linked list and you don't need to keep track of the previous node.</p>\n\n<p><strong>Find:</strong></p>\n\n<p>Traverse the list from node to node till you find the one you are looking for.</p>\n\n<p>read this <a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"nofollow noreferrer\">wikipedia article for more info.</a></p>\n"
},
{
"answer_id": 248126,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": 2,
"selected": false,
"text": "<p>Look at <a href=\"http://www.csharphelp.com/archives3/archive478.html\" rel=\"nofollow noreferrer\">this...</a></p>\n\n<p>Although if you really want to learn how to do this you should write it in c or c++ at least then you'd be doing something useful...</p>\n"
},
{
"answer_id": 248259,
"author": "Ryan Rodemoyer",
"author_id": 1444511,
"author_profile": "https://Stackoverflow.com/users/1444511",
"pm_score": 1,
"selected": false,
"text": "<p>The concept of linked lists is not very difficult to understand. Implementation on the other hand ... can get a bit tricky.</p>\n\n<p>I can also understand your frustration of trying to find information on the web about it. I have been in your boat before and everything varies from site to site. You really might want to invest in a data structures book as you I think the information you find will be much more clear and helpful than most information you find in the wild.</p>\n\n<p>Implementing a linked list in Java/C# will be much easier if you have never used ll's before. However, once you get a better feel for it you will get a much better understanding for the ll's by creating them in C/C++.</p>\n\n<p>From your code above, you will be better off thinking of each S_Node as just regular node that contains a Student object instead of thinking of it as a Student node (hope that makes sense). Same rules apply for your S_LinkedList class. A linked list is a list mode up of nodes. These nodes contain Student objects.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 248279,
"author": "Ryan Rodemoyer",
"author_id": 1444511,
"author_profile": "https://Stackoverflow.com/users/1444511",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Try this as your Student class.</strong></p>\n\n<pre><code>public class Student\n{\n protected string Name;\n protected int ID;\n protected int Mark;\n protected char Grade;\n\n public Student() // default Constructor\n {\n Name = \"\";\n ID = 0;\n Mark = 0;\n Grade = '';\n }\n\n public Student(string Name, int ID, int Mark, char Grade) // Constructor\n {\n this.Name = Name;\n this.ID = ID;\n this.Mark = Mark;\n this.Grade = Grade;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248899,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 5,
"selected": true,
"text": "<pre>\n the head of the list.\n ( item1\n Element: student1\n Next ------------> ( item2\n ) Element: student2\n Next ------------> ( item3\n ) Element: student3\n Next: null\n )\n the tail of the list.\n</pre>\n\n<p>First of all, for you to be able to write the StudentList class, you need to write the client code first. Client code is the code that uses your student list. Also, don't just write one thing at a time and throw it away. Instead write a whole bunch of [test] cases that exercise the different ways you <em>need</em> to interact with the StudentList. Write exceptional cases too. But don't be tempted to write a swiss-army knife of a class that does everything just because it can. Write the minimal amount of code that gets the job done.</p>\n\n<p>How you need to use the class will heavily dictate how the class is constructed. This is the essence of TDD or Test Driven Design.</p>\n\n<p>Your biggest problem that I can see is you have no idea how you want to use the class. So lets do that first.</p>\n\n<pre><code>// create a list of students and print them back out.\nStudentList list = new StudentList();\nlist.Add( new Student(\"Bob\", 1234, 2, 'A') );\nlist.Add( new Student(\"Mary\", 2345, 4, 'C') );\n\nforeach( Student student in list)\n{\n Console.WriteLine(student.Name);\n}\n</code></pre>\n\n<p>I add the students to the list, and then I print them out.</p>\n\n<p>I have no need for my client code to see inside the StudentList. Therefore StudentList hides how it implements the linked list. Let's write the basics of the StudentList.</p>\n\n<pre><code>public class StudentList \n{\n private ListNode _firstElement; // always need to keep track of the head.\n\n private class ListNode\n {\n public Student Element { get; set; }\n public ListNode Next { get; set; }\n }\n\n public void Add(Student student) { /* TODO */ }\n\n}\n</code></pre>\n\n<p>StudentList is pretty basic. Internally it keeps track of the first or head nodes. Keeping track of the first node is obviously always required. </p>\n\n<p>You also might wonder why ListNode is declared inside of StudentList. What happens is the ListNode class is only accessible to the StudentList class. This is done because StudentList doesn't want to give out the details to it's internal implementation because it is controlling all access to the list. StudentList never reveals how the list is implemented. Implementation hiding is an important OO concept.</p>\n\n<p>If we did allow client code to directly manipulate the list, there'd be no point having StudentList is the first place.</p>\n\n<p>Let's go ahead and implement the Add() operation.</p>\n\n<pre><code>public void Add(Student student)\n{\n if (student == null)\n throw new ArgumentNullException(\"student\");\n\n // create the new element\n ListNode insert = new ListNode() { Element = student };\n\n if( _firstElement == null )\n {\n _firstElement = insert;\n return;\n }\n\n ListNode current = _firstElement;\n while (current.Next != null)\n {\n current = current.Next;\n }\n\n current.Next = insert;\n}\n</code></pre>\n\n<p>The Add operation has to find the last item in the list and then puts the new ListNode at the end. Not terribly efficient though. It's currently O(N) and Adding will get slower as the list gets longer. </p>\n\n<p>Lets optimize this a little for inserts and rewrite the Add method. To make Add faster all we need to do is have StudentList keep track of the last element in the list.</p>\n\n<pre><code>private ListNode _lastElement; // keep track of the last element: Adding is O(1) instead of O(n)\n\npublic void Add(Student student)\n{\n if( student == null )\n throw new ArgumentNullException(\"student\");\n\n // create the new element\n ListNode insert = new ListNode() { Element = student };\n\n if (_firstElement == null)\n {\n _firstElement = insert;\n _lastElement = insert;\n return;\n }\n\n // fix up Next reference\n ListNode last = _lastElement;\n last.Next = insert;\n _lastElement = insert;\n}\n</code></pre>\n\n<p>Now, when we add, we don't iterate. We just need to keep track of the head and tail references.</p>\n\n<p>Next up: the foreach loop. StudentList is a collection, and being a collection we want to enumerate over it and use C#'s <code>foreach</code>. The C# compiler can't iterate magically. In order to use the foreach loop We need to provide the compiler with an enumerator to use even if the code we write doesn't explicitly appear to use the enumerator.</p>\n\n<p>First though, lets re-visit how we iterate over a linked list.</p>\n\n<pre><code>// don't add this to StudentList\nvoid IterateOverList( ListNode current )\n{\n while (current != null)\n {\n current = current.Next;\n }\n}\n</code></pre>\n\n<p>Okay. so let's hook into C#'s foreach loop and return an enumerator. To do that we alter StudentList to implement IEnumerable. This is getting a little bit advanced, but you should be able to figure out what's going on. </p>\n\n<pre><code>// StudentList now implements IEnumerable<Student>\npublic class StudentList : IEnumerable<Student>\n{\n // previous code omitted\n\n #region IEnumerable<Student> Members\n public IEnumerator<Student> GetEnumerator()\n {\n ListNode current = _firstElement;\n\n while (current != null)\n {\n yield return current.Element;\n current = current.Next;\n }\n }\n #endregion\n\n #region IEnumerable Members\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n #endregion\n}\n</code></pre>\n\n<p>You should be able to spot the linked list iteration in there. Don't get thrown by the <code>yield</code> keyword. All yield is doing is returning the current student back to the foreach loop. The enumarator stops returning students when it gets to the end of the linked list.</p>\n\n<p>And that's it! The code works the way we want it to.</p>\n\n<hr>\n\n<p>* This is by no means the only way to implement the list. I've opted to put the list logic in the StudentList and keep ListNode very basic. But the code does only what my very first unit test needs and nothing more. There are more optimizations you could make, and there are other ways of constructing the list.</p>\n\n<p>Going forward: What you need to do is first create [unit] tests for what your code needs to do, then add the implementation you require.</p>\n\n<hr>\n\n<p>* fyi I also rewrote the Student class. Bad naming and strange casing from a C# persepctive, not to mention the code you provided doesn't compile. I prefer the <code>_</code> as a leader to private member variables. Some people don't like that, however you're new to this so I'll leave them in because they're easy to spot.</p>\n\n<pre><code>public class Student\n{\n private string _name;\n private int _id;\n private int _mark;\n private char _letterGrade;\n\n private Student() // hide default Constructor\n { }\n\n public Student(string name, int id, int mark, char letterGrade) // Constructor\n {\n if( string.IsNullOrEmpty(name) )\n throw new ArgumentNullException(\"name\");\n if( id <= 0 )\n throw new ArgumentOutOfRangeException(\"id\");\n\n _name = name;\n _id = id;\n _mark = mark;\n _letterGrade = letterGrade;\n }\n // read-only properties - compressed to 1 line for SO answer.\n public string Name { get { return _name; } }\n public int Id { get { return _id; } }\n public int Mark { get { return _mark; } }\n public char LetterGrade { get { return _letterGrade; } }\n}\n</code></pre>\n\n<ul>\n<li>check parameters</li>\n<li>pay attention to the different casing of properties, classes, and variables. </li>\n<li>hide the default constructor. Why do I want to create students without real data?</li>\n<li>provide some read-only properties. \n\n<ul>\n<li>This class is immutable as written (i.e. once you create a student, you can't change it).</li>\n</ul></li>\n</ul>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31512/"
] |
Hi I'm trying to get some practice with Linked Lists.
I Defined an Object class called `Student`:
```
public class Student
{
protected string Student_Name;
protected int Student_ID;
protected int Student_Mark;
protected char Student_Grade;
public Student() // default Constructor
{
Student_Name = " ";
Student_ID = 0;
Student_Mark = 0;
Student_Grade = ' ';
}
public Student(string Sname, int Sid, int Smark, char Sgrade) // Constructor
{
int len = sname.Length;
Student_Name = sname.Substring(0, len);
//Student_Name = sname.Substring(0, sname.Length);
Student_ID = Sid;
Student_Mark = Smark;
Student_Grade = Sgrade;
}
}
```
and then a `Node` class:
```
public class S_Node
{
public Student Element;
public S_Node Link;
public S_Node()
{
Element = new Student();
Link = null;
}
public Node(Student theElement)
{
Element = theElement;
Link = null;
}
}
```
and the `LinkedList`:
```
public class S_LinkedList
{
protected S_Node header;
protected S_Node tail;
public S_LinkedList()
{
header = new S_Node();
Tail = new S_Node();
header.Link = Tail;
}
// METHODS which i don't know how to do it (never use linkedlist before)
}
```
I need to organize this data using a “linkedlist data structure type”.
Contain all methods of linkedlist as Adding nodes to the list as I've learned -->(Insert),Deleting nodes from the list,as I've learned -->((Remove),Traversing the lists I've learned -->((PrintList),Finding a node in the list as I've learned -->((Find , FindPrevious) the problem I'm selflearning and I've tried to search the net and read more from the stupid C# that was a disaster.
I've done too much that I'm so sad that i don't know how to complete it .
I'm trying hard to Use this classes to write an executable program and to Test it .
If you don't want to help in completing this program (hope not) at least show me some real examples or ideas , after all I'm a selflearner geek :-)
|
```
the head of the list.
( item1
Element: student1
Next ------------> ( item2
) Element: student2
Next ------------> ( item3
) Element: student3
Next: null
)
the tail of the list.
```
First of all, for you to be able to write the StudentList class, you need to write the client code first. Client code is the code that uses your student list. Also, don't just write one thing at a time and throw it away. Instead write a whole bunch of [test] cases that exercise the different ways you *need* to interact with the StudentList. Write exceptional cases too. But don't be tempted to write a swiss-army knife of a class that does everything just because it can. Write the minimal amount of code that gets the job done.
How you need to use the class will heavily dictate how the class is constructed. This is the essence of TDD or Test Driven Design.
Your biggest problem that I can see is you have no idea how you want to use the class. So lets do that first.
```
// create a list of students and print them back out.
StudentList list = new StudentList();
list.Add( new Student("Bob", 1234, 2, 'A') );
list.Add( new Student("Mary", 2345, 4, 'C') );
foreach( Student student in list)
{
Console.WriteLine(student.Name);
}
```
I add the students to the list, and then I print them out.
I have no need for my client code to see inside the StudentList. Therefore StudentList hides how it implements the linked list. Let's write the basics of the StudentList.
```
public class StudentList
{
private ListNode _firstElement; // always need to keep track of the head.
private class ListNode
{
public Student Element { get; set; }
public ListNode Next { get; set; }
}
public void Add(Student student) { /* TODO */ }
}
```
StudentList is pretty basic. Internally it keeps track of the first or head nodes. Keeping track of the first node is obviously always required.
You also might wonder why ListNode is declared inside of StudentList. What happens is the ListNode class is only accessible to the StudentList class. This is done because StudentList doesn't want to give out the details to it's internal implementation because it is controlling all access to the list. StudentList never reveals how the list is implemented. Implementation hiding is an important OO concept.
If we did allow client code to directly manipulate the list, there'd be no point having StudentList is the first place.
Let's go ahead and implement the Add() operation.
```
public void Add(Student student)
{
if (student == null)
throw new ArgumentNullException("student");
// create the new element
ListNode insert = new ListNode() { Element = student };
if( _firstElement == null )
{
_firstElement = insert;
return;
}
ListNode current = _firstElement;
while (current.Next != null)
{
current = current.Next;
}
current.Next = insert;
}
```
The Add operation has to find the last item in the list and then puts the new ListNode at the end. Not terribly efficient though. It's currently O(N) and Adding will get slower as the list gets longer.
Lets optimize this a little for inserts and rewrite the Add method. To make Add faster all we need to do is have StudentList keep track of the last element in the list.
```
private ListNode _lastElement; // keep track of the last element: Adding is O(1) instead of O(n)
public void Add(Student student)
{
if( student == null )
throw new ArgumentNullException("student");
// create the new element
ListNode insert = new ListNode() { Element = student };
if (_firstElement == null)
{
_firstElement = insert;
_lastElement = insert;
return;
}
// fix up Next reference
ListNode last = _lastElement;
last.Next = insert;
_lastElement = insert;
}
```
Now, when we add, we don't iterate. We just need to keep track of the head and tail references.
Next up: the foreach loop. StudentList is a collection, and being a collection we want to enumerate over it and use C#'s `foreach`. The C# compiler can't iterate magically. In order to use the foreach loop We need to provide the compiler with an enumerator to use even if the code we write doesn't explicitly appear to use the enumerator.
First though, lets re-visit how we iterate over a linked list.
```
// don't add this to StudentList
void IterateOverList( ListNode current )
{
while (current != null)
{
current = current.Next;
}
}
```
Okay. so let's hook into C#'s foreach loop and return an enumerator. To do that we alter StudentList to implement IEnumerable. This is getting a little bit advanced, but you should be able to figure out what's going on.
```
// StudentList now implements IEnumerable<Student>
public class StudentList : IEnumerable<Student>
{
// previous code omitted
#region IEnumerable<Student> Members
public IEnumerator<Student> GetEnumerator()
{
ListNode current = _firstElement;
while (current != null)
{
yield return current.Element;
current = current.Next;
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
```
You should be able to spot the linked list iteration in there. Don't get thrown by the `yield` keyword. All yield is doing is returning the current student back to the foreach loop. The enumarator stops returning students when it gets to the end of the linked list.
And that's it! The code works the way we want it to.
---
\* This is by no means the only way to implement the list. I've opted to put the list logic in the StudentList and keep ListNode very basic. But the code does only what my very first unit test needs and nothing more. There are more optimizations you could make, and there are other ways of constructing the list.
Going forward: What you need to do is first create [unit] tests for what your code needs to do, then add the implementation you require.
---
\* fyi I also rewrote the Student class. Bad naming and strange casing from a C# persepctive, not to mention the code you provided doesn't compile. I prefer the `_` as a leader to private member variables. Some people don't like that, however you're new to this so I'll leave them in because they're easy to spot.
```
public class Student
{
private string _name;
private int _id;
private int _mark;
private char _letterGrade;
private Student() // hide default Constructor
{ }
public Student(string name, int id, int mark, char letterGrade) // Constructor
{
if( string.IsNullOrEmpty(name) )
throw new ArgumentNullException("name");
if( id <= 0 )
throw new ArgumentOutOfRangeException("id");
_name = name;
_id = id;
_mark = mark;
_letterGrade = letterGrade;
}
// read-only properties - compressed to 1 line for SO answer.
public string Name { get { return _name; } }
public int Id { get { return _id; } }
public int Mark { get { return _mark; } }
public char LetterGrade { get { return _letterGrade; } }
}
```
* check parameters
* pay attention to the different casing of properties, classes, and variables.
* hide the default constructor. Why do I want to create students without real data?
* provide some read-only properties.
+ This class is immutable as written (i.e. once you create a student, you can't change it).
|
248,046 |
<p>Oracle is giving me an error (ORA-00907: missing right parenthesis) when I run this query:</p>
<pre><code>select *
from reason_for_appointment
where reason_for_appointment_id in
(
select reason_for_appointment_id
from appointment_reason
where appointment_id = 11
order by appointment_reason_id
)
</code></pre>
<p>However, when I run just the subquery, there's no error.</p>
<p>Can anyone explain what the problem is?</p>
|
[
{
"answer_id": 248051,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 4,
"selected": false,
"text": "<p>The inner query results will never be displayed, so theres no point in doing the order by in the nested select. Apply it to the outer query instead. </p>\n"
},
{
"answer_id": 248526,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that ORDER BY is not permiited inside a subquery like this one. Why did you want to have one?</p>\n"
},
{
"answer_id": 248935,
"author": "darreljnz",
"author_id": 10538,
"author_profile": "https://Stackoverflow.com/users/10538",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like you're wanting to display the results from one table using an ordering defined in another table. An inner join should suffice.</p>\n\n<pre><code>select reason_for_appointment.*\nfrom reason_for_appointment rfa, appointment_reason ar\nwhere rfa.reason_for_appointment_id = ar.reason_for_appointment_id\nand ar.appointment_id = 11\norder by ar.appointment_reason_id;\n</code></pre>\n"
},
{
"answer_id": 461430,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>select * from reason_for_appointment where reason_for_appointment_id in (select reason_for_appointment_id from appointment_reason where appointment_id = 11 order by appointment_reason_id)</p>\n\n<p>try something like: \nwith auxiliar as (select reason_for_appointment_id from appointment_reason where appointment_id = 11 order by appointment_reason_id)\nselect reason_for_appointment_id from appointment_reason where reason_for_appointment_id in (select reason_for_appointment_id from auxiliar)</p>\n"
},
{
"answer_id": 461986,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "<p>If your goal is to have the output ordered, you simply want to move the ORDER BY outside of the subquery:</p>\n\n<pre><code>select * from reason_for_appointment where reason_for_appointment_id in\n (select reason_for_appointment_id from appointment_reason where appointment_id = 11)\n order by reason_for_appointment_id\n</code></pre>\n\n<p>( I'm assuming that where you wrote \"appointment_reason_id\" you meant \"reason_for_appointment_id\". If there really are two different columns with these names ... ouch.)</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
Oracle is giving me an error (ORA-00907: missing right parenthesis) when I run this query:
```
select *
from reason_for_appointment
where reason_for_appointment_id in
(
select reason_for_appointment_id
from appointment_reason
where appointment_id = 11
order by appointment_reason_id
)
```
However, when I run just the subquery, there's no error.
Can anyone explain what the problem is?
|
The problem is that ORDER BY is not permiited inside a subquery like this one. Why did you want to have one?
|
248,052 |
<p>I'm checking for existing of a row in in_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.</p>
<pre><code>select count(*)
from in_fmd i
where (description='GN')
and ( i.isbn in
(
select bwi_isbn from bw_isbn where orig_isbn = ?
union all
select cast(? as varchar) as isbn
)
)
</code></pre>
<p>I don't actually care about the count of the rows, but rather mere existence of at least one row.</p>
<p>This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement. It's PostgreSQL 8.1, if it matters.</p>
|
[
{
"answer_id": 248071,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": true,
"text": "<p>Why bother with the <code>UNION ALL</code></p>\n\n<pre><code>select count(*)\nfrom in_fmd i\nwhere (description='GN')\n and (\n i.isbn in (\n select bwi_isbn from bw_isbn where orig_isbn = ?\n )\n or i.isbn = cast(? as varchar)\n )\n</code></pre>\n\n<p>I would probably use a <code>LEFT JOIN</code>-style query instead of the <code>IN</code>, but that's more personal preference:</p>\n\n<pre><code>select count(*)\nfrom in_fmd i\nleft join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\nwhere (i.description='GN')\n and (\n bw_isbn.bwi_isbn is not null\n or i.isbn = cast(? as varchar)\n )\n</code></pre>\n\n<p>The inversion discussed over IM:</p>\n\n<pre><code>SELECT SUM(ct)\nFROM (\n select count(*) as ct\n from in_fmd i\n inner join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\n and i.isbn <> cast(? as varchar)\n and i.description = 'GN'\n\n UNION\n\n select count(*) as ct\n from in_fmd i\n where i.isbn = cast(? as varchar)\n and i.description = 'GN'\n) AS x\n</code></pre>\n"
},
{
"answer_id": 248075,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select count(*)\nfrom in_fmd i\nwhere description = 'GN'\n and exists (select 1 \n from bwi_isbn \n where bw_isbn.bwi_isbn = in_fmd.isbn)\n</code></pre>\n"
},
{
"answer_id": 248076,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I don't actually care about the count of the rows, but rather mere existence of at least one row.</p>\n</blockquote>\n\n<p>Then how about querying <code>SELECT ... LIMIT 1</code> and checking in the calling program whether you get one result row or not? </p>\n"
},
{
"answer_id": 494618,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT SUM(ct)\nFROM (select count(*) as ct\n from in_fmd i\n inner join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\n and i.isbn <> cast(? as varchar)\n and i.description = 'GN'\n UNION\n select count(*) as ct\n from in_fmd i\n where i.isbn = cast(? as varchar)\n and i.description = 'GN'\n ) AS x\n</code></pre>\n"
},
{
"answer_id": 494632,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 1,
"selected": false,
"text": "<p>apart from what other posters have noted , just changing </p>\n\n<p>select count(*)</p>\n\n<p>to</p>\n\n<p>exists(..) </p>\n\n<p>would <a href=\"http://www.postgresql.org/docs/7.4/interactive/functions-subquery.html\" rel=\"nofollow noreferrer\">improve things</a> quite a bit</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8454/"
] |
I'm checking for existing of a row in in\_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.
```
select count(*)
from in_fmd i
where (description='GN')
and ( i.isbn in
(
select bwi_isbn from bw_isbn where orig_isbn = ?
union all
select cast(? as varchar) as isbn
)
)
```
I don't actually care about the count of the rows, but rather mere existence of at least one row.
This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement. It's PostgreSQL 8.1, if it matters.
|
Why bother with the `UNION ALL`
```
select count(*)
from in_fmd i
where (description='GN')
and (
i.isbn in (
select bwi_isbn from bw_isbn where orig_isbn = ?
)
or i.isbn = cast(? as varchar)
)
```
I would probably use a `LEFT JOIN`-style query instead of the `IN`, but that's more personal preference:
```
select count(*)
from in_fmd i
left join bw_isbn
on bw_isbn.bwi_isbn = i.isbn
and bw_isbn.orig_isbn = ?
where (i.description='GN')
and (
bw_isbn.bwi_isbn is not null
or i.isbn = cast(? as varchar)
)
```
The inversion discussed over IM:
```
SELECT SUM(ct)
FROM (
select count(*) as ct
from in_fmd i
inner join bw_isbn
on bw_isbn.bwi_isbn = i.isbn
and bw_isbn.orig_isbn = ?
and i.isbn <> cast(? as varchar)
and i.description = 'GN'
UNION
select count(*) as ct
from in_fmd i
where i.isbn = cast(? as varchar)
and i.description = 'GN'
) AS x
```
|
248,067 |
<p>The only method provided by the DNN framework to get a module by ID also required a tab ID. What can I do if I don't <em>have</em> a tab ID?</p>
|
[
{
"answer_id": 248068,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "<p>The GetModule method off of the DotNetNuke.Entities.Modules.ModuleController class will accept a \"null\" value for tab ID if you don't have a tab ID. That is, try the following:</p>\n\n<pre><code>new ModuleController().GetModule(moduleId, DotNetNuke.Common.Utilities.Null.NullInteger)\n</code></pre>\n\n<p>See also <a href=\"http://weblogs.asp.net/briandukes/archive/2008/10/29/get-module-by-moduleid.aspx\" rel=\"noreferrer\">my blog post on the subject</a>.</p>\n"
},
{
"answer_id": 256004,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": -1,
"selected": false,
"text": "<p>Brian, I just took a look at the code for GetModule(), and there isn't any specific VB code in the framework that checks for the tabid being null. What's interesting though is that the stored procedure that is part of the SqlDataProvider selects rows from the Modules view that have a matching moduleid, no matter what tabid is... </p>\n\n<pre><code>ALTER PROCEDURE [dbo].[dnn_GetModule]\n\n @ModuleId int,\n @TabId int\n\nAS\nSELECT * \nFROM dbo.dnn_vw_Modules\nWHERE ModuleId = @ModuleId\nAND (TabId = @TabId or @TabId is null)\n</code></pre>\n\n<p>If I understand this correctly, this would return all the rows where moduleid is the one you specified, no matter if @tabid is null or not. That makes the @TabId rather pointless, don't you think?</p>\n"
},
{
"answer_id": 286310,
"author": "Don Worthley",
"author_id": 37225,
"author_profile": "https://Stackoverflow.com/users/37225",
"pm_score": 2,
"selected": false,
"text": "<p>One thing to watch out for when passing a null TabId to GetModule is that if you have a module that's installed on a number of different tabs, you'll be getting the first one back, so the values for TabId, TabModuleId and ModuleOrder will be based on that first instance, which may or may not be the instance you wanted.</p>\n\n<p>HTH,</p>\n\n<p>Don</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688/"
] |
The only method provided by the DNN framework to get a module by ID also required a tab ID. What can I do if I don't *have* a tab ID?
|
The GetModule method off of the DotNetNuke.Entities.Modules.ModuleController class will accept a "null" value for tab ID if you don't have a tab ID. That is, try the following:
```
new ModuleController().GetModule(moduleId, DotNetNuke.Common.Utilities.Null.NullInteger)
```
See also [my blog post on the subject](http://weblogs.asp.net/briandukes/archive/2008/10/29/get-module-by-moduleid.aspx).
|
248,072 |
<p>Evil or not evil?</p>
<pre><code>public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}
// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);
// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty);
</code></pre>
<p>Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).</p>
<p>Evil or not?</p>
|
[
{
"answer_id": 248089,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 6,
"selected": true,
"text": "<p>Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?</p>\n"
},
{
"answer_id": 248095,
"author": "David",
"author_id": 26144,
"author_profile": "https://Stackoverflow.com/users/26144",
"pm_score": 3,
"selected": false,
"text": "<p>Why would it be evil?</p>\n\n<p>Its purpose is clear: It raises the MyButtonClicked event.</p>\n\n<p>It does add a function call overhead, but in .NET it will either be optimized away or pretty fast anyway.</p>\n\n<p>It is slightly trivial, but it fixes my biggest complaint with C#.</p>\n\n<p>On the whole, I think it's a fantastic idea, and will probably steal it.</p>\n"
},
{
"answer_id": 248103,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 4,
"selected": false,
"text": "<p>You can always declare your events like this (not that i recommend it):</p>\n\n<pre><code>public event EventHandler<EventArgs> OnClicked = delegate { };\n</code></pre>\n\n<p>That way they have something assigned to them when you call them, so they don't throw a null pointer exception.</p>\n\n<p>You can probably get rid of the delegate keyword in C# 3.0... </p>\n"
},
{
"answer_id": 248110,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 0,
"selected": false,
"text": "<p>I wouldn't say it's evil, but I'm interested in how your extension method fits in with the </p>\n\n<pre><code>protected virtual OnSomeEvent(EventArgs e){ }\n</code></pre>\n\n<p>pattern and how it handles extensibility via inheritance. Does it presume all subclasses will handle the event instead of override a method?</p>\n"
},
{
"answer_id": 280688,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 3,
"selected": false,
"text": "<p>Coming from a java background this has always seemed odd to me. I think that no one listening to an event is perfectly valid. Especially when listeners are added and removed dynamically.</p>\n\n<p>To me this seems one of C#'s gottchas that causes bugs when people don't know / forget to check for null every time. </p>\n\n<p>Hiding this implementation detail seems a good plan as it's not helping readability to check for nulls every single time. I'm sure the MSFTs will say there's a performance gain in not constucting the event if no one is listening, but imho it is vastly outweighed by the pointless null pointer exceptions / reduction in readability in most business code.</p>\n\n<p>I'd also add these two methods to the class:</p>\n\n<pre><code> public static void Raise(this EventHandler handler, object sender)\n {\n Raise(handler, sender, EventArgs.Empty);\n }\n\n public static void Raise<TA>(this EventHandler<TA> handler, object sender, TA args)\n where TA : EventArgs\n {\n if (handler != null)\n {\n handler(sender, args);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 293414,
"author": "alvin",
"author_id": 15121,
"author_profile": "https://Stackoverflow.com/users/15121",
"pm_score": 3,
"selected": false,
"text": "<p>Don't forget to use <code>[MethodImpl(MethodImplOptions.NoInlining)]</code>, else its possible that it isn't thread safe. </p>\n\n<p>(Read that somewhere long ago, remembered it, googled and found <a href=\"http://blog.quantumbitdesigns.com/tag/events/\" rel=\"noreferrer\">http://blog.quantumbitdesigns.com/tag/events/</a> )</p>\n"
},
{
"answer_id": 2288042,
"author": "Bob",
"author_id": 49548,
"author_profile": "https://Stackoverflow.com/users/49548",
"pm_score": 0,
"selected": false,
"text": "<p>Although I wouldn't describ it as <em>evil</em>, it still has a negative implication, as it adds unnecessary overhead:</p>\n\n<p>When calling</p>\n\n<p><code>myEvent.Raise(this, new EventArgs());</code></p>\n\n<p>the object EventArgs is initialized in all situations, even if no-one subscribed to myEvent.</p>\n\n<p>When using </p>\n\n<pre><code>if (myEvent!= null) {\n myEvent(this, new EventArgs());\n}\n</code></pre>\n\n<p>EventArgs is only initialized if someone subscribed to myEvent.</p>\n"
},
{
"answer_id": 7330226,
"author": "Prakash",
"author_id": 557978,
"author_profile": "https://Stackoverflow.com/users/557978",
"pm_score": -1,
"selected": false,
"text": "<p>Throwing an exception when there are no handlers is not really preferable by the most. If it does not have an handlers it is better to be empty rather than null.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
Evil or not evil?
```
public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}
// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);
// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty);
```
Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).
Evil or not?
|
Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?
|
248,102 |
<p>By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.</p>
|
[
{
"answer_id": 248116,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<pre><code>:set nowrap\n</code></pre>\n\n<p>There is also the <code>linebreak</code> option that controls whether wrapped text is broken at word boundaries or not.</p>\n"
},
{
"answer_id": 248124,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://www.vim.org/htmldoc/quickref.html\" rel=\"nofollow noreferrer\">quickref</a> suggests (no)wrap</p>\n"
},
{
"answer_id": 248125,
"author": "m0j0",
"author_id": 31319,
"author_profile": "https://Stackoverflow.com/users/31319",
"pm_score": 4,
"selected": false,
"text": "<p>In your vimrc, create a function such as this:</p>\n\n<pre><code>:function ToggleWrap()\n: if (&wrap == 1)\n: set nowrap\n: else\n: set wrap\n: endif\n:endfunction\n</code></pre>\n\n<p>Then map a key (such as F9) to call this function, like so:</p>\n\n<pre><code>map <F9> :call ToggleWrap()<CR>\nmap! <F9> ^[:call ToggleWrap()<CR>\n</code></pre>\n\n<p>Whenever you press F9, it should toggle your wrapping on and off.</p>\n"
},
{
"answer_id": 248165,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 6,
"selected": false,
"text": "<p>I think what you want is:</p>\n\n<pre><code>:set wrap!\n</code></pre>\n\n<p>This will toggle line wrapping.</p>\n\n<p>More about using ! (bang) to alter commands can be found at:</p>\n\n<pre><code>:help :_!\n</code></pre>\n"
},
{
"answer_id": 60289964,
"author": "Shyam Habarakada",
"author_id": 850996,
"author_profile": "https://Stackoverflow.com/users/850996",
"pm_score": 2,
"selected": false,
"text": "<p>Add the following to have CTRL+W toggle wrapping. You can change it to some other key if you don't want <code>w</code> to be it.</p>\n\n<pre><code>map <C-w> :set wrap!<CR>\n</code></pre>\n"
},
{
"answer_id": 60293010,
"author": "D. Ben Knoble",
"author_id": 4400820,
"author_profile": "https://Stackoverflow.com/users/4400820",
"pm_score": 0,
"selected": false,
"text": "<p>I happen to like tpope’s unimpaired plugin, where <code>yow</code> will toggle wrap settings. </p>\n"
},
{
"answer_id": 74378126,
"author": "tothedistance",
"author_id": 13947038,
"author_profile": "https://Stackoverflow.com/users/13947038",
"pm_score": 0,
"selected": false,
"text": "<p>For those who want to change the text instead of just visual effect, for example in git commit, just press <code>qt</code> in a roll and press enter. This will properly wrap the current paragraph your cursor is in. The paragraph is only delimited by blank lines. or you can select some area to press <code>qt</code>.</p>\n<p>I found this by total accident.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.
|
```
:set nowrap
```
There is also the `linebreak` option that controls whether wrapped text is broken at word boundaries or not.
|
248,118 |
<p>What does this mean exactly? I'm doing something like this:</p>
<pre><code>File.Copy(@"\\foo\bar\baz.txt", @"c:\test\baz.txt");
</code></pre>
<p>MSDN doesn't describe this exception except in general terms, and googling around just yields tables of error codes.</p>
<p>I've confirmed the source file exists, and I'm 99% sure that I have the permissions to copy the file to the destination location.</p>
|
[
{
"answer_id": 248851,
"author": "Andrew Theken",
"author_id": 32238,
"author_profile": "https://Stackoverflow.com/users/32238",
"pm_score": 0,
"selected": false,
"text": "<p>You will get this error if the destination file already exists. I would also confirm that the account you're running the code under has access to the UNC \\foo\\bar\\baz.txt</p>\n"
},
{
"answer_id": 253624,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 3,
"selected": true,
"text": "<p>Check this article for some information about using symlinks in .Net: \"<a href=\"http://www.codeproject.com/KB/files/JunctionPointsNet.aspx\" rel=\"nofollow noreferrer\">Manipulating NTFS Junction Points in .NET</a>\".</p>\n\n<p>According to this article:</p>\n\n<blockquote>\n <p>\"In particular the .NET libraries does\n not include any functionality for\n creating or querying properties of\n Junction Points\"</p>\n</blockquote>\n\n<p>But there is a method how to actually get the target of the symlink, and then you'll be able to use File.Copy with it.</p>\n"
},
{
"answer_id": 599612,
"author": "Fowl",
"author_id": 45583,
"author_profile": "https://Stackoverflow.com/users/45583",
"pm_score": 1,
"selected": false,
"text": "<p>By default local evaluation of remote symbolic links is disabled. </p>\n\n<p>You could use fsutil to change that setting or you could delve into unmanaged code and resolve the link yourself.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16320/"
] |
What does this mean exactly? I'm doing something like this:
```
File.Copy(@"\\foo\bar\baz.txt", @"c:\test\baz.txt");
```
MSDN doesn't describe this exception except in general terms, and googling around just yields tables of error codes.
I've confirmed the source file exists, and I'm 99% sure that I have the permissions to copy the file to the destination location.
|
Check this article for some information about using symlinks in .Net: "[Manipulating NTFS Junction Points in .NET](http://www.codeproject.com/KB/files/JunctionPointsNet.aspx)".
According to this article:
>
> "In particular the .NET libraries does
> not include any functionality for
> creating or querying properties of
> Junction Points"
>
>
>
But there is a method how to actually get the target of the symlink, and then you'll be able to use File.Copy with it.
|
248,149 |
<p><code>Connection.close()</code> may throw <code>SqlException</code>, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them). </p>
<p>Normally I would write:</p>
<pre><code> try{
connection.close();
}catch(Exception e) {}
</code></pre>
<p>Or </p>
<pre><code> try{
connection.close();
}catch(Exception e) {
logger.log(e.getMessage(), e);
}
</code></pre>
<p>The question is:</p>
<ol>
<li>Is it bad practice (and has anyone had problems when ignoring such exceptions).</li>
<li>When <code>Connection.close()</code> does throw any exception. </li>
<li>If it is bad how should I handle the exception. </li>
</ol>
<p>Comment: </p>
<p>I know that discarding exceptions is evil, but I'm reffering only to exceptions thrown when closing a connection (and as I've seen this is fairly common in this case). </p>
<p>Does anyone know when <code>Connection.close()</code> may throw anything? </p>
|
[
{
"answer_id": 248167,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 4,
"selected": false,
"text": "<p>In general, I've had days wasted by people throwing away exceptions like that.</p>\n\n<p>I recommend following a few basic rules with exceptions:</p>\n\n<p>If you are ABSOLUTELY SURE you will NEVER cause a problem with a checked exception, catch JUST that exception and comment exactly why you don't need to handle it. (Sleep throws an InterruptedException that can always be ignored unless you actually are interested in it, but honestly this is the only case I usually ignore--even at that, if you never get it, what's the cost of logging it?)</p>\n\n<p>If you are not sure, but you may get it occasionally, catch and log a stack trace just so that if it is causing a problem, it can be found. Again, catch only the exception you need to.</p>\n\n<p>If you don't see any way the checked exception can be thrown, catch it and re-throw it as an unchecked exception.</p>\n\n<p>If you know exactly what is causing the exception, catch it and log exactly why, you don't really need a stack trace in this case if you are very clear as to what's causing it (and you might mention the class that's logging it if you're not already using log4j or something.</p>\n\n<p>It sounds like your problem would fall into the last category, and for this kind of a catch, never do what you wrote (Exception e), always do the specific exception just in case some unchecked exception is thrown (bad parameters, null pointer, ...)</p>\n\n<p><strong>Update:</strong> The main problem here is that Checked Exceptions are ungood. The only highly used language they exist in is Java. They are neat in theory, but in action they cause this behavior of catch and hide that you don't get with unchecked exceptions.</p>\n\n<p>A lot of people have commented on the fact that I said that hiding them is okay sometimes. To be specific, the one case I can think of is:</p>\n\n<pre><code>try {\n Thread.sleep(1000);\ncatch (InterruptedException e) {\n // I really don't care if this sleep is interrupted!\n}\n</code></pre>\n\n<p>I suppose the main reason I feel this use is okay is because this use of InterruptedException is an abuse of the checked exception pattern in the first place, it's communicating the result of a sleep more than indicating an exception condition.</p>\n\n<p>It would have made much more sense to have:</p>\n\n<pre><code>boolean interrupted=Thread.sleep(1000);\n</code></pre>\n\n<p>But they were very proud of their new checked exception pattern when they first created Java (understandably so, it's really neat in concept--only fails in practice)</p>\n\n<p>I can't imagine another case where this is acceptable, so perhaps I should have listed this as <strong>the</strong> single case where it might be valid to ignore an exception.</p>\n"
},
{
"answer_id": 248174,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 2,
"selected": false,
"text": "<p>I personally like your second idea of at least logging the error. Because you're catching Exception, it's theoretically possible to catch something other than a SQL Exception. I'm not sure what could happen or how rare (like out of memory exceptions, etc) but supressing all errors doesn't seem right to me. </p>\n\n<p>If you want to suppress errors, I would do it only to very specific ones you know should be handled that way.</p>\n\n<p>Hypothecial situation: what if your sql had an open transaction, and closing the connection caused an exceptino because of that, would you want to suppress that error? Even suppressing SQLExceptions might be a little dangerous.</p>\n"
},
{
"answer_id": 248210,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 1,
"selected": false,
"text": "<p>You have to handle the exception. It is not a bad practice. Imagine you lost the network just before closing the dabatase connection. It will probably throw the exception.</p>\n\n<p>Is it rare ? Yes. I suppose that's what they are called exceptions and that is not a reason to ignore it. Remember that if it could fail, it will fail.</p>\n\n<p>You should also think about whether it is possible to have a null connection at this point (it would cause a NullPointerException) or not.</p>\n\n<pre><code>if (connection != null) {\n try { \n connection.close(); \n } catch (SQLException sqle) { \n logger.log(e.getMessage(), e); \n }\n}\n</code></pre>\n"
},
{
"answer_id": 248226,
"author": "a-sak",
"author_id": 325613,
"author_profile": "https://Stackoverflow.com/users/325613",
"pm_score": 0,
"selected": false,
"text": "<p>From my experience ignoring an exception is never a good idea.\nBelieve me, the production support engineers and analysts will thank you a tonne if you logged the exception.</p>\n\n<p>Also, if you are using the right Logging framework, there would be zero or minimal performance impact of the exception.</p>\n"
},
{
"answer_id": 248402,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 1,
"selected": false,
"text": "<p>In an ideal world, you should never do nothing on an exception, of course, in an ideal world, you would never get an exception either 8-)</p>\n\n<p>So, you have to examine the impacts of the various options.</p>\n\n<p>Log only: Database operations are all finished, nothing left to do but clean up the resources. If an exception occurs at this point, it most likely has no impact on the work performed, so logging the error should suffice. Of course, if an error occurs during logging, then you basically have to handle failed database operation that didn't actually fail.</p>\n\n<p>Empty handler: Database operations are all finished, nothing left to do but clean up the resources. If an exception occurs at this point, it most likely has no impact on the work performed, so the method returns successfully. The next database access may run into the same problem, but it should occur at the start of a transaction, where it will rightly fail and then get handled appropriately. If the problem has fixed itself, then there will be no indication that anything ever went wrong.</p>\n\n<p>It is a pretty typical scenario to put a close() operation(s) in a finally block to ensure that cleanup occurs, since we don't want any other failures to inhibit the resource cleanup. If no error has occurred, then your method should not fail when its operation has successfully completed. In this case, empty exception handling is quite normal. </p>\n\n<p>Of course opinions will vary.</p>\n"
},
{
"answer_id": 248920,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 3,
"selected": false,
"text": "<p>At the very minimum, <em>always</em> <strong>always</strong> <strong><em>always</em></strong> log exceptions that you are catching and not acting on. </p>\n\n<p>Silently caught exceptions that are swallowed without the tiniest peep are the worst.</p>\n"
},
{
"answer_id": 248991,
"author": "SWD",
"author_id": 3034,
"author_profile": "https://Stackoverflow.com/users/3034",
"pm_score": 0,
"selected": false,
"text": "<p>if this is an \"error that never happens\" case then I will just rethrow an Exception and hope no one catches it.<br>\nif this is any other case I will probably log it</p>\n"
},
{
"answer_id": 249023,
"author": "Fábio",
"author_id": 9458,
"author_profile": "https://Stackoverflow.com/users/9458",
"pm_score": 1,
"selected": false,
"text": "<p>You could also throw a RuntimeException:</p>\n\n<pre><code>try {\n connection.close();\n } catch(Exception e) {\n throw new RuntimeException(e); \n }\n</code></pre>\n\n<p>You won't have to change your method signature and will be able to use the Exception.getCause method later on to find the cause of the problem.</p>\n"
},
{
"answer_id": 249149,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 5,
"selected": true,
"text": "<p>Actually, what you're doing is (almost) best practice :-) here's what I saw in Spring's JdbcUtils.java. So, you might want to add\nanother Catch block.</p>\n\n<pre><code>/**\n * Close the given ResultSet and ignore any thrown exception.\n * This is useful for typical finally blocks in manual code.\n * @param resultSet the ResultSet to close\n * @see javax.resource.cci.ResultSet#close()\n */\nprivate void closeResultSet(ResultSet resultSet) {\n if (resultSet != null) {\n try {\n resultSet.close();\n }\n catch (SQLException ex) {\n logger.debug(\"Could not close ResultSet\", ex);\n }\n catch (Throwable ex) {\n // We don't trust the driver: It might throw RuntimeException or Error.\n logger.debug(\"Unexpected exception on closing ResultSet\", ex);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 626449,
"author": "Brian Agnew",
"author_id": 12960,
"author_profile": "https://Stackoverflow.com/users/12960",
"pm_score": 1,
"selected": false,
"text": "<p>Note that <a href=\"http://commons.apache.org/dbutils/apidocs/org/apache/commons/dbutils/DbUtils.html\" rel=\"nofollow noreferrer\">Apache Commons DButils</a> provides a <code>closeQuietly()</code> method, that you can use to avoid cluttering your code with 'redundant' catches. Note I'm not advocating swallowing exceptions, but for this <code>close()</code> scenario I think it's generally acceptable.</p>\n"
},
{
"answer_id": 2574109,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 0,
"selected": false,
"text": "<p>If you can handle it, then do so (and log it if it was unexpected). If you cannot handle it, then rethrow it properly so some code above can handle it.</p>\n\n<p>Silently swallowing exceptions is leaving out crucial information for the person to fix the code.</p>\n"
},
{
"answer_id": 12544099,
"author": "Sankar",
"author_id": 1690448,
"author_profile": "https://Stackoverflow.com/users/1690448",
"pm_score": 0,
"selected": false,
"text": "<p>Its a better practice to handle the exception at the time of closing the connection to the database. Because, at later some point of time in your code, if you are trying to access the statement or resultset objects then it will automatically raise an exception. So, Better to handle the exception.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
] |
`Connection.close()` may throw `SqlException`, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them).
Normally I would write:
```
try{
connection.close();
}catch(Exception e) {}
```
Or
```
try{
connection.close();
}catch(Exception e) {
logger.log(e.getMessage(), e);
}
```
The question is:
1. Is it bad practice (and has anyone had problems when ignoring such exceptions).
2. When `Connection.close()` does throw any exception.
3. If it is bad how should I handle the exception.
Comment:
I know that discarding exceptions is evil, but I'm reffering only to exceptions thrown when closing a connection (and as I've seen this is fairly common in this case).
Does anyone know when `Connection.close()` may throw anything?
|
Actually, what you're doing is (almost) best practice :-) here's what I saw in Spring's JdbcUtils.java. So, you might want to add
another Catch block.
```
/**
* Close the given ResultSet and ignore any thrown exception.
* This is useful for typical finally blocks in manual code.
* @param resultSet the ResultSet to close
* @see javax.resource.cci.ResultSet#close()
*/
private void closeResultSet(ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException ex) {
logger.debug("Could not close ResultSet", ex);
}
catch (Throwable ex) {
// We don't trust the driver: It might throw RuntimeException or Error.
logger.debug("Unexpected exception on closing ResultSet", ex);
}
}
}
```
|
248,161 |
<p>I got curious by <a href="http://dotnet.kapenilattex.com/?p=93" rel="nofollow noreferrer">Jon Limjap's interview mishap</a> and started to look for efficient ways to do palindrome detection. I checked the <a href="https://stackoverflow.com/questions/228518/palindrome-golf">palindrome golf</a> answers and it seems to me that in the answers are two algorithms only, reversing the string and checking from tail and head.</p>
<pre class="lang-py prettyprint-override"><code>def palindrome_short(s):
length = len(s)
for i in xrange(0,length/2):
if s[i] != s[(length-1)-i]: return False
return True
def palindrome_reverse(s):
return s == s[::-1]
</code></pre>
<p>I think neither of these methods are used in the detection of exact palindromes in huge DNA sequences. I looked around a bit and didn't find any free article about what an ultra efficient way for this might be.</p>
<p>A good way might be parallelizing the first version in a divide-and-conquer approach, assigning a pair of char arrays 1..n and length-1-n..length-1 to each thread or processor. </p>
<p>What would be a better way?</p>
<p>Do you know any?</p>
|
[
{
"answer_id": 248187,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>There isn't, unless you do a fuzzy match. Which is what they probably do in DNA (I've done EST <em>searching</em> in DNA with smith-waterman, but that is obviously much harder then matching for a palindrome or reverse-complement in a sequence).</p>\n"
},
{
"answer_id": 248189,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>Obviously, you're not going to be able to get better than O(n) asymptotic efficiency, since each character must be examined at least once. You can get better multiplicative constants, though.</p>\n\n<p>For a single thread, you can get a speedup using assembly. You can also do better by examining data in chunks larger than a byte at a time, but this may be tricky due to alignment considerations. You'll do even better to use SIMD, if you can examine chunks as large as 16 bytes at a time.</p>\n\n<p>If you wanted to parallelize it, you could divide the string into N pieces, and have processor <code>i</code> compare the segment <code>[i*n/2, (i+1)*N/2)</code> with the segment <code>[L-(i+1)*N/2, L-i*N/2)</code>.</p>\n"
},
{
"answer_id": 248191,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "<p>They are both in O(N) so I don't think there is any particular efficiency problem with any of these solutions. Maybe I am not creative enough but I can't see how would it be possible to compare N elements in less than N steps, so something like O(log N) is definitely not possible IMHO.</p>\n\n<p>Pararellism might help, but it still wouldn't change the big-Oh rank of the algorithm since it is equivalent to running it on a faster machine.</p>\n"
},
{
"answer_id": 248214,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": true,
"text": "<p>Given only one palindrome, you will have to do it in O(N), yes. You can get more efficiency with multi-processors by splitting the string as you said.</p>\n<p>Now say you want to do exact DNA matching. These strings are thousands of characters long, and they are very repetitive. This gives us the opportunity to optimize.</p>\n<p>Say you split a 1000-char long string into 5 pairs of 100,100. The code will look like this:</p>\n<pre><code>isPal(w[0:100],w[-100:]) and isPal(w[101:200], w[-200:-100]) ...\n</code></pre>\n<p>etc... The first time you do these matches, you will have to process them. However, you can add all results you've done into a hashtable mapping pairs to booleans:</p>\n<pre><code>isPal = {("ATTAGC", "CGATTA"): True, ("ATTGCA", "CAGTAA"): False}\n</code></pre>\n<p>etc... this will take way too much memory, though. For pairs of 100,100, the hash map will have 2*4^100 elements. Say that you only store two 32-bit hashes of strings as the key, you will need something like 10^55 megabytes, which is ridiculous.</p>\n<p>Maybe if you use smaller strings, the problem can be tractable. Then you'll have a huge hashmap, but at least palindrome for let's say 10x10 pairs will take O(1), so checking if a 1000 string is a palindrome will take 100 lookups instead of 500 compares. It's still O(N), though...</p>\n"
},
{
"answer_id": 486278,
"author": "Demur Rumed",
"author_id": 40172,
"author_profile": "https://Stackoverflow.com/users/40172",
"pm_score": -1,
"selected": false,
"text": "<p>With Python, short code can be faster since it puts the load into the faster internals of the VM (And there is the whole cache and other such things)</p>\n\n<pre><code>def ispalin(x):\n return all(x[a]==x[-a-1] for a in xrange(len(x)>>1))\n</code></pre>\n"
},
{
"answer_id": 801422,
"author": "drnk",
"author_id": 77619,
"author_profile": "https://Stackoverflow.com/users/77619",
"pm_score": 2,
"selected": false,
"text": "<p>Another variant of your second function. We need no check equals of the right parts of normal and reverse strings.</p>\n\n<pre><code>def palindrome_reverse(s):\n l = len(s) / 2\n return s[:l] == s[l::-1]\n</code></pre>\n"
},
{
"answer_id": 3286162,
"author": "ZXX",
"author_id": 374835,
"author_profile": "https://Stackoverflow.com/users/374835",
"pm_score": 0,
"selected": false,
"text": "<p>Comparing from the center is always much more efficient since you can bail out early on a miss but it alwo allows you to do faster max palindrome search, regardless of whether you are looking for the maximal radius or all non-overlapping palindromes.</p>\n\n<p>The only real paralellization is if you have multiple independent strings to process. Splitting into chunks will waste a lot of work for every miss and there's always much more misses than hits.</p>\n"
},
{
"answer_id": 45397145,
"author": "mahashwetha",
"author_id": 1229998,
"author_profile": "https://Stackoverflow.com/users/1229998",
"pm_score": -1,
"selected": false,
"text": "<p>You can use a hashtable to put the character and have a counter variable whose value increases everytime you find an element not in table/map. If u check and find element thats already in table decrease the count.</p>\n\n<pre><code>For odd lettered string the counter should be back to 1 and for even it should hit 0.I hope this approach is right.\n\nSee below the snippet.\ns->refers to string\neg: String s=\"abbcaddc\";\nHashtable<Character,Integer> textMap= new Hashtable<Character,Integer>();\n char charA[]= s.toCharArray();\n for(int i=0;i<charA.length;i++)\n {\n\n if(!textMap.containsKey(charA[i]))\n { \n textMap.put(charA[i], ++count);\n\n }\n else\n {\n textMap.put(charA[i],--count);\n\n\n }\n if(length%2 !=0)\n {\n if(count == 1)\n System.out.println(\"(odd case:PALINDROME)\");\n else\n System.out.println(\"(odd case:not palindrome)\");\n }\n else if(length%2==0) \n {\n if(count ==0)\n System.out.println(\"(even case:palindrome)\");\n else\n System.out.println(\"(even case :not palindrome)\");\n }\n</code></pre>\n"
},
{
"answer_id": 53533419,
"author": "Tangang Atanga",
"author_id": 10720960,
"author_profile": "https://Stackoverflow.com/users/10720960",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public class Palindrome{\n private static boolean isPalindrome(String s){\n if(s == null)\n return false; //unitialized String ? return false\n if(s.isEmpty()) //Empty Strings is a Palindrome \n return true;\n //we want check characters on opposite sides of the string \n //and stop in the middle <divide and conquer>\n int left = 0; //left-most char \n int right = s.length() - 1; //right-most char\n\n while(left < right){ //this elegantly handles odd characters string \n if(s.charAt(left) != s.charAt(right)) //left char must equal \n return false; //right else its not a palindrome\n left++; //converge left to right \n right--;//converge right to left \n }\n return true; // return true if the while doesn't exit \n }\n}\n</code></pre>\n\n<p>though we are doing n/2 calculations its still O(n)\nthis can done also using threads, but calculations get messy, best to avoid it. this doesn't test for special characters and is case sensitive. I have code that does it, but this code can be modified to handle that easily. </p>\n"
},
{
"answer_id": 71468254,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": 0,
"selected": false,
"text": "<p>On top of what others said, I'd also add a few pre-check criteria for really large inputs :</p>\n<pre><code>quick check whether tail-character matches \n head character \n\nif NOT, just early exit by returning Boolean-False\n\nif (input-length < 4) { \n\n # The quick check just now already confirmed it's palindrome \n\n return Boolean-True \n\n} else if (200 < input-length) {\n \n # adjust this parameter to your preferences\n #\n # e.g. make it 20 for longer than 8000 etc\n # or make it scale to input size,\n # either logarithmically, or a fixed ratio like 2.5%\n #\n reverse last ( N = 4 ) characters/bytes of the input \n\n if that **DOES NOT** match first N chars/bytes {\n\n return boolean-false # early exit\n # no point to reverse rest of it\n # when head and tail don't even match\n } else {\n \n if N was substantial\n\n trim out the head and tail of the input\n you've confirmed; avoid duplicated work\n\n remember to also update the variable(s)\n you've elected to track the input size \n\n }\n\n [optional 1 : if that substring of N characters you've \n just checked happened to all contain the\n same character, let's call it C,\n \n then locate the index position, P, for the first \n character that isn't C\n \n if P == input-size \n\n then you've already proven\n the entire string is a nonstop repeat \n of one single character, which, by def, \n must be a palindrome\n\n then just return Boolean-True\n\n\n but the P is more than the half-way point,\n you've also proven it cannot possibly be a \n palindrome, because second half contains a \n component that doesn't exist in first half,\n \n\n then just return Boolean-False ]\n\n\n [optional 2 : for extremely long inputs, \n like over 200,000 chars,\n take the N chars right at the middle of it,\n and see if the reversed one matches\n \n if that fails, then do early exit and save time ]\n\n }\n\n if all pre-checks passed,\n then simply do it BAU style :\n\n reverse second-half of it, \n and see if it's same as first half\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
I got curious by [Jon Limjap's interview mishap](http://dotnet.kapenilattex.com/?p=93) and started to look for efficient ways to do palindrome detection. I checked the [palindrome golf](https://stackoverflow.com/questions/228518/palindrome-golf) answers and it seems to me that in the answers are two algorithms only, reversing the string and checking from tail and head.
```py
def palindrome_short(s):
length = len(s)
for i in xrange(0,length/2):
if s[i] != s[(length-1)-i]: return False
return True
def palindrome_reverse(s):
return s == s[::-1]
```
I think neither of these methods are used in the detection of exact palindromes in huge DNA sequences. I looked around a bit and didn't find any free article about what an ultra efficient way for this might be.
A good way might be parallelizing the first version in a divide-and-conquer approach, assigning a pair of char arrays 1..n and length-1-n..length-1 to each thread or processor.
What would be a better way?
Do you know any?
|
Given only one palindrome, you will have to do it in O(N), yes. You can get more efficiency with multi-processors by splitting the string as you said.
Now say you want to do exact DNA matching. These strings are thousands of characters long, and they are very repetitive. This gives us the opportunity to optimize.
Say you split a 1000-char long string into 5 pairs of 100,100. The code will look like this:
```
isPal(w[0:100],w[-100:]) and isPal(w[101:200], w[-200:-100]) ...
```
etc... The first time you do these matches, you will have to process them. However, you can add all results you've done into a hashtable mapping pairs to booleans:
```
isPal = {("ATTAGC", "CGATTA"): True, ("ATTGCA", "CAGTAA"): False}
```
etc... this will take way too much memory, though. For pairs of 100,100, the hash map will have 2\*4^100 elements. Say that you only store two 32-bit hashes of strings as the key, you will need something like 10^55 megabytes, which is ridiculous.
Maybe if you use smaller strings, the problem can be tractable. Then you'll have a huge hashmap, but at least palindrome for let's say 10x10 pairs will take O(1), so checking if a 1000 string is a palindrome will take 100 lookups instead of 500 compares. It's still O(N), though...
|
248,219 |
<p>i know how to import an sql file via the cli:</p>
<pre><code>mysql -u USER -p DBNAME < dump.sql
</code></pre>
<p>but that's if the dump.sql file is local. how could i use a file on a remote server?</p>
|
[
{
"answer_id": 248228,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>I'd use <a href=\"http://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">wget</a> to either download it to a file or pipe it in.</p>\n"
},
{
"answer_id": 248329,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 6,
"selected": true,
"text": "<p>You didn't say what network access you have to the remote server.</p>\n\n<p>Assuming you have SSH access to the remote server, you could pipe the results of a remote mysqldump to the mysql command. I just tested this, and it works fine:</p>\n\n<pre><code>ssh remote.com \"mysqldump remotedb\" | mysql localdb\n</code></pre>\n\n<p>I put stuff like user, password, host into <code>.my.cnf</code> so I'm not constantly typing them -- annoying and bad for security on multiuser systems, you are putting passwords in cleartext into your bash_history! But you can easily add the <code>-u -p -h</code> stuff back in on both ends if you need it:</p>\n\n<pre><code>ssh remote.com \"mysqldump -u remoteuser -p'remotepass' remotedb\" | mysql -u localuser -p'localpass' localdb\n</code></pre>\n\n<p>Finally, you can pipe through <code>gzip</code> to compress the data over the network:</p>\n\n<pre><code>ssh remote.com \"mysqldump remotedb | gzip\" | gzip -d | mysql localdb\n</code></pre>\n"
},
{
"answer_id": 31727748,
"author": "skh",
"author_id": 2772071,
"author_profile": "https://Stackoverflow.com/users/2772071",
"pm_score": 2,
"selected": false,
"text": "<p>Just thought I'd add to this as I was seriously low on space on my local VM, but if the .sql file exists already on the remote server you could do;</p>\n\n<pre><code>ssh <ip-address> \"cat /path/to/db.sql\" | mysql -u <user> -p<password> <dbname>\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18285/"
] |
i know how to import an sql file via the cli:
```
mysql -u USER -p DBNAME < dump.sql
```
but that's if the dump.sql file is local. how could i use a file on a remote server?
|
You didn't say what network access you have to the remote server.
Assuming you have SSH access to the remote server, you could pipe the results of a remote mysqldump to the mysql command. I just tested this, and it works fine:
```
ssh remote.com "mysqldump remotedb" | mysql localdb
```
I put stuff like user, password, host into `.my.cnf` so I'm not constantly typing them -- annoying and bad for security on multiuser systems, you are putting passwords in cleartext into your bash\_history! But you can easily add the `-u -p -h` stuff back in on both ends if you need it:
```
ssh remote.com "mysqldump -u remoteuser -p'remotepass' remotedb" | mysql -u localuser -p'localpass' localdb
```
Finally, you can pipe through `gzip` to compress the data over the network:
```
ssh remote.com "mysqldump remotedb | gzip" | gzip -d | mysql localdb
```
|
248,222 |
<p>What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?</p>
<p>For example. If I have some Products and I'm pulling from a database</p>
<p>explicit way:</p>
<pre><code>public List<Product> GetProduct(int productId) { // return a List }
public List<Product> GetProductByCategory(Category category) { // return a List }
public List<Product> GetProductByName(string Name ) { // return a List }
</code></pre>
<p>overloaded way:</p>
<pre><code>public List<Product> GetProducts() { // return a List of all products }
public List<Product> GetProducts(Category category) { // return a List by Category }
public List<Product> GetProducts(string searchString ) { // return a List by search string }
</code></pre>
<p>I realize you may get into a problem with <strong>similar signatures</strong>, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to <strong>overload a method</strong> to reduce the number of methods you have and for clarity, <strong>or</strong> should <strong>each method</strong> that filters the data a different way <strong>have a different method name</strong>?</p>
|
[
{
"answer_id": 248233,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 4,
"selected": false,
"text": "<p>As far as I can tell, you won't have fewer methods, just fewer names. I generally prefer the overloaded method system of naming, but I don't think it really makes much difference as long as you comment and document your code well (which you should do in either case).</p>\n"
},
{
"answer_id": 248237,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to use a Query object to build the \"WHERE Clause\". So you would have only one method like this:</p>\n\n<pre><code>public List<Product> GetProducts(Query query)\n</code></pre>\n\n<p>The Query object contains the condidition expressed in an Object Oriented way. The GetProducts obtain the query by \"parsing\" the Query object.</p>\n\n<p><a href=\"http://martinfowler.com/eaaCatalog/queryObject.html\" rel=\"nofollow noreferrer\">http://martinfowler.com/eaaCatalog/queryObject.html</a> </p>\n"
},
{
"answer_id": 248239,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 3,
"selected": false,
"text": "<p>You probably need some project-wide standards. Personally, I find the overloaded methods much easier to read. If you have the IDE support, go for it.</p>\n"
},
{
"answer_id": 248240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I like overloading my methods so that later on in the intellisense I don't have a million of the same method. And it seems more logical to me to have it just overloaded instead of having it named differently a dozen times.</p>\n"
},
{
"answer_id": 248247,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 4,
"selected": false,
"text": "<p>Can you overuse it? well, yes, that is true.</p>\n\n<p>However, the examples you've given are perfect examples of when to use method overloading. They all perform the same function, why give them different names just because you're passing different types to them. </p>\n\n<p>The main rule, is doing the clearest, easiest to understand thing. Don't use overloading just to be slick or clever, do it when it makes sense. Other developers might be working on this code as well. You want to make it as easy as possible for them to pick up and understand the code and be able to implement changes without implementing bugs. </p>\n"
},
{
"answer_id": 248267,
"author": "JTew",
"author_id": 25372,
"author_profile": "https://Stackoverflow.com/users/25372",
"pm_score": 1,
"selected": false,
"text": "<p>Yes you can overuse it, however here is another concept which could help keep the usage of it under control ...</p>\n\n<p>If you are using .Net 3.5+ and need to apply multiple filters you are probably better to use IQueryable and chaining i.e. </p>\n\n<pre><code>GetQuery<Type>().ApplyCategoryFilter(category).ApplyProductNameFilter(productName);\n</code></pre>\n\n<p>That way you can reuse the filtering logic over and over whereever you need it.</p>\n\n<pre><code>public static IQueryable<T> ApplyXYZFilter(this IQueryable<T> query, string filter)\n{\n return query.Where(XYZ => XYZ == filter);\n} \n</code></pre>\n"
},
{
"answer_id": 248284,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 2,
"selected": false,
"text": "<p>I have seen overloading overused when you have only subtle differences in the arguments to the method. For example: </p>\n\n<pre><code>public List<Product> GetProduct(int productId) { // return a List }\npublic List<Product> GetProduct(int productId, int ownerId ) { // return a List }\npublic List<Product> GetProduct(int productId, int vendorId, boolean printInvoice) { // return a List }\n</code></pre>\n\n<p>In my small example, it quickly becomes unclear if the second <code>int</code> argument should be the owner or customer id.</p>\n"
},
{
"answer_id": 248285,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>One thing you may consider is that you can't expose overloaded methods as operation contracts in a WCF Web Service. So if you think you may ever need to do this, it would be an argument for using different method names.</p>\n\n<p>Another argument for different method names is that they may be more easily discoverable using intellisense.</p>\n\n<p>But there are pros and cons for either choice - all design is trade-off.</p>\n"
},
{
"answer_id": 248473,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 3,
"selected": false,
"text": "<p>The point of overloading to to ease the learning curve of someone using your code... and to allow you to use naming schemes that inform the user as to what the method does.</p>\n\n<p>If you have ten different methods that all return a collection of employees, Then generating ten different names, (Especially if they start with different letters!) causes them to appear as multiple entries in your users' intellisense drop down, extending the length of the drop down, and hiding the distinction between the set of ten methods that all return an employee collection, and whatever other methods are in your class...</p>\n\n<p>Think about what is already enforced by the .Net framework for, say constructors, and indexers... They are all forced to have the same name, and you can only create multiples by overloading them... </p>\n\n<p>If you overload them, they will all appear as one, with their disparate signatures and comments off to tthe side.</p>\n\n<p>You should not overload two methods if they perform different or unrelated functions...</p>\n\n<p>As to the confusion that can exist when you want to overload two methods with the same signature by type \nas in</p>\n\n<pre><code>public List<Employee> GetEmployees(int supervisorId);\npublic List<Employee> GetEmployees(int departmentId); // Not Allowed !!\n</code></pre>\n\n<p>Well you can create separate types as wrappers for the offending core type to distinguish the signatures..</p>\n\n<pre><code> public struct EmployeeId \n { \n private int empId;\n public int EmployeeId { get { return empId; } set { empId = value; } }\n public EmployeeId(int employeId) { empId = employeeId; }\n }\n\n public struct DepartmentId \n {\n // analogous content\n }\n\n // Now it's fine, as the parameters are defined as distinct types...\n public List<Employee> GetEmployees(EmployeeId supervisorId);\n public List<Employee> GetEmployees(DepartmentId departmentId);\n</code></pre>\n"
},
{
"answer_id": 248559,
"author": "a-sak",
"author_id": 325613,
"author_profile": "https://Stackoverflow.com/users/325613",
"pm_score": 1,
"selected": false,
"text": "<p>You can use Overloading as much as you want. \nFrom the best practices point of view as well, it is recommended that you use Overloading if you are trying to perform the same \"operation\" (holistically) on the data. E.g. getProduct()</p>\n\n<p>Also, if you see Java API, Overloading is everywhere. You wouldn't find a bigger endorsement than that.</p>\n"
},
{
"answer_id": 248590,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 2,
"selected": false,
"text": "<p>A brief glance at the framework should convince you that numerous overloads is an accepted state of affairs. In the face of myriad overloads, the <em>design</em> of overloads for usability is directly addressed by section 5.1.1 of the Microsoft Framework Design Guidelines (Kwalina and Abrams, 2006). Here is a brief prècis of that section:</p>\n\n<ul>\n<li><p><strong>DO</strong> try to use descriptive parameter names to indicate the default used by shorter overloads.</p></li>\n<li><p><strong>AVOID</strong> arbitrarily varying parameter names in overloads.</p></li>\n<li><p><strong>AVOID</strong> being inconsistent in the ordering of parameters in overloaded members.</p></li>\n<li><p><strong>DO</strong> make only the longest overload virtual (if extensibility is required). Shorter overloads should simply call through to a longer overload.</p></li>\n<li><p><strong>DO NOT</strong> use <code>ref</code> or <code>out</code> parameters to overload members.</p></li>\n<li><p><strong>DO</strong> allow <code>null</code> to be passed for optional arguments.</p></li>\n<li><p><strong>DO</strong> use member overloading rather than defining members with default arguments.</p></li>\n</ul>\n"
},
{
"answer_id": 248677,
"author": "dongilmore",
"author_id": 31962,
"author_profile": "https://Stackoverflow.com/users/31962",
"pm_score": 1,
"selected": false,
"text": "<p>Overloading is desirable polymorphic behavior. It helps the human programmer remember the method name. If explicit is redundant with the type parameter, then it is bad. If the type parameter does not imply what the method is doing, then explicit starts to make sense.</p>\n\n<p>In your example, getProductByName is the only case where explicit might make sense, since you might want to get product by some other string. This problem was caused by the ambiguity of primitive types; getProduct(Name n) might be a better overload solution in some cases.</p>\n"
},
{
"answer_id": 249624,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, overloading can easily be overused.</p>\n\n<p>I've found that the key to working out whether an overload is warranted or not is to consider the audience - not the compiler, but the maintenance programmer who will be coming along in weeks/months/years and has to understand what the code is trying to achieve.</p>\n\n<p>A simple method name like GetProducts() is clear and understandable, but it does leave a lot unsaid. </p>\n\n<p>In many cases, if the parameter passed to GetProducts() are well named, the maintenance guy will be able to work out what the overload does - but that's relying on good naming discipline at the point of use, which you can't enforce. What you can enforce is the name of the method they're calling.</p>\n\n<p>The guideline that I follow is to only overload methods if they are interchangable - if they do the same thing. That way, I don't mind which version the consumer of my class invokes, as they're equivalent.</p>\n\n<p>To illustrate, I'd happily use overloads for a DeleteFile() method:</p>\n\n<pre><code>void DeleteFile(string filePath);\nvoid DeleteFile(FileInfo file);\nvoid DeleteFile(DirectoryInfo directory, string fileName);\n</code></pre>\n\n<p>However, for your examples, I'd use separate names:</p>\n\n<pre><code>public IList<Product> GetProductById(int productId) {...}\npublic IList<Product> GetProductByCategory(Category category) {...}\npublic IList<Product> GetProductByName(string Name ) {...}\n</code></pre>\n\n<p>Having the full names makes the code more explicit for the maintenance guy (who might well be me). It avoids issues with having signature collisions:</p>\n\n<pre><code>// No collisions, even though both methods take int parameters\npublic IList<Employee> GetEmployeesBySupervisor(int supervisorId);\npublic IList<Employee> GetEmployeesByDepartment(int departmentId);\n</code></pre>\n\n<p>There is also the opportunity to introduce overloading for each purpose:</p>\n\n<pre><code>// Examples for GetEmployees\n\npublic IList<Employee> GetEmployeesBySupervisor(int supervisorId);\npublic IList<Employee> GetEmployeesBySupervisor(Supervisor supervisor);\npublic IList<Employee> GetEmployeesBySupervisor(Person supervisor);\n\npublic IList<Employee> GetEmployeesByDepartment(int departmentId);\npublic IList<Employee> GetEmployeesByDepartment(Department department);\n\n// Examples for GetProduct\n\npublic IList<Product> GetProductById(int productId) {...}\npublic IList<Product> GetProductById(params int[] productId) {...}\n\npublic IList<Product> GetProductByCategory(Category category) {...}\npublic IList<Product> GetProductByCategory(IEnumerable<Category> category) {...}\npublic IList<Product> GetProductByCategory(params Category[] category) {...}\n</code></pre>\n\n<p>Code is read a lot more than it is written - even if you never come back to the code after the initial check in to source control, you're still going to be reading that line of code a couple of dozen times while you write the code that follows.</p>\n\n<p>Lastly, unless you're writing throwaway code, you need to allow for other people calling your code from other languages. It seems that most business systems end up staying in production well past their use by date. It may be that the code that consumes your class in 2016 ends up being written in VB.NET, C# 6.0, F# or something completely new that's not been invented yet. It may be that the language doesn't support overloads.</p>\n"
},
{
"answer_id": 250184,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 0,
"selected": false,
"text": "<p>yes you can overuse it. In your example it would seem like the first and third would probably return a single item, where the second would return several. If that is correct, then I would call the first and third GetProduct and the second GetProducts or GetProductList</p>\n\n<p>if this is not the case and all three return several (as in if you pass it productID 5, it returns any items with 5 in the productid, or returns any items with the string parameter in its name) then I would call all three GetProducts or GetProductList and override all of them.</p>\n\n<p>In any event, the name should reflect what the function does, so calling it GetProduct (singular) when it returns a list of Products doesn't make a good function name. IMNSHO</p>\n"
},
{
"answer_id": 442205,
"author": "Daniel Daranas",
"author_id": 96780,
"author_profile": "https://Stackoverflow.com/users/96780",
"pm_score": 0,
"selected": false,
"text": "<p>I'm a total fan of the \"explicit\" way: giving each function a different name. I've even refactored some code which had lots of <code>Add(...)</code> functions in the past, to <code>AddRecord(const Record&)</code>, <code>AddCell(const Cell&)</code>, etc.</p>\n\n<p>I think this helps to avoid some confusions, inadvertent casts (in C++, at least) and compiler warnings, and it improves clarity.</p>\n\n<p>Maybe in some cases you need the other strategy. I haven't encountered one yet.</p>\n"
},
{
"answer_id": 10635156,
"author": "AgentFire",
"author_id": 558018,
"author_profile": "https://Stackoverflow.com/users/558018",
"pm_score": 0,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code>public IList<Product> GetProducts() { /* Return all. */}\n\npublic IList<Product> GetProductBy(int productId) {...}\npublic IList<Product> GetProductBy(Category category) {...}\npublic IList<Product> GetProductBy(string Name ) {...}\n</code></pre>\n\n<p>And so on?</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?
For example. If I have some Products and I'm pulling from a database
explicit way:
```
public List<Product> GetProduct(int productId) { // return a List }
public List<Product> GetProductByCategory(Category category) { // return a List }
public List<Product> GetProductByName(string Name ) { // return a List }
```
overloaded way:
```
public List<Product> GetProducts() { // return a List of all products }
public List<Product> GetProducts(Category category) { // return a List by Category }
public List<Product> GetProducts(string searchString ) { // return a List by search string }
```
I realize you may get into a problem with **similar signatures**, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to **overload a method** to reduce the number of methods you have and for clarity, **or** should **each method** that filters the data a different way **have a different method name**?
|
Yes, overloading can easily be overused.
I've found that the key to working out whether an overload is warranted or not is to consider the audience - not the compiler, but the maintenance programmer who will be coming along in weeks/months/years and has to understand what the code is trying to achieve.
A simple method name like GetProducts() is clear and understandable, but it does leave a lot unsaid.
In many cases, if the parameter passed to GetProducts() are well named, the maintenance guy will be able to work out what the overload does - but that's relying on good naming discipline at the point of use, which you can't enforce. What you can enforce is the name of the method they're calling.
The guideline that I follow is to only overload methods if they are interchangable - if they do the same thing. That way, I don't mind which version the consumer of my class invokes, as they're equivalent.
To illustrate, I'd happily use overloads for a DeleteFile() method:
```
void DeleteFile(string filePath);
void DeleteFile(FileInfo file);
void DeleteFile(DirectoryInfo directory, string fileName);
```
However, for your examples, I'd use separate names:
```
public IList<Product> GetProductById(int productId) {...}
public IList<Product> GetProductByCategory(Category category) {...}
public IList<Product> GetProductByName(string Name ) {...}
```
Having the full names makes the code more explicit for the maintenance guy (who might well be me). It avoids issues with having signature collisions:
```
// No collisions, even though both methods take int parameters
public IList<Employee> GetEmployeesBySupervisor(int supervisorId);
public IList<Employee> GetEmployeesByDepartment(int departmentId);
```
There is also the opportunity to introduce overloading for each purpose:
```
// Examples for GetEmployees
public IList<Employee> GetEmployeesBySupervisor(int supervisorId);
public IList<Employee> GetEmployeesBySupervisor(Supervisor supervisor);
public IList<Employee> GetEmployeesBySupervisor(Person supervisor);
public IList<Employee> GetEmployeesByDepartment(int departmentId);
public IList<Employee> GetEmployeesByDepartment(Department department);
// Examples for GetProduct
public IList<Product> GetProductById(int productId) {...}
public IList<Product> GetProductById(params int[] productId) {...}
public IList<Product> GetProductByCategory(Category category) {...}
public IList<Product> GetProductByCategory(IEnumerable<Category> category) {...}
public IList<Product> GetProductByCategory(params Category[] category) {...}
```
Code is read a lot more than it is written - even if you never come back to the code after the initial check in to source control, you're still going to be reading that line of code a couple of dozen times while you write the code that follows.
Lastly, unless you're writing throwaway code, you need to allow for other people calling your code from other languages. It seems that most business systems end up staying in production well past their use by date. It may be that the code that consumes your class in 2016 ends up being written in VB.NET, C# 6.0, F# or something completely new that's not been invented yet. It may be that the language doesn't support overloads.
|
248,224 |
<p>I downloaded the free CodeRush Xpress version to try it. Is there a way to change the colors it uses for it's highlighting and line drawing? ie the matching braces. I have a dark color scheme and my monitor I have VS on must suck because I can't see the lines. Yet on the LCD I can. Is there a way to change the colors?</p>
|
[
{
"answer_id": 862842,
"author": "Christian",
"author_id": 54193,
"author_profile": "https://Stackoverflow.com/users/54193",
"pm_score": 4,
"selected": true,
"text": "<p>I use <em>CodeRush Xpress 9.2</em>. It is possible to configure some colors used for highlighting in the Options menu of <em>CodeRush Xpress</em>. You can find the menu in <em>Visual Studio</em> under <em>DevExpress</em> -> <em>Options</em>. Go to the <em>Painting</em> sub-item of the <em>Editor</em> item to control some of the colors used (among them <em>Navigation Fields</em>, <em>Navigation Links</em> and <em>Text fields</em>).</p>\n\n<p>If the <em>DevExpress</em> menu doesn't appear in your <em>Visual Studio</em> installation, just press <code>Alt+Ctrl+Shift+O</code> to directly go to DevExpress Options. Or, if you permanently want the <em>DevExpress</em> menu entry in <em>Visual Studio</em>, set the following registry key and restart it:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Developer Express\\CodeRush for VS\\9.2]\n \"HideMenu\"=dword:00000000\n</code></pre>\n\n<p>This works at least with <em>Visual Studio 2005</em> and <em>2008</em>.</p>\n"
},
{
"answer_id": 1579660,
"author": "jrsconfitto",
"author_id": 81411,
"author_profile": "https://Stackoverflow.com/users/81411",
"pm_score": 2,
"selected": false,
"text": "<p>Just found this online... You can open their control menu with this key combination: ctrl+alt+shift+o</p>\n\n<p>i'm using VS 2008 for the record & CodeRush xpress 9.2. i didnt see a menu in Visual Studio anywhere and i didnt find that registry setting either.</p>\n"
},
{
"answer_id": 15099143,
"author": "Samir Banjanovic",
"author_id": 1332387,
"author_profile": "https://Stackoverflow.com/users/1332387",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a 64bit machine the path will be different: </p>\n\n<p><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Developer Express\\CodeRush for VS</code></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7024/"
] |
I downloaded the free CodeRush Xpress version to try it. Is there a way to change the colors it uses for it's highlighting and line drawing? ie the matching braces. I have a dark color scheme and my monitor I have VS on must suck because I can't see the lines. Yet on the LCD I can. Is there a way to change the colors?
|
I use *CodeRush Xpress 9.2*. It is possible to configure some colors used for highlighting in the Options menu of *CodeRush Xpress*. You can find the menu in *Visual Studio* under *DevExpress* -> *Options*. Go to the *Painting* sub-item of the *Editor* item to control some of the colors used (among them *Navigation Fields*, *Navigation Links* and *Text fields*).
If the *DevExpress* menu doesn't appear in your *Visual Studio* installation, just press `Alt+Ctrl+Shift+O` to directly go to DevExpress Options. Or, if you permanently want the *DevExpress* menu entry in *Visual Studio*, set the following registry key and restart it:
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express\CodeRush for VS\9.2]
"HideMenu"=dword:00000000
```
This works at least with *Visual Studio 2005* and *2008*.
|
248,227 |
<p>I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?</p>
<p>I'd be fine with a tool that does this generally for text documents.</p>
|
[
{
"answer_id": 248457,
"author": "lImbus",
"author_id": 32490,
"author_profile": "https://Stackoverflow.com/users/32490",
"pm_score": 0,
"selected": false,
"text": "<p>never heard about anything like that, but it might be an intresting task to write such a program based on a <a href=\"http://en.wikipedia.org/wiki/Dictionary_coder\" rel=\"nofollow noreferrer\">dictionary coder</a> as used in archivers.</p>\n"
},
{
"answer_id": 473400,
"author": "Stephen Friederichs",
"author_id": 39492,
"author_profile": "https://Stackoverflow.com/users/39492",
"pm_score": 0,
"selected": false,
"text": "<p>Not easily. My first thought is XSLT but it's hard to implement. You'd have to go through each node and then do an XPATH select on every node with the same data. That would find them, but you'd end up processing all of the nodes with the same data later as well (ie, no way to keep track of what node data you've already processed and ignore it). You could do it with a real programming language but that's outside of my experience.</p>\n"
},
{
"answer_id": 473412,
"author": "cjk",
"author_id": 52201,
"author_profile": "https://Stackoverflow.com/users/52201",
"pm_score": 0,
"selected": false,
"text": "<p>You could write a simple C# app that uses Linq to read all the nodes twice as separate entities, then finds all values that are equal.</p>\n"
},
{
"answer_id": 473563,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a first attempt, written in Python and using only standard libraries. You can improve it in many ways (trim leading and ending whitespaces, computing a hash of the text to decrease memory requirments, better displaying of the elements, with their line number, etc):</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import xml.etree.ElementTree as ElementTree\nimport sys\n\ndef print_elem(element):\n return \"<%s>\" % element.tag\n\nif len(sys.argv) != 2:\n print >> sys.stderr, \"Usage: %s filename\" % sys.argv[0]\n sys.exit(1)\nfilename = sys.argv[1] \ntree = ElementTree.parse(filename)\nroot = tree.getroot()\nchunks = {}\niter = root.findall('.//*')\nfor element in iter:\n if element.text in chunks:\n chunks[element.text].append(element)\n else:\n chunks[element.text] = [element,]\nfor text in chunks:\n if len(chunks[text]) > 1:\n print \"\\\"%s\\\" is a duplicate: found in %s\" % \\\n (text, map(print_elem, chunks[text]))\n</code></pre>\n\n<p>If you give it this XML file:</p>\n\n\n\n<pre><code><foo>\n<bar>Hop</bar><quiz>Gaw</quiz>\n<sub>\n<und>Hop</und>\n</sub>\n</code></pre>\n\n<p>it will output:</p>\n\n<pre><code>\"Hop\" is a duplicate: found in ['<bar>', '<und>']\n</code></pre>\n"
},
{
"answer_id": 38512978,
"author": "tephyr",
"author_id": 562978,
"author_profile": "https://Stackoverflow.com/users/562978",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/q/1800634/562978\">A very similar question</a> (<em>asked a year after this one</em>) has some answers with very good tools for diffing chunks within the same file, including <a href=\"https://stackoverflow.com/a/3006324/562978\">Atomiq</a>.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245644/"
] |
I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?
I'd be fine with a tool that does this generally for text documents.
|
Here is a first attempt, written in Python and using only standard libraries. You can improve it in many ways (trim leading and ending whitespaces, computing a hash of the text to decrease memory requirments, better displaying of the elements, with their line number, etc):
```python
import xml.etree.ElementTree as ElementTree
import sys
def print_elem(element):
return "<%s>" % element.tag
if len(sys.argv) != 2:
print >> sys.stderr, "Usage: %s filename" % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
tree = ElementTree.parse(filename)
root = tree.getroot()
chunks = {}
iter = root.findall('.//*')
for element in iter:
if element.text in chunks:
chunks[element.text].append(element)
else:
chunks[element.text] = [element,]
for text in chunks:
if len(chunks[text]) > 1:
print "\"%s\" is a duplicate: found in %s" % \
(text, map(print_elem, chunks[text]))
```
If you give it this XML file:
```
<foo>
<bar>Hop</bar><quiz>Gaw</quiz>
<sub>
<und>Hop</und>
</sub>
```
it will output:
```
"Hop" is a duplicate: found in ['<bar>', '<und>']
```
|
248,243 |
<p>A library using off_t as a parameter for one function (seek). Library and application are compiled differently, one with large file support switched off, the other with large file support. This situation results in strange runtime errors, because both interpret off_t differently. How can the library check at runtime the size of off_t for the app? Or is there another solution, so that at least the user gets a meaningful error?</p>
<p>EDIT: The library (programmed in c and with autoconf) already exists and some third-party application use it. The library can be compiled with large file support (by default via AC_SYS_LARGEFILE). It is multiplatform, not only linux. How can be detected/prevented that installed applications will be broken by the change in LFS?</p>
|
[
{
"answer_id": 248309,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "<p>You could add an API to the library to return the sizeof(off_t) and then check it from the client. Alternatively the library could require every app to provide the API in order to successfully link:</p>\n\n<p>library.c:</p>\n\n<pre><code>size_t lib_get_off_t_size (void)\n{\n return (sizeof(off_t));\n}\n</code></pre>\n\n<p>client.c (init_function):</p>\n\n<pre><code>if (lib_get_off_t_size() != sizeof(off_t) {\n printf(\"Oh no!\\n\");\n exit();\n}\n</code></pre>\n\n<p>If the library has an init function then you could put the check there, but then the client would have to supply the API to get the size of its off_t, which generally isn't how libraries work.</p>\n"
},
{
"answer_id": 248417,
"author": "lImbus",
"author_id": 32490,
"author_profile": "https://Stackoverflow.com/users/32490",
"pm_score": 0,
"selected": false,
"text": "<p>As said before, the library will not be able to know how the application (being client to the library) is compiled, but the other way round has to work. Besides, I think you are talking about dynamic linking, since static linking certainly would not have different switches at same build time.</p>\n\n<p>Similar to the already given answer by \"Andrew Johnson\", the library could provide a method for finding out whether it was compiled with large file support or not. Knowing that such build-time switches are mostly done with defines in C, this could be looking like this:</p>\n\n<pre><code>//in library:\nBOOL isLargeFileSupport (void)\n{\n#ifdef LARGE_FILE_SUPPORT\n return TRUE;\n#else\n return FALSE;\n#endif\n}\n</code></pre>\n\n<p>The application then knows how to handle file sizes reported by that lib, or can refuse to work when incompatible:</p>\n\n<pre><code>//in application\nBOOL bLibLFS = lib_isLargeFileSupport();\nBOOL bAppLFS = FALSE;\n#ifdef LARGE_FILE_SUPPORT\n bAppLFS = TRUE;\n#endif\n\nif (bLibLFS != bAppLFS)\n //incompatible versions, bail out\n exit(0);\n</code></pre>\n"
},
{
"answer_id": 248539,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "<p>On Linux, when the library is compiled with large file support switched on, <code>off_t</code> is defined to be the same as <code>off64_t</code>. So, if the library is the one compiled with large file support, you could change its interface to always use <code>off64_t</code> instead of <code>off_t</code> (this might need <code>_LARGEFILE64_SOURCE</code>) and completely avoid the problem.</p>\n\n<p>You can also check whether the application is being compiled with large file support or not (by seeing if <code>_FILE_OFFSET_BITS</code> is not defined or <code>32</code>) and refuse compiling (with <code>#error</code>) if it's being compiled the wrong way; see <code>/usr/include/features.h</code> and <a href=\"http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html#Feature-Test-Macros\" rel=\"nofollow noreferrer\">Feature Test Macros</a>.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
A library using off\_t as a parameter for one function (seek). Library and application are compiled differently, one with large file support switched off, the other with large file support. This situation results in strange runtime errors, because both interpret off\_t differently. How can the library check at runtime the size of off\_t for the app? Or is there another solution, so that at least the user gets a meaningful error?
EDIT: The library (programmed in c and with autoconf) already exists and some third-party application use it. The library can be compiled with large file support (by default via AC\_SYS\_LARGEFILE). It is multiplatform, not only linux. How can be detected/prevented that installed applications will be broken by the change in LFS?
|
You could add an API to the library to return the sizeof(off\_t) and then check it from the client. Alternatively the library could require every app to provide the API in order to successfully link:
library.c:
```
size_t lib_get_off_t_size (void)
{
return (sizeof(off_t));
}
```
client.c (init\_function):
```
if (lib_get_off_t_size() != sizeof(off_t) {
printf("Oh no!\n");
exit();
}
```
If the library has an init function then you could put the check there, but then the client would have to supply the API to get the size of its off\_t, which generally isn't how libraries work.
|
248,246 |
<p>Do any queries exist that require RIGHT JOIN, or can they always be re-written with LEFT JOIN?</p>
<p>And more specifically, how do you re-write this one without the right join (and I guess implicitly without any subqueries or other fanciness):</p>
<p><pre><code>
SELECT *
FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
</pre></code></p>
|
[
{
"answer_id": 248252,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>You can always swap the table order to turn a RIGHT JOIN into a LEFT JOIN. Sometimes it's just more efficient to do it one way or the other.</p>\n"
},
{
"answer_id": 248253,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>You can always re-write them to get the same result set. However, sometimes the execution plan may be different in significant ways (performance) and sometimes a right join let's you express the query in a way that makes more sense.</p>\n\n<p>Let me illustrate the performance difference. Programmers tend to think in terms of an sql statement happening all at once. However, it's useful to keep a mental model that complicated queries happen in a series of steps where tables are typically joined in the order listed. So you may have a query like this:</p>\n\n<pre><code>SELECT * /* example: don't care what's returned */\nFROM LargeTable L\nLEFT JOIN MediumTable M ON M.L_ID=L.ID\nLEFT JOIN SmallTable S ON S.M_ID=M.ID\nWHERE ...\n</code></pre>\n\n<p>The server will normally start by applying anything it can from the WHERE clause to the first table listed (LargeTable, in this case), to reduce what it needs to load into memory. Then it will join the next table (MediumTable), and then the one after that (SmallTable), and so on. </p>\n\n<p>What we want to do is use a strategy that accounts for the expected impact of each joined table on the results. In general you want to keep the result set as small as possible for as long as possible. Apply that principle to the example query above, and we see it's obviously much slower than it needs to be. It starts with the larger sets (tables) and works down. We want to begin with the smaller sets and work up. That means using SmallTable first, and the way to do that is via a RIGHT JOIN.</p>\n\n<p>Another key here is that the server usually can't know which rows from SmallTable will be needed until the join is completed. Therefore it only matters if SmallTable is so much smaller than LargeTable that loading the entire SmallTable into memory is cheaper than whatever you would start with from LargeTable (which, being a large table, is probably well-indexed and probably filters on a field or three in the where clause).</p>\n\n<p>It's important to also point out that in the vast majority of cases the optimizer will look at this and handle things in the most efficient way possible, and most of the time the optimizer is going to do a better job at this than you could. </p>\n\n<p>But the optimizer isn't perfect. Sometimes you need to help it along: especially if one or more of your \"tables\" is a view (perhaps into a linked server!) or a nested select statement, for example. A nested sub-query is also a good case of where you might want to use a right join for expressive reasons: it lets you move the nested portion of the query around so you can group things better.</p>\n"
},
{
"answer_id": 248269,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 3,
"selected": false,
"text": "<p>It's a bit like asking if using greater-than is ever required. Use the one that better fits the task at hand.</p>\n"
},
{
"answer_id": 248275,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 3,
"selected": false,
"text": "<p>Yes! all the time! (Have to admit, mostly used when you're strict as to which table you want to call first) </p>\n\n<p>On this subject: <a href=\"https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">here's a nice visual guide on joins</a>.</p>\n"
},
{
"answer_id": 248403,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 5,
"selected": true,
"text": "<p>You can always use only left Joins...</p>\n\n<pre><code>SELECT * FROM t1\n LEFT JOIN t2 ON t1.k2 = t2.k2\n RIGHT JOIN t3 ON t3.k3 = t2.k3\n</code></pre>\n\n<p>is equivilent to:</p>\n\n<pre><code>Select * From t3 \n Left Join (t1 Left Join t2 \n On t2.k2 = t1.k2)\n On T2.k3 = T3.K3\n</code></pre>\n\n<p>In general I always try to use only Left Joins, as the table on the left in a Left Join is the one whose rows are ALL included in the output, and I like to think of it, (The Left side) as the \"base\" set I am performing the cartesion product (join) against ... So I like to have it first in the SQL... </p>\n"
},
{
"answer_id": 248413,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": -1,
"selected": false,
"text": "<p>I use <code>LEFT JOIN</code>s about 99.999% of the time, but some of my dynamic code generation uses <code>RIGHT JOIN</code>s which mean that the stuff outside the join doesn't need to be reversed.</p>\n\n<p>I'd also like to add that the specific example you give I believe produces a cross join, and that is probably not your intention or even a good design.</p>\n\n<p>i.e. I think it's effectively the same as:</p>\n\n<pre><code>SELECT *\nFROM t1\nCROSS JOIN t3\nLEFT JOIN t2\n ON t1.k2 = t2.k2\n AND t3.k3 = t2.k3\n</code></pre>\n\n<p>And also, because it's a cross join, there's not a lot the optimizer is going to be able to do.</p>\n"
},
{
"answer_id": 248419,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": -1,
"selected": false,
"text": "<p>There are many elements of many programming languages which are not strictly required to achieve the correct results but which permit one a) to express intent more clearly b) to boost performance. Examples include numbers, characters, loops, switches, classes, joins, types, filters, and thousands more.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12861/"
] |
Do any queries exist that require RIGHT JOIN, or can they always be re-written with LEFT JOIN?
And more specifically, how do you re-write this one without the right join (and I guess implicitly without any subqueries or other fanciness):
```
SELECT *
FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
```
|
You can always use only left Joins...
```
SELECT * FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
```
is equivilent to:
```
Select * From t3
Left Join (t1 Left Join t2
On t2.k2 = t1.k2)
On T2.k3 = T3.K3
```
In general I always try to use only Left Joins, as the table on the left in a Left Join is the one whose rows are ALL included in the output, and I like to think of it, (The Left side) as the "base" set I am performing the cartesion product (join) against ... So I like to have it first in the SQL...
|
248,254 |
<p>I want to be able to see how many lines were added to a file since the last quering without reading the whole file again.</p>
<p>Something like :</p>
<pre><code>ptail my_file | fgrep "[ERROR]" | wc -l
</code></pre>
<p>A solution in simple Perl would be prefered, since I don't have an easy access to a compiler.</p>
|
[
{
"answer_id": 248252,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>You can always swap the table order to turn a RIGHT JOIN into a LEFT JOIN. Sometimes it's just more efficient to do it one way or the other.</p>\n"
},
{
"answer_id": 248253,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>You can always re-write them to get the same result set. However, sometimes the execution plan may be different in significant ways (performance) and sometimes a right join let's you express the query in a way that makes more sense.</p>\n\n<p>Let me illustrate the performance difference. Programmers tend to think in terms of an sql statement happening all at once. However, it's useful to keep a mental model that complicated queries happen in a series of steps where tables are typically joined in the order listed. So you may have a query like this:</p>\n\n<pre><code>SELECT * /* example: don't care what's returned */\nFROM LargeTable L\nLEFT JOIN MediumTable M ON M.L_ID=L.ID\nLEFT JOIN SmallTable S ON S.M_ID=M.ID\nWHERE ...\n</code></pre>\n\n<p>The server will normally start by applying anything it can from the WHERE clause to the first table listed (LargeTable, in this case), to reduce what it needs to load into memory. Then it will join the next table (MediumTable), and then the one after that (SmallTable), and so on. </p>\n\n<p>What we want to do is use a strategy that accounts for the expected impact of each joined table on the results. In general you want to keep the result set as small as possible for as long as possible. Apply that principle to the example query above, and we see it's obviously much slower than it needs to be. It starts with the larger sets (tables) and works down. We want to begin with the smaller sets and work up. That means using SmallTable first, and the way to do that is via a RIGHT JOIN.</p>\n\n<p>Another key here is that the server usually can't know which rows from SmallTable will be needed until the join is completed. Therefore it only matters if SmallTable is so much smaller than LargeTable that loading the entire SmallTable into memory is cheaper than whatever you would start with from LargeTable (which, being a large table, is probably well-indexed and probably filters on a field or three in the where clause).</p>\n\n<p>It's important to also point out that in the vast majority of cases the optimizer will look at this and handle things in the most efficient way possible, and most of the time the optimizer is going to do a better job at this than you could. </p>\n\n<p>But the optimizer isn't perfect. Sometimes you need to help it along: especially if one or more of your \"tables\" is a view (perhaps into a linked server!) or a nested select statement, for example. A nested sub-query is also a good case of where you might want to use a right join for expressive reasons: it lets you move the nested portion of the query around so you can group things better.</p>\n"
},
{
"answer_id": 248269,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 3,
"selected": false,
"text": "<p>It's a bit like asking if using greater-than is ever required. Use the one that better fits the task at hand.</p>\n"
},
{
"answer_id": 248275,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 3,
"selected": false,
"text": "<p>Yes! all the time! (Have to admit, mostly used when you're strict as to which table you want to call first) </p>\n\n<p>On this subject: <a href=\"https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">here's a nice visual guide on joins</a>.</p>\n"
},
{
"answer_id": 248403,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 5,
"selected": true,
"text": "<p>You can always use only left Joins...</p>\n\n<pre><code>SELECT * FROM t1\n LEFT JOIN t2 ON t1.k2 = t2.k2\n RIGHT JOIN t3 ON t3.k3 = t2.k3\n</code></pre>\n\n<p>is equivilent to:</p>\n\n<pre><code>Select * From t3 \n Left Join (t1 Left Join t2 \n On t2.k2 = t1.k2)\n On T2.k3 = T3.K3\n</code></pre>\n\n<p>In general I always try to use only Left Joins, as the table on the left in a Left Join is the one whose rows are ALL included in the output, and I like to think of it, (The Left side) as the \"base\" set I am performing the cartesion product (join) against ... So I like to have it first in the SQL... </p>\n"
},
{
"answer_id": 248413,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": -1,
"selected": false,
"text": "<p>I use <code>LEFT JOIN</code>s about 99.999% of the time, but some of my dynamic code generation uses <code>RIGHT JOIN</code>s which mean that the stuff outside the join doesn't need to be reversed.</p>\n\n<p>I'd also like to add that the specific example you give I believe produces a cross join, and that is probably not your intention or even a good design.</p>\n\n<p>i.e. I think it's effectively the same as:</p>\n\n<pre><code>SELECT *\nFROM t1\nCROSS JOIN t3\nLEFT JOIN t2\n ON t1.k2 = t2.k2\n AND t3.k3 = t2.k3\n</code></pre>\n\n<p>And also, because it's a cross join, there's not a lot the optimizer is going to be able to do.</p>\n"
},
{
"answer_id": 248419,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": -1,
"selected": false,
"text": "<p>There are many elements of many programming languages which are not strictly required to achieve the correct results but which permit one a) to express intent more clearly b) to boost performance. Examples include numbers, characters, loops, switches, classes, joins, types, filters, and thousands more.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24760/"
] |
I want to be able to see how many lines were added to a file since the last quering without reading the whole file again.
Something like :
```
ptail my_file | fgrep "[ERROR]" | wc -l
```
A solution in simple Perl would be prefered, since I don't have an easy access to a compiler.
|
You can always use only left Joins...
```
SELECT * FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
```
is equivilent to:
```
Select * From t3
Left Join (t1 Left Join t2
On t2.k2 = t1.k2)
On T2.k3 = T3.K3
```
In general I always try to use only Left Joins, as the table on the left in a Left Join is the one whose rows are ALL included in the output, and I like to think of it, (The Left side) as the "base" set I am performing the cartesion product (join) against ... So I like to have it first in the SQL...
|
248,273 |
<p>Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.</p>
<p>I am currently working in C#.</p>
|
[
{
"answer_id": 248288,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>Any particular language and therefore date format?</p>\n\n<p>If dates are represented as a count of days, then the difference between two values plus one (day), and divide by 7, is most of the answer. If both end dates are the day in question, add one.</p>\n\n<p><em>Edited:</em> corrected 'modulo 7' to 'divide by 7' - thanks. And that is integer division.</p>\n"
},
{
"answer_id": 248308,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": false,
"text": "<p>Add the smallest possible number to make the first day a Monday. Subtract the smallest possible number to make the last day a Monday. Calculate the difference in days and divide by 7.</p>\n"
},
{
"answer_id": 248356,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "<p>Since you're using C#, if you're using C#3.0, you can use LINQ.</p>\n\n<p>Assuming you have an Array/List/IQueryable etc that contains your dates as DateTime types:</p>\n\n<pre><code>DateTime[] dates = { new DateTime(2008,10,6), new DateTime(2008,10,7)}; //etc....\n\nvar mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday); // = {10/6/2008}\n</code></pre>\n\n<p>Added:</p>\n\n<p>Not sure if you meant grouping them and counting them, but here's how to do that in LINQ as well:</p>\n\n<pre><code>var datesgrouped = from d in dates\n group d by d.DayOfWeek into grouped\n select new { WeekDay = grouped.Key, Days = grouped };\n\nforeach (var g in datesgrouped)\n{\n Console.Write (String.Format(\"{0} : {1}\", g.WeekDay,g.Days.Count());\n}\n</code></pre>\n"
},
{
"answer_id": 248359,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 3,
"selected": false,
"text": "<p>Here's some pseudocode:</p>\n\n<pre><code>DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayOfWeek(Start) <= DayImLookingFor\n+ 1 if DayOfWeek(End) >= DayImLookingFor\n- 1\n</code></pre>\n\n<p>Where <code>DifferenceInDays</code> returns <code>End - Start</code> in days, and <code>DayOfWeek</code> returns the day of the week as an integer. It doesn't really matter what mapping <code>DayOfWeek</code> uses, as long as it is increasing and matches up with <code>DayImLookingFor</code>.</p>\n\n<p>Note that this algorithm assumes the date range is inclusive. If <code>End</code> should not be part of the range, you'll have to adjust the algorithm slightly.</p>\n\n<p>Translating to C# is left as an exercise for the reader.</p>\n"
},
{
"answer_id": 248369,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 4,
"selected": false,
"text": "<p>It's fun to look at different algorithms for calculating day of week, and @Gabe Hollombe's pointing to WP on the subject was a great idea (and I remember implementing <a href=\"http://en.wikipedia.org/wiki/Zeller%27s_congruence\" rel=\"nofollow noreferrer\">Zeller's Congruence</a> in COBOL about twenty years ago), but it was rather along the line of handing someone a blueprint of a clock when all they asked what time it was.</p>\n<p>In C#:</p>\n<pre><code> private int CountMondays(DateTime startDate, DateTime endDate)\n {\n int mondayCount = 0;\n\n for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))\n {\n if (dt.DayOfWeek == DayOfWeek.Monday)\n {\n mondayCount++;\n }\n }\n\n return mondayCount;\n }\n</code></pre>\n<p>This of course does not evaluate the end date for "Mondayness", so if this was desired, make the for loop evaluate</p>\n<pre><code>dt < endDate.AddDays(1.0)\n</code></pre>\n"
},
{
"answer_id": 248370,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 1,
"selected": false,
"text": "<p>Convert the dates to Julian Day Number, then do a little bit of math. Since Mondays are zero mod 7, you could do the calculation like this:</p>\n\n<pre><code>JD1=JulianDayOf(the_first_date)\nJD2=JulianDayOf(the_second_date)\nRound JD1 up to nearest multiple of 7\nRound JD2 up to nearest multiple of 7\nd = JD2-JD1\nnMondays = (JD2-JD1+7)/7 # integer divide\n</code></pre>\n"
},
{
"answer_id": 248374,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem for a report. I needed the number of workdays between two dates.\nI could have cycled through the dates and counted but my discrete math training wouldn't let me. Here is a function I wrote in VBA to get the number of workdays between two dates. I'm sure .net has a similar WeekDay function.</p>\n\n<pre><code> 1 \n 2 ' WorkDays\n 3 ' returns the number of working days between two dates\n 4 Public Function WorkDays(ByVal dtBegin As Date, ByVal dtEnd As Date) As Long\n 5 \n 6 Dim dtFirstSunday As Date\n 7 Dim dtLastSaturday As Date\n 8 Dim lngWorkDays As Long\n 9 \n 10 ' get first sunday in range\n 11 dtFirstSunday = dtBegin + ((8 - Weekday(dtBegin)) Mod 7)\n 12 \n 13 ' get last saturday in range\n 14 dtLastSaturday = dtEnd - (Weekday(dtEnd) Mod 7)\n 15 \n 16 ' get work days between first sunday and last saturday\n 17 lngWorkDays = (((dtLastSaturday - dtFirstSunday) + 1) / 7) * 5\n 18 \n 19 ' if first sunday is not begin date\n 20 If dtFirstSunday <> dtBegin Then\n 21 \n 22 ' assume first sunday is after begin date\n 23 ' add workdays from begin date to first sunday\n 24 lngWorkDays = lngWorkDays + (7 - Weekday(dtBegin))\n 25 \n 26 End If\n 27 \n 28 ' if last saturday is not end date\n 29 If dtLastSaturday <> dtEnd Then\n 30 \n 31 ' assume last saturday is before end date\n 32 ' add workdays from last saturday to end date\n 33 lngWorkDays = lngWorkDays + (Weekday(dtEnd) - 1)\n 34 \n 35 End If\n 36 \n 37 ' return working days\n 38 WorkDays = lngWorkDays\n 39 \n 40 End Function\n</code></pre>\n"
},
{
"answer_id": 248525,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 7,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>static int CountDays(DayOfWeek day, DateTime start, DateTime end)\n{\n TimeSpan ts = end - start; // Total duration\n int count = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks\n int remainder = (int)(ts.TotalDays % 7); // Number of remaining days\n int sinceLastDay = (int)(end.DayOfWeek - day); // Number of days since last [day]\n if (sinceLastDay < 0) sinceLastDay += 7; // Adjust for negative days since last [day]\n\n // If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.\n if (remainder >= sinceLastDay) count++; \n\n return count;\n}\n</code></pre>\n"
},
{
"answer_id": 248579,
"author": "Paul Osterhout",
"author_id": 30976,
"author_profile": "https://Stackoverflow.com/users/30976",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private System.Int32 CountDaysOfWeek(System.DayOfWeek dayOfWeek, System.DateTime date1, System.DateTime date2)\n{\n System.DateTime EndDate;\n System.DateTime StartDate;\n\n if (date1 > date2)\n {\n StartDate = date2;\n EndDate = date1;\n }\n else\n {\n StartDate = date1;\n EndDate = date2;\n }\n\n while (StartDate.DayOfWeek != dayOfWeek)\n StartDate = StartDate.AddDays(1);\n\n return EndDate.Subtract(StartDate).Days / 7 + 1;\n}\n</code></pre>\n"
},
{
"answer_id": 1322835,
"author": "Olivier de Rivoyre",
"author_id": 26071,
"author_profile": "https://Stackoverflow.com/users/26071",
"pm_score": 1,
"selected": false,
"text": "<p>I have had the same need today. I started with the <em>cjm</em> function since I don't understand the <em>JonB</em> function and since the <em>Cyberherbalist</em> function is not linear.</p>\n\n<p>I had have to correct</p>\n\n<pre><code>DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayOfWeek(Start) <= DayImLookingFor\n+ 1 if DayOfWeek(End) >= DayImLookingFor\n- 1\n</code></pre>\n\n<p>to</p>\n\n<pre><code>DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayImLookingFor is between Start.Day and End.Day \n</code></pre>\n\n<p>With the between function that return true if, starting from the start day, we meet first the dayImLookingFor before the endDay.</p>\n\n<p>I have done the between function by computing the number of day from startDay to the other two days:</p>\n\n<pre><code>private int CountDays(DateTime start, DateTime end, DayOfWeek selectedDay)\n{\n if (start.Date > end.Date)\n {\n return 0;\n }\n int totalDays = (int)end.Date.Subtract(start.Date).TotalDays;\n DayOfWeek startDay = start.DayOfWeek;\n DayOfWeek endDay = end.DayOfWeek;\n ///look if endDay appears before or after the selectedDay when we start from startDay.\n int startToEnd = (int)endDay - (int)startDay;\n if (startToEnd < 0)\n {\n startToEnd += 7;\n }\n int startToSelected = (int)selectedDay - (int)startDay;\n if (startToSelected < 0)\n {\n startToSelected += 7;\n }\n bool isSelectedBetweenStartAndEnd = startToEnd >= startToSelected;\n if (isSelectedBetweenStartAndEnd)\n {\n return totalDays / 7 + 1;\n }\n else\n {\n return totalDays / 7;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8397382,
"author": "Terje Kvannli",
"author_id": 1081743,
"author_profile": "https://Stackoverflow.com/users/1081743",
"pm_score": 2,
"selected": false,
"text": "\nYou could try this, if you want to get specific week days between two dates\n\n\n<pre><code>public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)\n{\n var selectedDates = new List<DateTime>();\n\n if (startDate >= endDate)\n return selectedDates; //No days to return\n\n if (daysToCheck == null || daysToCheck.Count == 0)\n return selectedDates; //No days to select\n\n try\n {\n //Get the total number of days between the two dates\n var totalDays = (int)endDate.Subtract(startDate).TotalDays;\n\n //So.. we're creating a list of all dates between the two dates:\n var allDatesQry = from d in Enumerable.Range(1, totalDays)\n select new DateTime(\n startDate.AddDays(d).Year,\n startDate.AddDays(d).Month,\n startDate.AddDays(d).Day);\n\n //And extracting those weekdays we explicitly wanted to return\n var selectedDatesQry = from d in allDatesQry\n where daysToCheck.Contains(d.DayOfWeek)\n select d;\n\n //Copying the IEnumerable to a List\n selectedDates = selectedDatesQry.ToList();\n }\n catch (Exception ex)\n {\n //Log error\n //...\n\n //And re-throw\n throw;\n }\n return selectedDates;\n}\n</code></pre>\n"
},
{
"answer_id": 9026080,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 0,
"selected": false,
"text": "<p>Four years later, I thought I'd run a test:</p>\n\n<pre><code>[TestMethod]\npublic void ShouldFindFridaysInTimeSpan()\n{\n //reference: http://stackoverflow.com/questions/248273/count-number-of-mondays-in-a-given-date-range\n\n var spanOfSixtyDays = new TimeSpan(60, 0, 0, 0);\n var setOfDates = new List<DateTime>(spanOfSixtyDays.Days);\n var now = DateTime.Now;\n\n for(int i = 0; i < spanOfSixtyDays.Days; i++)\n {\n setOfDates.Add(now.AddDays(i));\n }\n\n Assert.IsTrue(setOfDates.Count == 60,\n \"The expected number of days is not here.\");\n\n var fridays = setOfDates.Where(i => i.DayOfWeek == DayOfWeek.Friday);\n\n Assert.IsTrue(fridays.Count() > 0,\n \"The expected Friday days are not here.\");\n Assert.IsTrue(fridays.First() == setOfDates.First(i => i.DayOfWeek == DayOfWeek.Friday),\n \"The expected first Friday day is not here.\");\n Assert.IsTrue(fridays.Last() == setOfDates.Last(i => i.DayOfWeek == DayOfWeek.Friday),\n \"The expected last Friday day is not here.\");\n}\n</code></pre>\n\n<p>My use of <code>TimeSpan</code> is a bit of overkill---actually I wanted to query <code>TimeSpan</code> directly.</p>\n"
},
{
"answer_id": 9418562,
"author": "Peter Morris",
"author_id": 61311,
"author_profile": "https://Stackoverflow.com/users/61311",
"pm_score": 1,
"selected": false,
"text": "<p>This will return a collection of integers showing how many times each day of the week occurs within a date range</p>\n\n<pre><code> int[] CountDays(DateTime firstDate, DateTime lastDate)\n {\n var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;\n var weeks = (int)Math.Floor(totalDays / 7);\n\n var result = Enumerable.Repeat<int>(weeks, 7).ToArray();\n if (totalDays % 7 != 0)\n {\n int firstDayOfWeek = (int)firstDate.DayOfWeek;\n int lastDayOfWeek = (int)lastDate.DayOfWeek;\n if (lastDayOfWeek < firstDayOfWeek)\n lastDayOfWeek += 7;\n for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)\n result[dayOfWeek % 7]++;\n }\n return result;\n }\n</code></pre>\n\n<p>Or a slight variation which lets you do FirstDate.TotalDaysOfWeeks(SecondDate) and returns a Dictionary</p>\n\n<pre><code> public static Dictionary<DayOfWeek, int> TotalDaysOfWeeks(this DateTime firstDate, DateTime lastDate)\n {\n var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;\n var weeks = (int)Math.Floor(totalDays / 7);\n\n var resultArray = Enumerable.Repeat<int>(weeks, 7).ToArray();\n if (totalDays % 7 != 0)\n {\n int firstDayOfWeek = (int)firstDate.DayOfWeek;\n int lastDayOfWeek = (int)lastDate.DayOfWeek;\n if (lastDayOfWeek < firstDayOfWeek)\n lastDayOfWeek += 7;\n for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)\n resultArray[dayOfWeek % 7]++;\n }\n var result = new Dictionary<DayOfWeek, int>();\n for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++)\n result[(DayOfWeek)dayOfWeek] = resultArray[dayOfWeek];\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 56919715,
"author": "Monzur",
"author_id": 1331294,
"author_profile": "https://Stackoverflow.com/users/1331294",
"pm_score": 1,
"selected": false,
"text": "<p>A bit Modified Code is here works and Tested by me</p>\n\n<pre><code> private int CountDays(DayOfWeek day, DateTime startDate, DateTime endDate)\n {\n int dayCount = 0;\n\n for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))\n {\n if (dt.DayOfWeek == day)\n {\n dayCount++;\n }\n }\n\n return dayCount;\n }\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>int Days = CountDays(DayOfWeek.Friday, Convert.ToDateTime(\"2019-07-04\"), \n Convert.ToDateTime(\"2019-07-27\")).ToString();\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32552/"
] |
Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.
I am currently working in C#.
|
Try this:
```
static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
TimeSpan ts = end - start; // Total duration
int count = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks
int remainder = (int)(ts.TotalDays % 7); // Number of remaining days
int sinceLastDay = (int)(end.DayOfWeek - day); // Number of days since last [day]
if (sinceLastDay < 0) sinceLastDay += 7; // Adjust for negative days since last [day]
// If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.
if (remainder >= sinceLastDay) count++;
return count;
}
```
|
248,312 |
<p>Two table:</p>
<pre><code>StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar
UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
</code></pre>
<p>the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo. </p>
<p>the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.</p>
<pre><code>declare @UserName nvarchar(255)
declare @Password nvarchar(25)
declare @UserId uniqueidentifier
select @UserName = UserName, @Password = Password, @UserId = UserId
from UserInfo
select UserId, Password
from FranchiseInfo
where UserID = @UserName and Password = @Password
update FranchiseInfo
set UserI = @UserId
</code></pre>
|
[
{
"answer_id": 248323,
"author": "Philip Kelley",
"author_id": 7491,
"author_profile": "https://Stackoverflow.com/users/7491",
"pm_score": 0,
"selected": false,
"text": "<pre><code>UPDATE StoreInfo\n set UserId = ui.UserId\n from StoreInfo si\n inner join UserInfo ui\n on ui.UserName = si.UserName\n and ui.Password = si.Password\n where si.UserId is null\n</code></pre>\n\n<p>This will update all rows in the table where UserId is not set. Build out the where clause if you only want to update selected rows. (I haven't tested this, so watch for typos!)</p>\n"
},
{
"answer_id": 248324,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "<p>The update would look like this</p>\n\n<pre><code>update storeinfo\nset userid = u.userid\nfrom userinfo u \ninner join storeinfo s on (s.username = u.username and s.password = u.password)\nwhere userid is null\n</code></pre>\n"
},
{
"answer_id": 248326,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 0,
"selected": false,
"text": "<p>The most efficient way is the <code>UPDATE ... FROM</code> syntax, e.g.</p>\n\n<pre><code>UPDATE StoreInfo\nSET\n UserId = ui.UserId\nFROM\n StoreInfo si\n INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
Two table:
```
StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar
UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
```
the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo.
the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.
```
declare @UserName nvarchar(255)
declare @Password nvarchar(25)
declare @UserId uniqueidentifier
select @UserName = UserName, @Password = Password, @UserId = UserId
from UserInfo
select UserId, Password
from FranchiseInfo
where UserID = @UserName and Password = @Password
update FranchiseInfo
set UserI = @UserId
```
|
The update would look like this
```
update storeinfo
set userid = u.userid
from userinfo u
inner join storeinfo s on (s.username = u.username and s.password = u.password)
where userid is null
```
|
248,315 |
<p>I have a simple Flex application that is a panel with a repeater inside of it; albeit a little simplified, it is like such:</p>
<pre>
<code>
<mx:Panel id="pnl">
<mx:Repeater id="rp">
<mx:Label text = "foo" />
</mx:Repeater>
</mx:Panel>
</code>
</pre>
<p>I am then embedding this Flex application into an HTML wrapper. I am then attempting to dynamically re size the embedded Flash object in the HTML as the Flex panel changes size (thus allowing the Flex application to consume as much of the HTML page as it needs). </p>
<p>I am doing this by doing the following actionscipt:</p>
<p><pre>
<code>
pnl.addEventListener(ResizeEvent.RESIZE,function(event:Event):void {
ExternalInterface.call("resize",event.target.height);
});
</code>
</pre>which in turn calls this javascript function:</p>
<pre>
<code>
function resize(height) {
// the embed or object that contains the flex app
var e = document.getElementById('flex_object');
if(e) e.height = height;
}
</code>
</pre>
<p>This seems to work perfect in IE, however I get strange results in Firefox / Safari, the repeater works for <em>n</em> number of times, and then the text seems to get cut off / disappear in the repeater, see the attached image:
<a href="http://img528.imageshack.us/img528/9538/rpre0.jpg" rel="nofollow noreferrer">alt text http://img528.imageshack.us/img528/9538/rpre0.jpg</a></p>
<p>Can anyone explain why this is happening, and if there are any workarounds / ways of doing the same thing?</p>
|
[
{
"answer_id": 258517,
"author": "netsuo",
"author_id": 27911,
"author_profile": "https://Stackoverflow.com/users/27911",
"pm_score": 0,
"selected": false,
"text": "<p>Why not simply using percent width and height on your HTML page for your Flash object ? This way you event don't have to do anything to resize your SWF...</p>\n"
},
{
"answer_id": 264222,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 0,
"selected": false,
"text": "<p>That's very strange - it looks like Firefox/Safari are expanding the draw area of the embed, but somehow Flash is not getting the message that it needs to render the new pixels.</p>\n\n<p>You could probably work around this by doing something to force Flash to update itself, but since the communication between the browsers and the embed seems to be confused it would probably be less hackish to take a different approach, that fits into the browsers' event flow without bugging.</p>\n\n<p>For example, instead of resizing the embed, you might try putting Flash inside a <code>DIV</code>, setting the Flash's size to 100%, and then resizing the <code>DIV</code>. That seems a lot less likely to misbehave.</p>\n"
},
{
"answer_id": 462463,
"author": "cwallenpoole",
"author_id": 57191,
"author_profile": "https://Stackoverflow.com/users/57191",
"pm_score": 0,
"selected": false,
"text": "<p>My experience is that Flex's resizing abilities are... funny. Sometimes they work the way one would expect, other times they do not. There are a couple of things you could try: first, trace the value you expect to get in Flex for the height or even ExternalInterface.call(\"alert\",event.target.height); This will let you know if it is a JavaScript or a Flex problem for sure (but I suspect it is Flex).</p>\n\n<p>Your problem might have to do with the scaling of the component:\n<blockquote>\nSetting [the height] property causes a resize event to be dispatched. See the resize event for details on when this event is dispatched. If the component's scaleY property is not 100, the height of the component from its internal coordinates will not match. Thus a 100 pixel high component with a scaleY of 200 will take 100 pixels in the parent, but will internally think it is 50 pixels high. \n</blockquote><br /></p>\n\n<p>If it is Flex and that does not help, I would try using callLater in front of the ExternalInterface call, often that will allow Flex enough time to figure out what the heck it is doing. Occasionally, setTimeout is needed, but I find that awkward.</p>\n"
},
{
"answer_id": 1353909,
"author": "DanyAlejandro",
"author_id": 165606,
"author_profile": "https://Stackoverflow.com/users/165606",
"pm_score": 1,
"selected": false,
"text": "<p>I'm currently working in the same thing (a swf that dynamically changes it's height depending on the content it's currently holding). I also had a similar problem to yours trying to make a multi-line button.</p>\n\n<p>I'm new to flex but I managed to solve the problem manually invoking the updateDisplayList() of the container... I think it \"forces\" a render somewhere... it's parameters are the width and height of some area where the changes happen. Sorry for not knowing the details... But it worked for me.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
I have a simple Flex application that is a panel with a repeater inside of it; albeit a little simplified, it is like such:
```
<mx:Panel id="pnl">
<mx:Repeater id="rp">
<mx:Label text = "foo" />
</mx:Repeater>
</mx:Panel>
```
I am then embedding this Flex application into an HTML wrapper. I am then attempting to dynamically re size the embedded Flash object in the HTML as the Flex panel changes size (thus allowing the Flex application to consume as much of the HTML page as it needs).
I am doing this by doing the following actionscipt:
```
pnl.addEventListener(ResizeEvent.RESIZE,function(event:Event):void {
ExternalInterface.call("resize",event.target.height);
});
```
which in turn calls this javascript function:
```
function resize(height) {
// the embed or object that contains the flex app
var e = document.getElementById('flex_object');
if(e) e.height = height;
}
```
This seems to work perfect in IE, however I get strange results in Firefox / Safari, the repeater works for *n* number of times, and then the text seems to get cut off / disappear in the repeater, see the attached image:
[alt text http://img528.imageshack.us/img528/9538/rpre0.jpg](http://img528.imageshack.us/img528/9538/rpre0.jpg)
Can anyone explain why this is happening, and if there are any workarounds / ways of doing the same thing?
|
I'm currently working in the same thing (a swf that dynamically changes it's height depending on the content it's currently holding). I also had a similar problem to yours trying to make a multi-line button.
I'm new to flex but I managed to solve the problem manually invoking the updateDisplayList() of the container... I think it "forces" a render somewhere... it's parameters are the width and height of some area where the changes happen. Sorry for not knowing the details... But it worked for me.
|
248,320 |
<p>I have some HTML that looks like this:</p>
<pre><code><ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
</code></pre>
<p>Using CSS I'm setting the <code>p</code> tag to <code>display:none;</code>. I want to use jQuery to display or hide the <code>p</code> tag when the <code>anchor</code> is clicked, but I'm having some troubles with the sibling selector. </p>
<p>Just trying to get the selector working, I tried:</p>
<pre><code>$("a.question").click(function () {
$(this + " ~ p").css("background-color", "red");
});
</code></pre>
<p>to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen. </p>
|
[
{
"answer_id": 248331,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$(this).next(\"p\").css(\"...\")\n</code></pre>\n\n<p>the \"p\" above is optional, if you just want the next non-whitespace node in the DOM.</p>\n"
},
{
"answer_id": 248335,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 6,
"selected": true,
"text": "<p>Try using: </p>\n\n<pre><code>$(this).siblings('p').css()\n</code></pre>\n"
},
{
"answer_id": 248347,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I want to use jQuery to display or hide the 'p' tag when the anchor is clicked</p>\n</blockquote>\n\n<p>Since you mentioned that you'd like to toggle the 'p' tag when the anchor is clicked, I'd do:</p>\n\n<pre><code> $(\"a.question\").click(function (event) {\n $(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element\n event.preventDefault(); //stop the browser from following the link\n }); \n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4106/"
] |
I have some HTML that looks like this:
```
<ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
```
Using CSS I'm setting the `p` tag to `display:none;`. I want to use jQuery to display or hide the `p` tag when the `anchor` is clicked, but I'm having some troubles with the sibling selector.
Just trying to get the selector working, I tried:
```
$("a.question").click(function () {
$(this + " ~ p").css("background-color", "red");
});
```
to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen.
|
Try using:
```
$(this).siblings('p').css()
```
|
248,332 |
<p>I have this large C++ project that I need to build on a platform that does not have a parallel make (like make -j on Linux). The server has 6 CPU's and I want to do a parallel build manually. </p>
<p>I can generate a task list like this for about 300 object files. I use the Makefile for the dependency checks and incremental build:</p>
<p>make -f Makefile obj1.o</p>
<p>make -f Makefile obj2.o</p>
<p>make -f Makefile obj3.o
...</p>
<p>How would I execute these tasks in parallel with no more then 6 tasks running at a time using Ksh and Perl? (Java or Python are not available :-( )</p>
|
[
{
"answer_id": 248365,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": -1,
"selected": false,
"text": "<p>If the OS is properly handling inter-processor communication and scheduling, you should just be able to throw all the makes into backgrounded processes, as long as there are no interdependencies.</p>\n\n<p>If they're all independent, I would issues a series of commands like this:</p>\n\n<pre><code>make -f Makefile obj1.o &\nmake -f Makefile obj2.o &\n...\nmake -f Makefile objn.o &\n</code></pre>\n\n<p>With dependencies, string them with the double ampersand (<code>&&</code>) so that the dependent item doesn't start until its 'parent' has finished.</p>\n\n<p>I realize that's not quite the solution you requested, but it's how I would attack the problem :)</p>\n"
},
{
"answer_id": 248447,
"author": "mpeters",
"author_id": 12094,
"author_profile": "https://Stackoverflow.com/users/12094",
"pm_score": 4,
"selected": true,
"text": "<p>In Perl the you should look at <a href=\"http://search.cpan.org/perldoc?Parallel::ForkManager\" rel=\"nofollow noreferrer\">Parallel::ForkManager</a>. You could do something like this:</p>\n\n<pre><code>my @make_obj = qw(\n obj1.o\n obj2.o\n obj3.o\n ...\n);\n\nmy $fm = $pm = new Parallel::ForkManager(6);\nforeach my $obj (@make_obj) {\n $fm->start and next;\n system(\"make -f Makefile $make_obj\");\n $fm->finish();\n}\n</code></pre>\n"
},
{
"answer_id": 248890,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to forking is to run each make in its own thread.</p>\n\n<pre><code>use threads;\n\nmy $max_threads = 5;\n\nmy @targets = qw(obj1.o obj2.o obj3.o ...);\nwhile(@targets) {\n my $num_threads = threads->list(threads::running);\n if( $num_threads < $max_threads ) {\n my $target = shift @targets;\n threads->create(sub { return system \"make $target\" });\n }\n}\n</code></pre>\n\n<p>I am unfortunately hand waving around two bits. First is making the loop wait quiescently until a thread finishes. I believe this is accomplished using threads::shared's cond_wait() and a semaphore variable.</p>\n\n<p>The second is getting the return value from make, so you know if something failed and to halt the build. To do that you'd have to join() each thread to get the result of system(), the process' exit code.</p>\n\n<p>Sorry for the hasty reply. Hopefully the community will fill in the rest.</p>\n"
},
{
"answer_id": 248937,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "<p>Does gnu make on HPUX not have the -j flag?</p>\n\n<p><a href=\"http://hpux.connect.org.uk/hppd/hpux/Gnu/make-3.81/\" rel=\"nofollow noreferrer\">http://hpux.connect.org.uk/hppd/hpux/Gnu/make-3.81/</a></p>\n"
},
{
"answer_id": 19799409,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 1,
"selected": false,
"text": "<p>Using GNU Parallel you can write:</p>\n\n<pre><code>parallel -j6 make -f Makefile obj{}.o ::: {1..500}\n</code></pre>\n\n<p>10 second installation:</p>\n\n<pre><code>(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash\n</code></pre>\n\n<p>Learn more: <a href=\"http://www.gnu.org/software/parallel/parallel_tutorial.html\" rel=\"nofollow\">http://www.gnu.org/software/parallel/parallel_tutorial.html</a> <a href=\"https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1\" rel=\"nofollow\">https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1</a></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7743/"
] |
I have this large C++ project that I need to build on a platform that does not have a parallel make (like make -j on Linux). The server has 6 CPU's and I want to do a parallel build manually.
I can generate a task list like this for about 300 object files. I use the Makefile for the dependency checks and incremental build:
make -f Makefile obj1.o
make -f Makefile obj2.o
make -f Makefile obj3.o
...
How would I execute these tasks in parallel with no more then 6 tasks running at a time using Ksh and Perl? (Java or Python are not available :-( )
|
In Perl the you should look at [Parallel::ForkManager](http://search.cpan.org/perldoc?Parallel::ForkManager). You could do something like this:
```
my @make_obj = qw(
obj1.o
obj2.o
obj3.o
...
);
my $fm = $pm = new Parallel::ForkManager(6);
foreach my $obj (@make_obj) {
$fm->start and next;
system("make -f Makefile $make_obj");
$fm->finish();
}
```
|
248,350 |
<p>The windows installed on my machine has the locale <code>en_AU</code> and that's what JasperReports uses. I already tried changing the locale of all users, including the Administrator but it still uses <code>en_AU</code>.</p>
<p>How can I change that locale? Is it possible to change the <code>REPORT_LOCALE</code> parameter on my report?</p>
|
[
{
"answer_id": 772406,
"author": "waxwing",
"author_id": 90566,
"author_profile": "https://Stackoverflow.com/users/90566",
"pm_score": 6,
"selected": false,
"text": "<p>The locale is set during execution, not in the JRXML.</p>\n\n<p>Using Java, set the <code>REPORT_LOCALE</code> parameter for the report's parameter map. For example:</p>\n\n<pre><code>InputStream reportTemplate = getReportTemplate();\nJRDataSource dataSource = getDataSource();\n\njava.util.Map parameters = getParameters();\njava.util.Locale locale = new Locale( \"en\", \"US\" );\nparameters.put( JRParameter.REPORT_LOCALE, locale );\n\nJasperFillManager.fillReport( reportTemplate, parameters, dataSource );\n</code></pre>\n\n<p>Using Jaspersoft Studio, open the project properties dialog to the <strong>Report Execution</strong> area:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DRjFS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DRjFS.png\" alt=\"Project Properties\"></a></p>\n\n<p>Using iReport, set the report locale in the Options window under the \"Report execution options\" section in the General tab. This will set the report locale when run.</p>\n"
},
{
"answer_id": 65848996,
"author": "siom",
"author_id": 2833924,
"author_profile": "https://Stackoverflow.com/users/2833924",
"pm_score": 0,
"selected": false,
"text": "<p>You can set the locale on JVM that executes the <code>JasperFillManager</code> code if you do not want to change the code:</p>\n<pre><code>java -Duser.language=de -Duser.country=CH ...\n</code></pre>\n"
},
{
"answer_id": 69773254,
"author": "Jan Bodnar",
"author_id": 2008247,
"author_profile": "https://Stackoverflow.com/users/2008247",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to set the locale <code>net.sf.jasperreports.default.locale</code> property in the <code>jasperreports.properties</code> file.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16020/"
] |
The windows installed on my machine has the locale `en_AU` and that's what JasperReports uses. I already tried changing the locale of all users, including the Administrator but it still uses `en_AU`.
How can I change that locale? Is it possible to change the `REPORT_LOCALE` parameter on my report?
|
The locale is set during execution, not in the JRXML.
Using Java, set the `REPORT_LOCALE` parameter for the report's parameter map. For example:
```
InputStream reportTemplate = getReportTemplate();
JRDataSource dataSource = getDataSource();
java.util.Map parameters = getParameters();
java.util.Locale locale = new Locale( "en", "US" );
parameters.put( JRParameter.REPORT_LOCALE, locale );
JasperFillManager.fillReport( reportTemplate, parameters, dataSource );
```
Using Jaspersoft Studio, open the project properties dialog to the **Report Execution** area:
[](https://i.stack.imgur.com/DRjFS.png)
Using iReport, set the report locale in the Options window under the "Report execution options" section in the General tab. This will set the report locale when run.
|
248,351 |
<p>I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?</p>
|
[
{
"answer_id": 248379,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>just as you say, have them put a div at the bottom of their page:</p>\n\n<pre><code><div id=\"mywidget\"></div>\n</code></pre>\n\n<p>then have them link to your javascript:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"http://yourdomain.com/mywidget.js\"></script>\n</code></pre>\n\n<p>then have them alter their body tag, or onload to call your script</p>\n\n<pre><code><script type=\"text/javascript\">\n document.body.onload = loadYourWidget();\n</script>\n</code></pre>\n"
},
{
"answer_id": 248392,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 0,
"selected": false,
"text": "<p>Like @Owen said, except why not craft your javascript so that </p>\n\n<pre><code><script type=\"text/javascript\" src=\"http://yourdomain.com/mywidget.js\"></script>\n</code></pre>\n\n<p>does the work of populating <code><div id=\"mywidget\"></div></code> on its own, thus negating the need for them to call loadYourWidget() from their DOM load if you include the script tag right after the mywidget div in the html source. This isn't really a best practice, but I think it'll work.</p>\n\n<p>Example for your mywidget.js code:</p>\n\n<pre><code>document.getElementById('mywidget').innerHTML = \"<a href=''>LinkOne</a> <a href=''>LinkTwo</a>\";\n</code></pre>\n"
},
{
"answer_id": 248451,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:</p>\n\n<pre><code><script id=\"my-script\" src=\"http://example.com/my-script.js\"></script>\n</code></pre>\n\n<p>In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:</p>\n\n<pre><code>var scriptTag, myDiv;\nscriptTag = document.getElementById('my-script');\nmyDiv = document.createElement('DIV');\nmyDiv.innerHTML = '<p>Wow, cool!</p>';\nscriptTag.parentNode.replaceChild(myDiv, scriptTag);\n</code></pre>\n"
},
{
"answer_id": 248514,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 1,
"selected": false,
"text": "<p>You do not necessary need an initial div to fill with you link list.</p>\n\n<p>Simply create the div using <em><code>document.write</code></em> at the place where the script is placed.</p>\n\n<pre><code><script type=\"text/javascript\" src=\"http://domain.com/badge.js\"></script>\n</code></pre>\n\n<p>... and in your script:</p>\n\n<pre><code>var links = [\n '<a href=\"#\">One</a>',\n '<a href=\"#\">Two</a>', \n '<a href=\"#\">Three</a>'\n];\n\ndocument.write(\"<div>\" + links.join(\", \") + \"</div>\");\n</code></pre>\n\n<p>Another benefit is that you do not have to wait for the page to be fully loaded.</p>\n"
},
{
"answer_id": 12251737,
"author": "ptim",
"author_id": 2586761,
"author_profile": "https://Stackoverflow.com/users/2586761",
"pm_score": 0,
"selected": false,
"text": "<p>It took me some time to find <a href=\"https://stackoverflow.com/questions/8256083/how-does-the-facebook-like-button-work\" title=\"How does the Facebook Like button work?\">this answer on Stackexchange</a> because I was using different search terms. I believe that the link suggested there is a more complete answer than the ones already given here:</p>\n\n<p><a href=\"http://alexmarandon.com/articles/web_widget_jquery/\" rel=\"nofollow noreferrer\">How to build a web widget (using jQuery)</a></p>\n\n<p>It covers:</p>\n\n<blockquote>\n <ul>\n <li>ensure the widget’s code doesn’t accidentally mess up with the rest of the page,</li>\n <li>dynamically load external CSS and JavaScript files,</li>\n <li>bypass browsers’ single-origin policy using JSONP.</li>\n </ul>\n</blockquote>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3784/"
] |
I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?
|
I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:
```
<script id="my-script" src="http://example.com/my-script.js"></script>
```
In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:
```
var scriptTag, myDiv;
scriptTag = document.getElementById('my-script');
myDiv = document.createElement('DIV');
myDiv.innerHTML = '<p>Wow, cool!</p>';
scriptTag.parentNode.replaceChild(myDiv, scriptTag);
```
|
248,353 |
<p>I'm busy with an asignment where i have to make a graphical interface for a simple program. But i'm strugling with the layout.</p>
<p>This is the idea:<br>
<img src="https://i.stack.imgur.com/a3Xk7.png" alt="Layout Example" title="Layout Example"></p>
<p>What is the easiest way to accomplish such a layout?</p>
<p>And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?</p>
|
[
{
"answer_id": 248380,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?</p>\n</blockquote>\n\n<p>NetBeans for GUI developers is like a calculator for grade schoolers: you really shouldn't use it until you know how to do things without it, but then it will save you a lot of time.</p>\n\n<p>(I'd love to answer your primary question, but the firewall I'm behind is blocking the picture.)</p>\n"
},
{
"answer_id": 248383,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "<p>I used to love Motif's XmForm for this sort of thing. In Java, I usually put Boxes inside of boxes. So I have a vertical box. First row of the box contains a JLabel for the Instruction. Second row contains something for the label/result stuff, possibly some sort of grid. Third row contains whatever that blacked out thing, Fourth row contains the JTable. Then I'd spend some time to try to figure out how to do the lable/result stuff. Then I'd probably end up saying \"dammit\", and doing it as a GridBagLayout.</p>\n"
},
{
"answer_id": 248406,
"author": "Christian",
"author_id": 32279,
"author_profile": "https://Stackoverflow.com/users/32279",
"pm_score": 1,
"selected": false,
"text": "<p>For myself gui-builders for swing or swt never worked that well that's why i code layouts myself using layout managers. \nYour question doesn't mention which gui-system you are using but i assume you want to use swing. If that's the case I would recommend to use GridBagLayout for your layout. It is not that easy to use in the beginning but as soon as you know how it works you can do most layouts in the way you want it to be and i think it is also the layoutmanager of choice for the layout you want to do.</p>\n"
},
{
"answer_id": 248435,
"author": "bmeck",
"author_id": 12781,
"author_profile": "https://Stackoverflow.com/users/12781",
"pm_score": 3,
"selected": true,
"text": "<p>Well considering how simple the layout is I would suggest you use a BorderLayout with NORTH set to the top section in a container and the JTable in the CENTER of the BorderLayout. For the Top it appears to be a simple BorderLayout again with NORTH as the Instruction: south as the black box (possibly in a container with a FlowLayout). The center of the top pane appears to be 2 Containers of GridLayouts with 2 rows and 2 columns, so put thos in another container with a GirdLayout.</p>\n\n<p>So in pseudo:</p>\n\n<pre><code>Container(BorderLayout)\n{\n @NORTH\n Container(BorderLayout)\n {\n @NORTH\n Label(Instruction);\n @CENTER\n Container(GridLayout(2,1))\n {\n Container(GirdLayout(2,2))\n {\n Label() TextField()\n Label() TextField() \n }\n Container(GirdLayout(2,2))\n {\n Label() TextField()\n Label() TextField()\n }\n }\n @SOUTH\n Container(FlowLayout())\n {\n JButton() //shaded thing?\n }\n }\n @CENTER\n {\n JTable\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248538,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 2,
"selected": false,
"text": "<p>I build everything by hand. Like Christian, I've had bad experiences with GUI builders; they always either refused to configure a couple of components quite right, or they generated huge amounts of unnecessary code which made later maintenance impractical, or both.</p>\n\n<p>I used to do build a lot of UIs using GridBagLayout, but for years, I've never seen an office-environment UI that couldn't be built with nested BorderLayouts, GridLayouts, and the occasional BoxLayout or FlowLayout. About 98% of the stuff I've seen is doable with nested BorderLayouts.</p>\n\n<p>In your case, the layout organization will be as bmeck says. Speaking from memory, using CENTER for the JTable (remember to put it in a JScrollPane!) and NORTH for everything else ensures that if you resize your JFrame, the JTable will get all of the extra space, and that should be exactly what you want. For the top labels and fields, the nested GridLayouts should ensure that each \"column\" of labels and fields will take up equal horizontal space. (They'll get only enough vertical space to be completely visible, and no more, since the JTable is taking up everything else.)</p>\n\n<p>Everything else is just a matter of adding borders and setting the GridLayout padding reasonably.</p>\n"
},
{
"answer_id": 256466,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 1,
"selected": false,
"text": "<p>I've used GUI layout generating tools for super rapid development (maybe get the first 2 or 3 iterations of an interface out of the way). I've ultimately found that using a simple fixed layout (no layout manager) with these tools is the best approach. Once we are starting to hone in on a design, we switch to manual layout. </p>\n\n<p>Whenever I've tried to use GUI generators to create code for layout managers, I've almost always been bitten eventually where the layout would just stop working and I spent more time debugging the impossible to read auto-generated code than if I'd done the layout by hand anyway. For what it's worth, when we are doing the early phase of layouts, we use the Jigloo plugin for Eclipse. It's very inexpensive, and does a good job.</p>\n\n<p>I'm a big fan of <a href=\"http://www.miglayout.com/\" rel=\"nofollow noreferrer\">MiGLayout</a>. I've found that it is incredibly easy to use for simple layouts, and is capable of doing extremely complicated layouts. All without the need to resort to nested panels, etc... JGoodies Forms is also good, but harder to use.</p>\n"
},
{
"answer_id": 259365,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote an article a while back on layout managers:</p>\n\n<p><a href=\"http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr\" rel=\"nofollow noreferrer\">http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr</a></p>\n\n<p>It describes how nesting (as bmeck above demonstrates) can be used very effectively for many UI designs.</p>\n"
},
{
"answer_id": 538292,
"author": "jedierikb",
"author_id": 62255,
"author_profile": "https://Stackoverflow.com/users/62255",
"pm_score": 1,
"selected": false,
"text": "<p>Try table layout. Works great.</p>\n\n<p><a href=\"https://tablelayout.dev.java.net/\" rel=\"nofollow noreferrer\">https://tablelayout.dev.java.net/</a></p>\n"
},
{
"answer_id": 538320,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"http://java.sun.com/javase/6/docs/api/javax/swing/GroupLayout.html\" rel=\"nofollow noreferrer\">GroupLayout</a></p>\n\n<p>:) </p>\n\n<p>All the alignments are pretty easy to do </p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20261/"
] |
I'm busy with an asignment where i have to make a graphical interface for a simple program. But i'm strugling with the layout.
This is the idea:

What is the easiest way to accomplish such a layout?
And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?
|
Well considering how simple the layout is I would suggest you use a BorderLayout with NORTH set to the top section in a container and the JTable in the CENTER of the BorderLayout. For the Top it appears to be a simple BorderLayout again with NORTH as the Instruction: south as the black box (possibly in a container with a FlowLayout). The center of the top pane appears to be 2 Containers of GridLayouts with 2 rows and 2 columns, so put thos in another container with a GirdLayout.
So in pseudo:
```
Container(BorderLayout)
{
@NORTH
Container(BorderLayout)
{
@NORTH
Label(Instruction);
@CENTER
Container(GridLayout(2,1))
{
Container(GirdLayout(2,2))
{
Label() TextField()
Label() TextField()
}
Container(GirdLayout(2,2))
{
Label() TextField()
Label() TextField()
}
}
@SOUTH
Container(FlowLayout())
{
JButton() //shaded thing?
}
}
@CENTER
{
JTable
}
}
```
|
248,362 |
<p>I am trying to build a dropdown list for a winform interop, and I am creating the dropdown in code. However, I have a problem getting the data to bind based on the DataTemplate I specify.</p>
<p>What am I missing?</p>
<pre><code>drpCreditCardNumberWpf = new ComboBox();
DataTemplate cardLayout = new DataTemplate {DataType = typeof (CreditCardPayment)};
StackPanel sp = new StackPanel
{
Orientation = System.Windows.Controls.Orientation.Vertical
};
TextBlock cardHolder = new TextBlock {ToolTip = "Card Holder Name"};
cardHolder.SetBinding(TextBlock.TextProperty, "BillToName");
sp.Children.Add(cardHolder);
TextBlock cardNumber = new TextBlock {ToolTip = "Credit Card Number"};
cardNumber.SetBinding(TextBlock.TextProperty, "SafeNumber");
sp.Children.Add(cardNumber);
TextBlock notes = new TextBlock {ToolTip = "Notes"};
notes.SetBinding(TextBlock.TextProperty, "Notes");
sp.Children.Add(notes);
cardLayout.Resources.Add(sp, null);
drpCreditCardNumberWpf.ItemTemplate = cardLayout;
</code></pre>
|
[
{
"answer_id": 248638,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 8,
"selected": true,
"text": "<p>Assuming that you've already set up the <code>ItemsSource</code> etc for <code>drpCreditCardNumberWpf</code>...</p>\n\n<pre><code>//create the data template\nDataTemplate cardLayout = new DataTemplate();\ncardLayout.DataType = typeof(CreditCardPayment);\n\n//set up the stack panel\nFrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));\nspFactory.Name = \"myComboFactory\";\nspFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);\n\n//set up the card holder textblock\nFrameworkElementFactory cardHolder = new FrameworkElementFactory(typeof(TextBlock));\ncardHolder.SetBinding(TextBlock.TextProperty, new Binding(\"BillToName\"));\ncardHolder.SetValue(TextBlock.ToolTipProperty, \"Card Holder Name\");\nspFactory.AppendChild(cardHolder);\n\n//set up the card number textblock\nFrameworkElementFactory cardNumber = new FrameworkElementFactory(typeof(TextBlock));\ncardNumber.SetBinding(TextBlock.TextProperty, new Binding(\"SafeNumber\"));\ncardNumber.SetValue(TextBlock.ToolTipProperty, \"Credit Card Number\");\nspFactory.AppendChild(cardNumber);\n\n//set up the notes textblock\nFrameworkElementFactory notes = new FrameworkElementFactory(typeof(TextBlock));\nnotes.SetBinding(TextBlock.TextProperty, new Binding(\"Notes\"));\nnotes.SetValue(TextBlock.ToolTipProperty, \"Notes\");\nspFactory.AppendChild(notes);\n\n//set the visual tree of the data template\ncardLayout.VisualTree = spFactory;\n\n//set the item template to be our shiny new data template\ndrpCreditCardNumberWpf.ItemTemplate = cardLayout;\n</code></pre>\n\n<p>You can use the same way I have set the <code>ToolTip</code> on the <code>TextBlock</code>s to set other properties such as margins.</p>\n"
},
{
"answer_id": 38211618,
"author": "a_a",
"author_id": 5975828,
"author_profile": "https://Stackoverflow.com/users/5975828",
"pm_score": 0,
"selected": false,
"text": "<p>Well, indeed we still have another way, you will really like it if you dislike those <em><code>FrameworkElementFactory</code></em> things.</p>\n\n<p>And I think it just makes minor changes to the natural code, that is, declare a <em><code>UserControl</code></em> and put your control into it, and then, use just one <em><code>FrameworkElementFactory</code></em> to call the <em><code>UserControl</code></em>.</p>\n\n<p>Simple demo code (in F#):</p>\n\n<pre><code>let buildView()=StackPanel()\n//Build it with natural code\ntype MyView()=inherit UserControl(Content=buildView())\nlet factory=FrameworkElementFactory(typeof<MyView>)\nlet template=DataTemplate(VisualTree=factory)\nlet list=ItemsControl(ItemsSource=makeData(),ItemTemplate=template)\n</code></pre>\n"
},
{
"answer_id": 57461040,
"author": "Pavlo Datsiuk",
"author_id": 2214916,
"author_profile": "https://Stackoverflow.com/users/2214916",
"pm_score": 3,
"selected": false,
"text": "<p>The full version</p>\n\n<pre><code>var ms = new MemoryStream(Encoding.UTF8.GetBytes(@\"<DataTemplate xmlns=\"\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\"\n xmlns:x=\"\"http://schemas.microsoft.com/winfx/2006/xaml\"\" \n xmlns:c=\"\"clr-namespace:MyApp.Converters;assembly=MyApp\"\">\n <DataTemplate.Resources>\n <c:MyConverter x:Key=\"\"MyConverter\"\"/>\n </DataTemplate.Resources>\n <TextBlock Text=\"\"{Binding ., Converter={StaticResource MyConverter}}\"\"/>\n </DataTemplate>\"));\nvar template = (DataTemplate)XamlReader.Load(ms);\n\nvar cb = new ComboBox { };\n//Set the data template\ncb.ItemTemplate = template;\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to build a dropdown list for a winform interop, and I am creating the dropdown in code. However, I have a problem getting the data to bind based on the DataTemplate I specify.
What am I missing?
```
drpCreditCardNumberWpf = new ComboBox();
DataTemplate cardLayout = new DataTemplate {DataType = typeof (CreditCardPayment)};
StackPanel sp = new StackPanel
{
Orientation = System.Windows.Controls.Orientation.Vertical
};
TextBlock cardHolder = new TextBlock {ToolTip = "Card Holder Name"};
cardHolder.SetBinding(TextBlock.TextProperty, "BillToName");
sp.Children.Add(cardHolder);
TextBlock cardNumber = new TextBlock {ToolTip = "Credit Card Number"};
cardNumber.SetBinding(TextBlock.TextProperty, "SafeNumber");
sp.Children.Add(cardNumber);
TextBlock notes = new TextBlock {ToolTip = "Notes"};
notes.SetBinding(TextBlock.TextProperty, "Notes");
sp.Children.Add(notes);
cardLayout.Resources.Add(sp, null);
drpCreditCardNumberWpf.ItemTemplate = cardLayout;
```
|
Assuming that you've already set up the `ItemsSource` etc for `drpCreditCardNumberWpf`...
```
//create the data template
DataTemplate cardLayout = new DataTemplate();
cardLayout.DataType = typeof(CreditCardPayment);
//set up the stack panel
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));
spFactory.Name = "myComboFactory";
spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
//set up the card holder textblock
FrameworkElementFactory cardHolder = new FrameworkElementFactory(typeof(TextBlock));
cardHolder.SetBinding(TextBlock.TextProperty, new Binding("BillToName"));
cardHolder.SetValue(TextBlock.ToolTipProperty, "Card Holder Name");
spFactory.AppendChild(cardHolder);
//set up the card number textblock
FrameworkElementFactory cardNumber = new FrameworkElementFactory(typeof(TextBlock));
cardNumber.SetBinding(TextBlock.TextProperty, new Binding("SafeNumber"));
cardNumber.SetValue(TextBlock.ToolTipProperty, "Credit Card Number");
spFactory.AppendChild(cardNumber);
//set up the notes textblock
FrameworkElementFactory notes = new FrameworkElementFactory(typeof(TextBlock));
notes.SetBinding(TextBlock.TextProperty, new Binding("Notes"));
notes.SetValue(TextBlock.ToolTipProperty, "Notes");
spFactory.AppendChild(notes);
//set the visual tree of the data template
cardLayout.VisualTree = spFactory;
//set the item template to be our shiny new data template
drpCreditCardNumberWpf.ItemTemplate = cardLayout;
```
You can use the same way I have set the `ToolTip` on the `TextBlock`s to set other properties such as margins.
|
248,396 |
<p>I am writing a batch file script using Windows command and want to change each occurrence of some blank space with "," What is the simplest way to do that? </p>
|
[
{
"answer_id": 248401,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>Well it will depend a lot on how you are getting the data, but you may be able to finagle something with a For-Do construct. Make the field seperator be a space then build the string back in the do with a , between each token. Might I suggest a more robust scripting language? You should have VBScript on just about any relatively modern windows bow.</p>\n"
},
{
"answer_id": 248487,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 1,
"selected": false,
"text": "<p>You could download sed.exe from <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">http://unxutils.sourceforge.net/</a> and run this command:</p>\n\n<pre><code>sed -e \"s/ /,/\" infile.txt >outfile.txt\n</code></pre>\n"
},
{
"answer_id": 248805,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 3,
"selected": true,
"text": "<p>If your users are a list of words on one line in a text file, separated by spaces, eg:</p>\n\n<pre><code>one two three four\n</code></pre>\n\n<p>Create a batch file SpaceToComma.bat as follows:</p>\n\n<pre><code>@echo off\nsetlocal\nfor /F \"tokens=* delims= \" %%a in (%1) do @set data=%%a\necho %data: =,%\nendlocal\n</code></pre>\n\n<p>Then run it, you'll get the words separated by commas. Is this what you want?</p>\n\n<pre><code>C:\\>SpaceToComma.bat data.txt\none,two,three,four\n</code></pre>\n\n<p>If you have a multi-line file, then this will do it:</p>\n\n<p>data.txt</p>\n\n<pre><code>one two three four\nfive six seven\n</code></pre>\n\n<p>SpaceToComma.bat</p>\n\n<pre><code>@echo off\nsetlocal\nfor /F \"tokens=* delims= \" %%a in (%1) do @call :processaline %%a\nendlocal\ngoto :eof\n:processaline\nsetlocal\nset data=%*\necho %data: =,%\nendlocal\ngoto:eof\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>C:\\>SpaceToComma.bat data.txt\none,two,three,four\nfive,six,seven\n</code></pre>\n\n<p>(There's probably a clever way of doing this without the subroutine, using the !data! syntax for delayed variable expansion, but I couldn't get it to work with the substitution syntax.)</p>\n\n<p>If this is not what you want, then please explain and I can try to help.</p>\n\n<p>(PS: I delight in using batch files where people insist it can't be done.)</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32565/"
] |
I am writing a batch file script using Windows command and want to change each occurrence of some blank space with "," What is the simplest way to do that?
|
If your users are a list of words on one line in a text file, separated by spaces, eg:
```
one two three four
```
Create a batch file SpaceToComma.bat as follows:
```
@echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do @set data=%%a
echo %data: =,%
endlocal
```
Then run it, you'll get the words separated by commas. Is this what you want?
```
C:\>SpaceToComma.bat data.txt
one,two,three,four
```
If you have a multi-line file, then this will do it:
data.txt
```
one two three four
five six seven
```
SpaceToComma.bat
```
@echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do @call :processaline %%a
endlocal
goto :eof
:processaline
setlocal
set data=%*
echo %data: =,%
endlocal
goto:eof
```
Output
```
C:\>SpaceToComma.bat data.txt
one,two,three,four
five,six,seven
```
(There's probably a clever way of doing this without the subroutine, using the !data! syntax for delayed variable expansion, but I couldn't get it to work with the substitution syntax.)
If this is not what you want, then please explain and I can try to help.
(PS: I delight in using batch files where people insist it can't be done.)
|
248,400 |
<p>I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:</p>
<pre><code>vector<int> n
</code></pre>
<p>and the values are inserted like this:</p>
<pre><code>srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
</code></pre>
<p>I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.</p>
<pre><code>void sieve(vector<int> v, int n)
{
int i,j;
for(i = 2; i <= n; i++)
{
cout << i << " % ";
for(j = 0; j <= n; j++)
{
if(i % v[j] == 0)
cout << v[j] << endl;
}
}
}
</code></pre>
<p>This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?</p>
<p>Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?</p>
<pre><code>void sieve(vector<int> v, BST<int> t, int n)
{
vector<int> v_nonPrime(n);
int i,j;
for(i = 2; i < n; i++)
v_nonPrime[i] = i;
for(i = 2; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(v_nonPrime[i] % j == 0)
cout << v_nonPrime[i] << endl;
}
}
}
</code></pre>
|
[
{
"answer_id": 248436,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 1,
"selected": false,
"text": "<p>You should try using a <a href=\"http://en.wikipedia.org/wiki/Prime_sieve\" rel=\"nofollow noreferrer\">prime sieve</a>. You need to know the maximal number for creating the sieve (<code>O(n)</code>) and then you can build a set of primes in that range (<code>O(max_element)</code> or as the problem states <code>O(1000) == O(1)</code>)) and check whether each number is in the set of primes.</p>\n"
},
{
"answer_id": 248440,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>Basically, you have a lot of unrelated numbers, so for each one you will have to check if it's prime.</p>\n\n<p>If you know the range of the numbers in advance, you can generate all prime numbers that <em>can</em> occur in that range (or the sqrt thereof), and test every number in your container for divisibility by any one of the generated primes.</p>\n\n<p>Generating the primes is best done by the Erathostenes Sieve - many examples to be found of that algorithm.</p>\n"
},
{
"answer_id": 248441,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 2,
"selected": false,
"text": "<p>First off, I think Knuth said it first: premature optimization is the cause of many bugs. Make the slow version first, and then figure out how to make it faster.</p>\n\n<p>Second, for your outer loop, you really only need to go to sqrt(n) rather than n.</p>\n"
},
{
"answer_id": 248444,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "<p>The idea of the sieve that you try to implement depends on the fact that you start at a prime (2) and cross out multitudes of that number - so all numbers that depend on the prime \"2\" are ruled out beforehand. </p>\n\n<p>That's because all non-primes can be factorized down to primes. Whereas primes are not divisible with modulo 0 unless you divide them by 1 or by themselves.</p>\n\n<p>So, if you want to rely on this algorithm, you will need some mean to actually restore this property of the algorithm.</p>\n"
},
{
"answer_id": 248479,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": true,
"text": "<p>In this code:</p>\n\n<pre><code>if(i % v[j] == 0)\n cout << v[j] << endl;\n</code></pre>\n\n<p>You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:</p>\n\n<pre><code>if(v[j] % i == 0)\n</code></pre>\n\n<p>Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. Also, you will have duplicates in your output, perhaps that is ok.</p>\n"
},
{
"answer_id": 248493,
"author": "Rodyland",
"author_id": 10681,
"author_profile": "https://Stackoverflow.com/users/10681",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is just plain wrong. First, you're testing i % v[j] == 0, which is backwards and also explains why you get all numbers. Second, your output will contain duplicates as you're testing and outputting each input number every time it fails the (broken) divisibility test.</p>\n\n<p>Other suggestions:</p>\n\n<p>Using n as the maximum value in the vector and the number of elements in the vector is confusing and pointless. You don't need to pass in the number of elements in the vector - you just query the vector's size. And you can figure out the max fairly quickly (but if you know it ahead of time you may as well pass it in).</p>\n\n<p>As mentioned above, you only need to test to sqrt(n) [where n is the max value in the vecotr]</p>\n\n<p>You could use a sieve to generate all primes up to n and then just remove those values from the input vector, as also suggested above. This may be quicker and easier to understand, especially if you store the primes somewhere.</p>\n\n<p>If you're going to test each number individually (using, I guess, and inverse sieve) then I suggest testing each number individually, in order. IMHO it'll be easier to understand than the way you've written it - testing each number for divisibility by k < n for ever increasing k.</p>\n"
},
{
"answer_id": 248528,
"author": "MaDDoG",
"author_id": 18317,
"author_profile": "https://Stackoverflow.com/users/18317",
"pm_score": 0,
"selected": false,
"text": "<p>Your code seems to have many problems:</p>\n\n<ol>\n<li>If you want to test if your number is prime or non-prime, you would need to check for v[j] % i == 0, not the other way round</li>\n<li>You did not check if your number is dividing by itself</li>\n<li>You keep on checking your numbers again and again. That's very inefficient.</li>\n</ol>\n\n<p>As other guys suggested, you need to do something like the Sieve of Eratosthenes.</p>\n\n<p>So a pseudo C code for your problem would be (I haven't run this through compilers yet, so please ignore syntax errors. This code is to illustrate the algorithm only)</p>\n\n<pre><code>vector<int> inputNumbers;\n\n// First, find all the prime numbers from 1 to n\nbool isPrime[n+1] = {true};\nisPrime[0]= false;\nisPrime[1]= false;\nfor (int i = 2; i <= sqrt(n); i++)\n{\n if (!isPrime[i])\n continue;\n for (int j = 2; j <= n/i; j++)\n isPrime[i*j] = false;\n}\n\n// Check the input array for non-prime numbers\nfor (int i = 0; i < inputNumbers.size(); i++)\n{\n int thisNumber = inputNumbers[i];\n // Vet the input to make sure we won't blow our isPrime array\n if ((0<= thisNumber) && (thisNumber <=n))\n {\n // Prints out non-prime numbers\n if (!isPrime[thisNumber])\n cout<< thisNumber;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248540,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 0,
"selected": false,
"text": "<p>sorting the number first might be a good start - you can do that in nLogN time. That is a small addition (I think) to your other problem - that of finding if a number is prime.<br>\n(actually, with a small set of numbers like that you can do a sort much faster with a copy of the size of the vector/set and do a hash/bucket sort/whatever)</p>\n\n<p>I'd then find the highest number in the set (I assume the numbers can be unbounded - no know upper limit until your sort - or do a single pass to find the max)</p>\n\n<p>then go with a sieve - as others have said</p>\n"
},
{
"answer_id": 248660,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 0,
"selected": false,
"text": "<p>Jeremy is right, the basic problem is your <code>i % v[j]</code> instead of <code>v[j] % i</code>.</p>\n\n<p>Try this:</p>\n\n<pre><code>void sieve(vector<int> v, int n) {\n int i,j;\n\n for(j = 0; j <= n; j++) {\n cout << v[j] << \": \";\n\n for(i = 2; i < v[j]; i++) {\n if(v[j] % i == 0) {\n cout << \"is divisible by \" << i << endl;\n break;\n }\n }\n\n if (i == v[j]) {\n cout << \"is prime.\" << endl;\n }\n }\n}\n</code></pre>\n\n<p>It's not optimal, because it's attempting to divide by all numbers less than <code>v[j]</code> instead of just up to the square root of <code>v[j]</code>. And it is attempting dividion by all numbers instead of only primes.</p>\n\n<p>But it will work.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28392/"
] |
I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:
```
vector<int> n
```
and the values are inserted like this:
```
srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
```
I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.
```
void sieve(vector<int> v, int n)
{
int i,j;
for(i = 2; i <= n; i++)
{
cout << i << " % ";
for(j = 0; j <= n; j++)
{
if(i % v[j] == 0)
cout << v[j] << endl;
}
}
}
```
This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?
Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?
```
void sieve(vector<int> v, BST<int> t, int n)
{
vector<int> v_nonPrime(n);
int i,j;
for(i = 2; i < n; i++)
v_nonPrime[i] = i;
for(i = 2; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(v_nonPrime[i] % j == 0)
cout << v_nonPrime[i] << endl;
}
}
}
```
|
In this code:
```
if(i % v[j] == 0)
cout << v[j] << endl;
```
You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:
```
if(v[j] % i == 0)
```
Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. Also, you will have duplicates in your output, perhaps that is ok.
|
248,405 |
<p>I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.</p>
<pre><code>//code without thread use
public static int getNextPrime(int from) {
int nextPrime = from+1;
boolean superPrime = false;
while(!superPrime) {
boolean prime = true;
for(int i = 2;i < nextPrime;i++) {
if(nextPrime % i == 0) {
prime = false;
}
}
if(prime) {
superPrime = true;
} else {
nextPrime++;
}
}
return nextPrime;
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
list.add(primeStart);
primeStart = getNextPrime(primeStart);
}
}
</code></pre>
<p>If I'm running the code like this and it takes about 56 seconds. If, however, I have the following code (as an alternative):</p>
<pre><code>public class PrimeRunnable implements Runnable {
private int from;
private int lastPrime;
public PrimeRunnable(int from) {
this.from = from;
}
public boolean isPrime(int number) {
for(int i = 2;i < from;i++) {
if((number % i) == 0) {
return false;
}
}
lastPrime = number;
return true;
}
public int getLastPrime() {
return lastPrime;
}
public void run() {
while(!isPrime(++from))
;
}
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
PrimeRunnable pr = new PrimeRunnable(primeStart);
Thread t = new Thread(pr);
t.start();
t.join();
primeStart = pr.getLastPrime();
list.add(primeStart);
}
}
</code></pre>
<p>The whole operation takes about 7 seconds. I am almost certain that even though I only create one thread at a time, a thread doesn't always finish when another is created. Is that right? I am also curious: why is the operation ending so fast?</p>
<p>When I'm joining a thread, do other threads keep running in the background, or is the joined thread the only one that's running?</p>
|
[
{
"answer_id": 248431,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 1,
"selected": false,
"text": "<p>Read your code carefully. The two cases aren't doing the same thing, and it has nothing to do with threads.</p>\n\n<p>When you join a thread, other threads will run in the background, yes.</p>\n"
},
{
"answer_id": 248454,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>Running a test, the second one doesn't seem to take 9 seconds--in fact, it takes at least as long as the first (which is to be expected, threding can't help the way it's implemented in your example.</p>\n\n<p>Thread.join will only return when the thread.joined terminates, then the current thread will continue, the one you called join on will be dead.</p>\n\n<p>For a quick reference--think threading when starting one iteration does not depend on the result of the previous one. </p>\n"
},
{
"answer_id": 248482,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 2,
"selected": false,
"text": "<p>You can test this better by making the exact code in your first example run with threads. Sub your main method with this:</p>\n\n<pre><code> private static int currentPrime;\npublic static void main(String[] args) throws InterruptedException {\n for (currentPrime = 0; currentPrime < 10000; currentPrime++) {\n Thread t = new Thread(new Runnable() {\n public void run() {\n getNextPrime(currentPrime);\n }});\n t.run();\n t.join();\n }\n}\n</code></pre>\n\n<p>This will run in the same time as the original.</p>\n\n<p>To answer your \"join\" question: yes, other threads can be running in the background when you use \"join\", but in this particular case you will only have one active thread at a time, because you are blocking the creation of new threads until the last thread is done executing.</p>\n"
},
{
"answer_id": 248547,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "<p>JesperE is right, but I don't believe in only giving hints (at least outside a classroom):</p>\n\n<p>Note this loop in the non-threaded version:</p>\n\n<pre><code>for(int i = 2;i < nextPrime;i++) {\n if(nextPrime % i == 0) {\n prime = false;\n }\n}\n</code></pre>\n\n<p>As opposed to this in the threaded version:</p>\n\n<pre><code>for(int i = 2;i < from;i++) {\n if((number % i) == 0) {\n return false;\n }\n}\n</code></pre>\n\n<p>The first loop will always run completely through, while the second will exit early if it finds a divisor.</p>\n\n<p>You could make the first loop also exit early by adding a break statement like this:</p>\n\n<pre><code>for(int i = 2;i < nextPrime;i++) {\n if(nextPrime % i == 0) {\n prime = false;\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 249019,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 3,
"selected": true,
"text": "<p>By putting the join() in the loop, you're starting a thread, then waiting for that thread to stop before running the next one. I think you probably want something more like this:</p>\n\n<pre><code>public static void main(String[] args) {\n int primeStart = 5;\n\n // Make thread-safe list for adding results to\n List list = Collections.synchronizedList(new ArrayList());\n\n // Pull thread pool count out into a value so you can easily change it\n int threadCount = 10000;\n Thread[] threads = new Thread[threadCount];\n\n // Start all threads\n for(int i = 0;i < threadCount;i++) {\n // Pass list to each Runnable here\n // Also, I added +i here as I think the intention is \n // to test 10000 possible numbers>5 for primeness - \n // was testing 5 in all loops\n PrimeRunnable pr = new PrimeRunnable(primeStart+i, list);\n Thread[i] threads = new Thread(pr);\n threads[i].start(); // thread is now running in parallel\n }\n\n // All threads now running in parallel\n\n // Then wait for all threads to complete\n for(int i=0; i<threadCount; i++) {\n threads[i].join();\n }\n}\n</code></pre>\n\n<p>By the way pr.getLastPrime() will return 0 in the case of no prime, so you might want to filter that out before adding it to your list. The PrimeRunnable has to absorb the work of adding to the final results list. Also, I think PrimeRunnable was actually broken by still having incrementing code in it. I think this is fixed, but I'm not actually compiling this.</p>\n\n<pre><code>public class PrimeRunnable implements Runnable { \n private int from;\n private List results; // shared but thread-safe\n\n public PrimeRunnable(int from, List results) {\n this.from = from;\n this.results = results;\n }\n\n public void isPrime(int number) {\n for(int i = 2;i < from;i++) {\n if((number % i) == 0) {\n return;\n }\n }\n // found prime, add to shared results\n this.results.add(number);\n }\n\n public void run() {\n isPrime(from); // don't increment, just check one number\n } \n}\n</code></pre>\n\n<p>Running 10000 threads in parallel is not a good idea. It's a much better idea to create a reasonably sized fixed thread pool and have them pull work from a shared queue. Basically every worker pulls tasks from the same queue, works on them and saves the results somewhere. The closest port of this with Java 5+ is to use an ExecutorService backed by a thread pool. You could also use a CompletionService which combines an ExecutorService with a result queue. </p>\n\n<p>An ExecutorService version would look like:</p>\n\n<pre><code>public static void main(String[] args) {\n int primeStart = 5;\n\n // Make thread-safe list for adding results to\n List list = Collections.synchronizedList(new ArrayList());\n\n int threadCount = 16; // Experiment with this to find best on your machine\n ExecutorService exec = Executors.newFixedThreadPool(threadCount);\n\n int workCount = 10000; // See how # of work is now separate from # of threads?\n for(int i = 0;i < workCount;i++) {\n // submit work to the svc for execution across the thread pool \n exec.execute(new PrimeRunnable(primeStart+i, list));\n }\n\n // Wait for all tasks to be done or timeout to go off\n exec.awaitTermination(1, TimeUnit.DAYS);\n}\n</code></pre>\n\n<p>Hope that gave you some ideas. And I hope the last example seemed a lot better than the first.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.
```
//code without thread use
public static int getNextPrime(int from) {
int nextPrime = from+1;
boolean superPrime = false;
while(!superPrime) {
boolean prime = true;
for(int i = 2;i < nextPrime;i++) {
if(nextPrime % i == 0) {
prime = false;
}
}
if(prime) {
superPrime = true;
} else {
nextPrime++;
}
}
return nextPrime;
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
list.add(primeStart);
primeStart = getNextPrime(primeStart);
}
}
```
If I'm running the code like this and it takes about 56 seconds. If, however, I have the following code (as an alternative):
```
public class PrimeRunnable implements Runnable {
private int from;
private int lastPrime;
public PrimeRunnable(int from) {
this.from = from;
}
public boolean isPrime(int number) {
for(int i = 2;i < from;i++) {
if((number % i) == 0) {
return false;
}
}
lastPrime = number;
return true;
}
public int getLastPrime() {
return lastPrime;
}
public void run() {
while(!isPrime(++from))
;
}
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
PrimeRunnable pr = new PrimeRunnable(primeStart);
Thread t = new Thread(pr);
t.start();
t.join();
primeStart = pr.getLastPrime();
list.add(primeStart);
}
}
```
The whole operation takes about 7 seconds. I am almost certain that even though I only create one thread at a time, a thread doesn't always finish when another is created. Is that right? I am also curious: why is the operation ending so fast?
When I'm joining a thread, do other threads keep running in the background, or is the joined thread the only one that's running?
|
By putting the join() in the loop, you're starting a thread, then waiting for that thread to stop before running the next one. I think you probably want something more like this:
```
public static void main(String[] args) {
int primeStart = 5;
// Make thread-safe list for adding results to
List list = Collections.synchronizedList(new ArrayList());
// Pull thread pool count out into a value so you can easily change it
int threadCount = 10000;
Thread[] threads = new Thread[threadCount];
// Start all threads
for(int i = 0;i < threadCount;i++) {
// Pass list to each Runnable here
// Also, I added +i here as I think the intention is
// to test 10000 possible numbers>5 for primeness -
// was testing 5 in all loops
PrimeRunnable pr = new PrimeRunnable(primeStart+i, list);
Thread[i] threads = new Thread(pr);
threads[i].start(); // thread is now running in parallel
}
// All threads now running in parallel
// Then wait for all threads to complete
for(int i=0; i<threadCount; i++) {
threads[i].join();
}
}
```
By the way pr.getLastPrime() will return 0 in the case of no prime, so you might want to filter that out before adding it to your list. The PrimeRunnable has to absorb the work of adding to the final results list. Also, I think PrimeRunnable was actually broken by still having incrementing code in it. I think this is fixed, but I'm not actually compiling this.
```
public class PrimeRunnable implements Runnable {
private int from;
private List results; // shared but thread-safe
public PrimeRunnable(int from, List results) {
this.from = from;
this.results = results;
}
public void isPrime(int number) {
for(int i = 2;i < from;i++) {
if((number % i) == 0) {
return;
}
}
// found prime, add to shared results
this.results.add(number);
}
public void run() {
isPrime(from); // don't increment, just check one number
}
}
```
Running 10000 threads in parallel is not a good idea. It's a much better idea to create a reasonably sized fixed thread pool and have them pull work from a shared queue. Basically every worker pulls tasks from the same queue, works on them and saves the results somewhere. The closest port of this with Java 5+ is to use an ExecutorService backed by a thread pool. You could also use a CompletionService which combines an ExecutorService with a result queue.
An ExecutorService version would look like:
```
public static void main(String[] args) {
int primeStart = 5;
// Make thread-safe list for adding results to
List list = Collections.synchronizedList(new ArrayList());
int threadCount = 16; // Experiment with this to find best on your machine
ExecutorService exec = Executors.newFixedThreadPool(threadCount);
int workCount = 10000; // See how # of work is now separate from # of threads?
for(int i = 0;i < workCount;i++) {
// submit work to the svc for execution across the thread pool
exec.execute(new PrimeRunnable(primeStart+i, list));
}
// Wait for all tasks to be done or timeout to go off
exec.awaitTermination(1, TimeUnit.DAYS);
}
```
Hope that gave you some ideas. And I hope the last example seemed a lot better than the first.
|
248,437 |
<p>Is it possible in ASP.NET to take a string containing some HTML and make ASP.NET to parse it and create a Control for me? For example:</p>
<pre><code>string rawHTML = "<table><td><td>Cell</td></tr></table>";
HTMLTable table = MagicClass.ParseTable(rawHTML);
</code></pre>
<p>I know that this is a bad thing to do but I am in the unfortunate situation that this is really the only way I can achieve what I need (as I cannot modify this particular coworker's code).</p>
<p>Also, I know that LiteralControl allows you to have a control with arbitrary HTML in it, but unfortunately I need to have them converted to proper control.</p>
<p>Unfortunately, HTMLTable does not support the InnerHTML property. I need to preserve the HTML tree exactly as it is, so I cannot put it into a <code><div></code> tag.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 248462,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>You could traverse the HTML string a token at a time (token defined here as HTML Element or HTML InnerText), and determine which control needs to be instantiated, and what attributes it needs. But, that would be something highly... evil in the writing. </p>\n\n<p>Why exactly do you need it to be a \"proper\" control as opposed to a text inside of a Literal control?</p>\n"
},
{
"answer_id": 248542,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "<p>The closest I think you'll get is <a href=\"http://msdn.microsoft.com/en-us/library/kz3ffe28.aspx\" rel=\"noreferrer\">Page.ParseControl</a>, which is the ASP.NET parser. The downside is that the text you have <em>is</em> a LiteralControl, since it doesn't have runat=\"server\" on it - so you 'll do a very tiny bit of string manipulation beforehand.</p>\n\n<p>In otherwords:</p>\n\n<pre><code>this.ParseControl(\"<table><tr><td>Cell</td></tr></table>\")\n</code></pre>\n\n<p>will produce:</p>\n\n<pre><code>Control\n LiteralControl\n</code></pre>\n\n<p>whereas:</p>\n\n<pre><code>this.ParseControl(\"<table runat=\\\"server\\\"><tr><td>Cell</td></tr></table>\")\n</code></pre>\n\n<p>will produce:</p>\n\n<pre><code>Control\n HtmlTable\n HtmlTableRow\n HtmlTableCell\n LiteralControl\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954/"
] |
Is it possible in ASP.NET to take a string containing some HTML and make ASP.NET to parse it and create a Control for me? For example:
```
string rawHTML = "<table><td><td>Cell</td></tr></table>";
HTMLTable table = MagicClass.ParseTable(rawHTML);
```
I know that this is a bad thing to do but I am in the unfortunate situation that this is really the only way I can achieve what I need (as I cannot modify this particular coworker's code).
Also, I know that LiteralControl allows you to have a control with arbitrary HTML in it, but unfortunately I need to have them converted to proper control.
Unfortunately, HTMLTable does not support the InnerHTML property. I need to preserve the HTML tree exactly as it is, so I cannot put it into a `<div>` tag.
Thanks.
|
The closest I think you'll get is [Page.ParseControl](http://msdn.microsoft.com/en-us/library/kz3ffe28.aspx), which is the ASP.NET parser. The downside is that the text you have *is* a LiteralControl, since it doesn't have runat="server" on it - so you 'll do a very tiny bit of string manipulation beforehand.
In otherwords:
```
this.ParseControl("<table><tr><td>Cell</td></tr></table>")
```
will produce:
```
Control
LiteralControl
```
whereas:
```
this.ParseControl("<table runat=\"server\"><tr><td>Cell</td></tr></table>")
```
will produce:
```
Control
HtmlTable
HtmlTableRow
HtmlTableCell
LiteralControl
```
|
248,459 |
<p>We are deploying our ASP.NET 3.5 app to a production server for beta testing.</p>
<p>Each page is secured using SSL.</p>
<p>On our homepage (default.aspx) we have web services which populate flash objects.</p>
<p>I am getting an error:</p>
<p>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.</p>
<p>Also, when using firefox, receive the Windows Login pop up screen.</p>
<p>Does anyone have any clue what or why this is happening?</p>
<p>Much thanks!</p>
|
[
{
"answer_id": 248500,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like IIS isn't configured for <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/9ded7af2-fcb7-4ed2-b007-e19f971f6e13.mspx?mfr=true\" rel=\"nofollow noreferrer\">anonymous access</a>. </p>\n\n<p>If you believe you have it setup correctly (sounds like it isn't), then you might try troubleshooting your connection with <a href=\"http://support.microsoft.com/kb/284285\" rel=\"nofollow noreferrer\">Wfetch</a>. </p>\n"
},
{
"answer_id": 248936,
"author": "JTew",
"author_id": 25372,
"author_profile": "https://Stackoverflow.com/users/25372",
"pm_score": 1,
"selected": false,
"text": "<p>I would think that the request from Flash to the secure web services doesn't have credentials or that the secure certificate in the response can't be validated.</p>\n\n<p>Probably both.</p>\n\n<p>So in flash there will probably need to be some code like:</p>\n\n<pre><code>request.Username = \"xyz\"\nrequest.Password = \"***\"\n</code></pre>\n\n<p>or something similar </p>\n\n<p>In .net there is a way to manually override the validation of a certificate for the request. I'm not sure how you would do that in Flash.</p>\n\n<p>I'll update this if I find a sample for the .net way. </p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23576/"
] |
We are deploying our ASP.NET 3.5 app to a production server for beta testing.
Each page is secured using SSL.
On our homepage (default.aspx) we have web services which populate flash objects.
I am getting an error:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.
Also, when using firefox, receive the Windows Login pop up screen.
Does anyone have any clue what or why this is happening?
Much thanks!
|
I would think that the request from Flash to the secure web services doesn't have credentials or that the secure certificate in the response can't be validated.
Probably both.
So in flash there will probably need to be some code like:
```
request.Username = "xyz"
request.Password = "***"
```
or something similar
In .net there is a way to manually override the validation of a certificate for the request. I'm not sure how you would do that in Flash.
I'll update this if I find a sample for the .net way.
|
248,470 |
<p>I'm writing a script to remove some build artifacts older than 1 week. </p>
<p>The files have names in the form <em>artifact-1.1-200810391018.exe</em>.</p>
<p>How do I go about removing only the files that are greater than 1 week old, excluding the time in hours and minutes at the end of the date-time-stamp?</p>
<p>Currently it is removing all of the files in the directory.</p>
<pre><code>#!/bin/sh
NIGHTLY_LOCATIONS=( "/foo" "/bar" )
ARTIFACT_PREFIX="artifact-*-"
NUM_TO_KEEP=7
for home in $(seq 0 $((${#NIGHTLY_LOCATIONS[@]} - 1))); do
echo "Removing artifacts for" ${NIGHTLY_LOCATIONS[$location]}
for file in `find ${NIGHTLY_LOCATIONS[$location]} -name "$ARTIFACT_PREFIX*"`; do
keep=true
for day in $(seq 0 $((${NUM_TO_KEEP} - 1))); do
date=`date --date="$day days ago" +%Y%m%d`
echo $(basename $file ".exe") " = " $ARTIFACT_PREFIX$date
if [ "$(basename $file ".exe")" != "$ARTIFACT_PREFIX$date" ]; then
keep=false
fi
done
if [ !$keep ]; then
echo "Removing file"
rm -f $file
fi
done done
</code></pre>
|
[
{
"answer_id": 248485,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": true,
"text": "<p>You mean, something along the line of:</p>\n\n<pre><code>find /path/to/files -name \"artifact*\" -type f -mtime +7 -exec rm {} \\;\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 248490,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>If you trust the mtime of the file, you can do it in a simple sweep with find:</p>\n\n<pre><code>find \"${NIGHTLY_LOCATIONS}\" -name $ARTIFACT_PREFIX -type f -mtime +7 -delete\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18340/"
] |
I'm writing a script to remove some build artifacts older than 1 week.
The files have names in the form *artifact-1.1-200810391018.exe*.
How do I go about removing only the files that are greater than 1 week old, excluding the time in hours and minutes at the end of the date-time-stamp?
Currently it is removing all of the files in the directory.
```
#!/bin/sh
NIGHTLY_LOCATIONS=( "/foo" "/bar" )
ARTIFACT_PREFIX="artifact-*-"
NUM_TO_KEEP=7
for home in $(seq 0 $((${#NIGHTLY_LOCATIONS[@]} - 1))); do
echo "Removing artifacts for" ${NIGHTLY_LOCATIONS[$location]}
for file in `find ${NIGHTLY_LOCATIONS[$location]} -name "$ARTIFACT_PREFIX*"`; do
keep=true
for day in $(seq 0 $((${NUM_TO_KEEP} - 1))); do
date=`date --date="$day days ago" +%Y%m%d`
echo $(basename $file ".exe") " = " $ARTIFACT_PREFIX$date
if [ "$(basename $file ".exe")" != "$ARTIFACT_PREFIX$date" ]; then
keep=false
fi
done
if [ !$keep ]; then
echo "Removing file"
rm -f $file
fi
done done
```
|
You mean, something along the line of:
```
find /path/to/files -name "artifact*" -type f -mtime +7 -exec rm {} \;
```
?
|
248,478 |
<p>I am writing a custom session handler in PHP and trying to make the methods defined in session_set_save_handler private.</p>
<pre><code>session_set_save_handler(
array('Session','open'),
array('Session','close'),
array('Session','read'),
array('Session','write'),
array('Session','destroy'),
array('Session','gc')
);
</code></pre>
<p>For example I can set the open function to be private without any errors, but when I make the write method private it barks at me.</p>
<blockquote>
<p>Fatal error: Call to private method
Session::write() from context '' in
Unknown on line 0</p>
</blockquote>
<p>I was just wondering if this was a bug or there is a way around this. Barring that I can certainly just make it public, but I'd rather not. There was a post from last year on php.net eluding to a similar thing, but just want to know if anyone had any ideas. Does it really matter? I am using PHP 5.2.0 on my development box, but could certainly upgrade. </p>
|
[
{
"answer_id": 248648,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 3,
"selected": true,
"text": "<p>They have to be public. Your class is instantiated and called in exactly the manner you would in your own code.</p>\n\n<p>So, unless you can figure out how to publically call a private method on ANY class, then no =P</p>\n"
},
{
"answer_id": 1561578,
"author": "fentie",
"author_id": 189275,
"author_profile": "https://Stackoverflow.com/users/189275",
"pm_score": 0,
"selected": false,
"text": "<p>Pass an instantiated object as the first parameter of your callback array.</p>\n\n<pre><code>$session = new Session();\nsession_set_save_handler(\n array($session,'open'),\n array($session,'close'),\n array($session,'read'),\n array($session,'write'),\n array($session,'destroy'),\n array($session,'gc')\n);\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28714/"
] |
I am writing a custom session handler in PHP and trying to make the methods defined in session\_set\_save\_handler private.
```
session_set_save_handler(
array('Session','open'),
array('Session','close'),
array('Session','read'),
array('Session','write'),
array('Session','destroy'),
array('Session','gc')
);
```
For example I can set the open function to be private without any errors, but when I make the write method private it barks at me.
>
> Fatal error: Call to private method
> Session::write() from context '' in
> Unknown on line 0
>
>
>
I was just wondering if this was a bug or there is a way around this. Barring that I can certainly just make it public, but I'd rather not. There was a post from last year on php.net eluding to a similar thing, but just want to know if anyone had any ideas. Does it really matter? I am using PHP 5.2.0 on my development box, but could certainly upgrade.
|
They have to be public. Your class is instantiated and called in exactly the manner you would in your own code.
So, unless you can figure out how to publically call a private method on ANY class, then no =P
|
248,483 |
<p>I have defined a fieldset in HTML, and applied the following (simple) CSS rules to it:</p>
<pre><code>fieldset
{
margin: 2em 0;
position:relative;
padding: 1em;
border:1px solid #ccc;
}
</code></pre>
<p>Everything is great, no big deal, except in all versions (well, up to 7 as far as I know) of IE the top border -- but not, interestingly, the bottom border -- of the fieldset visually extends too far to the right by about 25px, beyond where the vertical border is on that side.</p>
<p>It is worth noting that this element's width causes it to be outside its parent element width-wise to the right, when viewed in Firebug for example.</p>
<p>What is causing this problem in IE? Is this a known issue, and, if so, what is the fix / hack / workaround?</p>
|
[
{
"answer_id": 248515,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 1,
"selected": false,
"text": "<p>Could you post more of your code, like the HTML of what's surrounding the fieldset and the corresponding CSS rules for that?</p>\n\n<p>You mentioned that you can see it's wider than its parent element in Firebug. That's almost certainly related. Can you change the CSS of the parent element to make it wide enough to contain the fieldset?</p>\n\n<p>Without a little more context, it's probably going to be tough to diagnose this more accurately...</p>\n"
},
{
"answer_id": 2414876,
"author": "wchrisjohnson",
"author_id": 14120,
"author_profile": "https://Stackoverflow.com/users/14120",
"pm_score": 3,
"selected": true,
"text": "<p>I've struggled with this one for some time; tonight I finally found the answer.</p>\n\n<p><a href=\"http://www.sitepoint.com/forums/showthread.php?t=526881\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/forums/showthread.php?t=526881</a></p>\n\n<p>To quote NatalieMac:</p>\n\n<blockquote>\n <p>Seems that if you have an element inside the fieldset that's overflowing\n to the right of the fieldset, it extends the top border. I had a\n container set to a width of 100% with no padding or margins which IE7\n thought was overflowing for some reason (even though the content inside\n this container was right-aligned and viewable within the border of the\n fieldset).</p>\n \n <p>I was able to fix it just by adding overflow:hidden to the fieldset.</p>\n</blockquote>\n\n<p>I can confirm that this does indeed fix the issue for me as well.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2323/"
] |
I have defined a fieldset in HTML, and applied the following (simple) CSS rules to it:
```
fieldset
{
margin: 2em 0;
position:relative;
padding: 1em;
border:1px solid #ccc;
}
```
Everything is great, no big deal, except in all versions (well, up to 7 as far as I know) of IE the top border -- but not, interestingly, the bottom border -- of the fieldset visually extends too far to the right by about 25px, beyond where the vertical border is on that side.
It is worth noting that this element's width causes it to be outside its parent element width-wise to the right, when viewed in Firebug for example.
What is causing this problem in IE? Is this a known issue, and, if so, what is the fix / hack / workaround?
|
I've struggled with this one for some time; tonight I finally found the answer.
<http://www.sitepoint.com/forums/showthread.php?t=526881>
To quote NatalieMac:
>
> Seems that if you have an element inside the fieldset that's overflowing
> to the right of the fieldset, it extends the top border. I had a
> container set to a width of 100% with no padding or margins which IE7
> thought was overflowing for some reason (even though the content inside
> this container was right-aligned and viewable within the border of the
> fieldset).
>
>
> I was able to fix it just by adding overflow:hidden to the fieldset.
>
>
>
I can confirm that this does indeed fix the issue for me as well.
|
248,501 |
<p>I am using MS SQL Server 2005, I have dates stored in epoch time (starting 1970) I need to create a statement that will affect any record that has not been updated in the last 24 hours.</p>
|
[
{
"answer_id": 248524,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 1,
"selected": false,
"text": "<p>You can convert from SQL Server DateTime to Epoch time by calculating the number of seconds that have elapsed since Jan 1, 1970, like this.</p>\n\n<p><code>Select DateDiff(Second, '19700101', GetDate())</code></p>\n\n<p>To get rows from the last 24 hours....</p>\n\n<pre><code>Select Columns\nFrom Table\nWhere EpochColumn Between DateDiff(Second, '19700101', GetDate()) And DateDiff(Second, '19700101, GetDate()-1)\n</code></pre>\n"
},
{
"answer_id": 248543,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 3,
"selected": true,
"text": "<p>To get the current datetime into epoch format, use (<a href=\"http://wiki.lessthandot.com/index.php/Epoch_Date\" rel=\"nofollow noreferrer\">via</a>):</p>\n\n<pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000',GETUTCDATE())\n</code></pre>\n\n<p>To get the epoch time for now - 24 hours use:</p>\n\n<pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))\n</code></pre>\n\n<p>So, you could do:</p>\n\n<pre><code>DECLARE @24_hours_ago AS INT\nSELECT @24_hours_ago = DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))\n\nUPDATE table SET col = value WHERE last_updated < @24_hours_ago\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32579/"
] |
I am using MS SQL Server 2005, I have dates stored in epoch time (starting 1970) I need to create a statement that will affect any record that has not been updated in the last 24 hours.
|
To get the current datetime into epoch format, use ([via](http://wiki.lessthandot.com/index.php/Epoch_Date)):
```
SELECT DATEDIFF(s,'19700101 05:00:00:000',GETUTCDATE())
```
To get the epoch time for now - 24 hours use:
```
SELECT DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))
```
So, you could do:
```
DECLARE @24_hours_ago AS INT
SELECT @24_hours_ago = DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))
UPDATE table SET col = value WHERE last_updated < @24_hours_ago
```
|
248,502 |
<p>I want to run a background task that reads input from a TextReader and processes it a line at a time. I want the background task to block until the user types some text into a field and clicks the submit button. Is there some flavour of TextReader that will block until text is available and lets you somehow add more text to the underlying source?</p>
<p>I thought that a StreamReader and StreamWriter pointing to the same MemoryStream might work, but it doesn't seem to. The StreamReader sees that the MemoryStream is empty at the start, and never checks again.</p>
<p>I realize that it would be easier to write a ProcessLine() method and call it whenever the user clicks the submit button. However, I'm trying to design a plug-in architecture, and I'd like the plug ins to look like old-fashioned console apps with an input stream and an output stream. I want the plug in's input stream to just block until the user clicks the submit button with some input text.</p>
|
[
{
"answer_id": 248561,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 3,
"selected": false,
"text": "<p>I think you'd be much better off creating an event in your main application that is raised when the user hits Submit. The text data would be passed in the event args. Each plugin registers an event handler for the event, and handles the data passed in when the event is raised. This allows many plugins to process the data from a single submission without a lot of plumbing work on your part, and means the plugins are able to just sit idle until the event is raised.</p>\n"
},
{
"answer_id": 248700,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": true,
"text": "<p>It seems that there is no implementation of this - which is strange, since I agree that it would be a useful construct. But it should be simple to write. Something like this should work:</p>\n\n<pre><code> public class BlockingStream: Stream\n {\n private readonly Stream _stream;\n\n public BlockingStream(Stream stream)\n {\n if(!stream.CanSeek)\n throw new ArgumentException(\"Stream must support seek\", \"stream\");\n _stream = stream;\n }\n\n public override void Flush()\n {\n lock (_stream)\n {\n _stream.Flush();\n Monitor.Pulse(_stream);\n }\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n lock (_stream)\n {\n long res = _stream.Seek(offset, origin);\n Monitor.Pulse(_stream);\n return res;\n }\n }\n\n public override void SetLength(long value)\n {\n lock (_stream)\n {\n _stream.SetLength(value);\n Monitor.Pulse(_stream);\n }\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n lock (_stream)\n {\n do\n {\n int read = _stream.Read(buffer, offset, count);\n if (read > 0)\n return read;\n Monitor.Wait(_stream);\n } while (true);\n }\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n lock (_stream)\n {\n long currentPosition = _stream.Position;\n _stream.Position = _stream.Length;\n _stream.Write(buffer, offset, count);\n _stream.Position = currentPosition;\n Monitor.Pulse(_stream);\n }\n }\n\n public override bool CanRead\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanRead;\n }\n }\n }\n\n public override bool CanSeek\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanSeek;\n }\n }\n }\n\n public override bool CanWrite\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanWrite;\n }\n }\n }\n\n public override long Length\n {\n get\n {\n lock (_stream)\n {\n return _stream.Length;\n }\n }\n }\n\n public override long Position\n {\n get\n {\n lock (_stream)\n {\n return _stream.Position;\n }\n }\n set\n {\n lock (_stream)\n {\n _stream.Position = value;\n Monitor.Pulse(_stream);\n }\n }\n }\n }\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4794/"
] |
I want to run a background task that reads input from a TextReader and processes it a line at a time. I want the background task to block until the user types some text into a field and clicks the submit button. Is there some flavour of TextReader that will block until text is available and lets you somehow add more text to the underlying source?
I thought that a StreamReader and StreamWriter pointing to the same MemoryStream might work, but it doesn't seem to. The StreamReader sees that the MemoryStream is empty at the start, and never checks again.
I realize that it would be easier to write a ProcessLine() method and call it whenever the user clicks the submit button. However, I'm trying to design a plug-in architecture, and I'd like the plug ins to look like old-fashioned console apps with an input stream and an output stream. I want the plug in's input stream to just block until the user clicks the submit button with some input text.
|
It seems that there is no implementation of this - which is strange, since I agree that it would be a useful construct. But it should be simple to write. Something like this should work:
```
public class BlockingStream: Stream
{
private readonly Stream _stream;
public BlockingStream(Stream stream)
{
if(!stream.CanSeek)
throw new ArgumentException("Stream must support seek", "stream");
_stream = stream;
}
public override void Flush()
{
lock (_stream)
{
_stream.Flush();
Monitor.Pulse(_stream);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
{
long res = _stream.Seek(offset, origin);
Monitor.Pulse(_stream);
return res;
}
}
public override void SetLength(long value)
{
lock (_stream)
{
_stream.SetLength(value);
Monitor.Pulse(_stream);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
lock (_stream)
{
do
{
int read = _stream.Read(buffer, offset, count);
if (read > 0)
return read;
Monitor.Wait(_stream);
} while (true);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
lock (_stream)
{
long currentPosition = _stream.Position;
_stream.Position = _stream.Length;
_stream.Write(buffer, offset, count);
_stream.Position = currentPosition;
Monitor.Pulse(_stream);
}
}
public override bool CanRead
{
get
{
lock (_stream)
{
return _stream.CanRead;
}
}
}
public override bool CanSeek
{
get
{
lock (_stream)
{
return _stream.CanSeek;
}
}
}
public override bool CanWrite
{
get
{
lock (_stream)
{
return _stream.CanWrite;
}
}
}
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
Monitor.Pulse(_stream);
}
}
}
}
```
|
248,534 |
<p><strong>Question</strong></p>
<p>I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new <em>firefox</em> window. However, <em>firefox</em> never opens. It always has a shell exit code of 1. I can run this same code with <em>gnome-terminal</em> and it opens fine.</p>
<p><strong>Background</strong></p>
<p>So, here is its initialization process:</p>
<ol>
<li>Start X "Xorg :1 -br -terminate -dpms -quiet vt7"</li>
<li>Start Window Manager "metacity --display=:1 --replace"</li>
<li>Configure resources "xrdb -merge /etc/X11/Xresources"</li>
<li>Become a daemon and disconnect from controlling terminal</li>
</ol>
<p>Once the program is up an running, there is a button the user can click that should spawn a firefox window. Here is my code to do that. Remember X is running on display :1.</p>
<p><strong>Code</strong></p>
<pre><code>
public boolean openBrowser()
{
try {
Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" );
int bExit = oProc.waitFor(); // This is always 1 for some reason
return true;
} catch ( Exception e ) {
oLogger.log( Level.WARNING, "Open Browser", e );
return false;
}
}
</code></pre>
|
[
{
"answer_id": 248552,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 3,
"selected": false,
"text": "<p>If you can narrow it down to Java 6, you can use the desktop API:</p>\n\n<p><a href=\"http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/\" rel=\"noreferrer\">http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/</a></p>\n\n<p>Should look something like:</p>\n\n<pre><code> if (Desktop.isDesktopSupported()) {\n Desktop desktop = Desktop.getDesktop();\n if (desktop.isSupported(Desktop.Action.BROWSE)) {\n try {\n desktop.browse(new URI(\"http://localhost\"));\n }\n catch(IOException ioe) {\n ioe.printStackTrace();\n }\n catch(URISyntaxException use) {\n use.printStackTrace();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 248602,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>You might have better luck if you read and display the standard output/error streams, so you can catch any error message firefox may print.</p>\n"
},
{
"answer_id": 248607,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://browserlaunch2.sourceforge.net/\" rel=\"nofollow noreferrer\">BrowserLauncher</a>.</p>\n\n<p>Invoking it is very easy, just go</p>\n\n<pre><code>new BrowserLauncher().openURLinBrowser(\"http://www.google.com\");\n</code></pre>\n"
},
{
"answer_id": 249168,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 3,
"selected": true,
"text": "<p>after having read the various answers and various comments(from questioner), here's what I would do</p>\n\n<p>1) try this java approach\n<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html</a></p>\n\n<pre><code>ProcessBuilder pb = new ProcessBuilder(\"myCommand\", \"myArg1\", \"myArg2\");\nMap<String, String> env = pb.environment();\nenv.put(\"VAR1\", \"myValue\");\nenv.remove(\"OTHERVAR\");\nenv.put(\"VAR2\", env.get(\"VAR1\") + \"suffix\");\npb.directory(\"myDir\");\nProcess p = pb.start();\n</code></pre>\n\n<p>see more about this class:</p>\n\n<p><a href=\"http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2\" rel=\"nofollow noreferrer\">http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2</a> <br>\n<a href=\"http://www.javabeat.net/tips/8-using-the-new-process-builder-class.html\" rel=\"nofollow noreferrer\">http://www.javabeat.net/tips/8-using-the-new-process-builder-class.html</a><br></p>\n\n<p>2) try doing this(launching firefox) from C/C++/ruby/python and see if that is succeeding. </p>\n\n<p>3) if all else fails, I would launch a shell program and that shell program would launch firefox!!</p>\n"
},
{
"answer_id": 9247555,
"author": "kta",
"author_id": 539023,
"author_profile": "https://Stackoverflow.com/users/539023",
"pm_score": 0,
"selected": false,
"text": "<pre><code>try {\n String url = \"http://www.google.com\";\n java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));\n} catch (java.io.IOException e) {\n System.out.println(e.getMessage());\n}\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29773/"
] |
**Question**
I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new *firefox* window. However, *firefox* never opens. It always has a shell exit code of 1. I can run this same code with *gnome-terminal* and it opens fine.
**Background**
So, here is its initialization process:
1. Start X "Xorg :1 -br -terminate -dpms -quiet vt7"
2. Start Window Manager "metacity --display=:1 --replace"
3. Configure resources "xrdb -merge /etc/X11/Xresources"
4. Become a daemon and disconnect from controlling terminal
Once the program is up an running, there is a button the user can click that should spawn a firefox window. Here is my code to do that. Remember X is running on display :1.
**Code**
```
public boolean openBrowser()
{
try {
Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" );
int bExit = oProc.waitFor(); // This is always 1 for some reason
return true;
} catch ( Exception e ) {
oLogger.log( Level.WARNING, "Open Browser", e );
return false;
}
}
```
|
after having read the various answers and various comments(from questioner), here's what I would do
1) try this java approach
<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html>
```
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();
```
see more about this class:
<http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2>
<http://www.javabeat.net/tips/8-using-the-new-process-builder-class.html>
2) try doing this(launching firefox) from C/C++/ruby/python and see if that is succeeding.
3) if all else fails, I would launch a shell program and that shell program would launch firefox!!
|
248,535 |
<p>How can you find out the number of active users when you're using a StateServer? Also is it possible to query the StateServer and retrieve the contents in the Session State? </p>
<p>I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.</p>
|
[
{
"answer_id": 248674,
"author": "Doug Wilson",
"author_id": 32588,
"author_profile": "https://Stackoverflow.com/users/32588",
"pm_score": 1,
"selected": true,
"text": "<p>Tracking the number of users would need to be done at the application level, not the session level.</p>\n\n<p>You should be able to see what is currently in the session with the following:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nforeach ( String key in Session.Contents ) {\n builder.AppendFormat(\"{0}: {1}<br />\", key, Session[key]);\n}\nResponse.Write(builder.ToString());\n</code></pre>\n"
},
{
"answer_id": 2105287,
"author": "Tormod Hystad",
"author_id": 73960,
"author_profile": "https://Stackoverflow.com/users/73960",
"pm_score": 3,
"selected": false,
"text": "<p>The number of active <em>sessions</em> in the State Server can be viewed with a Performance Counter on the server running the State Server easily. This does not directly equate to active users (due to session timeout time)</p>\n\n<p>The counter for active sessions is: \"Asp.net\" - \"State Server Sessions Active\"</p>\n\n<p>For reference, here are all State Server related perfmon counters, from <a href=\"http://msdn.microsoft.com/en-us/library/fxk122b4.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/fxk122b4.aspx</a></p>\n\n<p><strong>State Server Sessions Abandoned</strong>\nThe number of user sessions that have been explicitly abandoned. These are sessions that are ended by specific user actions, such as closing the browser or navigating to another site. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>\n\n<p><strong>State Server Sessions Active</strong>\nThe number of currently active user sessions. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>\n\n<p><strong>State Server Sessions Timed Out</strong>\nThe number of user sessions that have become inactive through user inaction. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>\n\n<p><strong>State Server Sessions Total</strong>\nThe number of sessions created during the lifetime of the process. This counter is the total value of State Server Sessions Active, State Server Sessions Abandoned, and State Server Sessions Timed Out. This counter is available only on the computer where the state server service (aspnet_state) is running.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] |
How can you find out the number of active users when you're using a StateServer? Also is it possible to query the StateServer and retrieve the contents in the Session State?
I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.
|
Tracking the number of users would need to be done at the application level, not the session level.
You should be able to see what is currently in the session with the following:
```
StringBuilder builder = new StringBuilder();
foreach ( String key in Session.Contents ) {
builder.AppendFormat("{0}: {1}<br />", key, Session[key]);
}
Response.Write(builder.ToString());
```
|
248,545 |
<p>I have a listbox, and I have the following ItemTemplate for it:</p>
<pre><code><DataTemplate x:Key="ScenarioItemTemplate">
<Border Margin="5,0,5,0"
Background="#FF3C3B3B"
BorderBrush="#FF797878"
BorderThickness="2"
CornerRadius="5">
<DockPanel>
<DockPanel DockPanel.Dock="Top"
Margin="0,2,0,0">
<Button HorizontalAlignment="Left"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="White" />
<Label Content="{Binding Path=Name}"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="white" />
<Label HorizontalAlignment="Right"
Background="#FF3C3B3B"
Content="X"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="White" />
</DockPanel>
<ContentControl Name="designerContent"
Visibility="Collapsed"
MinHeight="100"
Margin="2,0,2,2"
Content="{Binding Path=DesignerInstance}"
Background="#FF999898">
</ContentControl>
</DockPanel>
</Border>
</DataTemplate>
</code></pre>
<p>As you can see the ContentControl has Visibility set to collapsed.</p>
<p>I need to define a trigger that causes the Visibility to be set to "Visible"</p>
<p>when the ListItem is selected, but I can't figure it out.</p>
<p>Any ideas? </p>
<p>UPDATE: Of course I could simply duplicate the DataTemplate and add triggers
to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.</p>
|
[
{
"answer_id": 248581,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": true,
"text": "<p>You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected:</p>\n\n<pre><code><ContentControl \n x:Name=\"designerContent\"\n MinHeight=\"100\"\n Margin=\"2,0,2,2\"\n Content=\"{Binding Path=DesignerInstance}\"\n Background=\"#FF999898\">\n <ContentControl.Style>\n <Style TargetType=\"{x:Type ContentControl}\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n <Style.Triggers>\n <DataTrigger\n Binding=\"{Binding\n RelativeSource={RelativeSource\n Mode=FindAncestor,\n AncestorType={x:Type ListBoxItem}},\n Path=IsSelected}\"\n Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </ContentControl.Style>\n</ContentControl>\n</code></pre>\n\n<p>Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this:</p>\n\n<pre><code><DataTemplate x:Key=\"ScenarioItemTemplate\">\n <DataTemplate.Triggers>\n <DataTrigger\n Binding=\"{Binding\n RelativeSource={RelativeSource\n Mode=FindAncestor,\n AncestorType={x:Type ListBoxItem}},\n Path=IsSelected}\"\n Value=\"True\">\n <Setter\n TargetName=\"designerContent\"\n Property=\"Visibility\"\n Value=\"Visible\"/>\n </DataTrigger>\n </DataTemplate.Triggers>\n\n ...\n</DataTemplate>\n</code></pre>\n"
},
{
"answer_id": 248628,
"author": "TimothyP",
"author_id": 28149,
"author_profile": "https://Stackoverflow.com/users/28149",
"pm_score": 2,
"selected": false,
"text": "<p>@Matt, Thank you!!!</p>\n\n<p>Just had to add a trigger for IsSelected == false as well,\nand now it works like a charm!</p>\n\n<pre><code><ContentControl.Style>\n<Style TargetType=\"{x:Type ContentControl}\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}\" Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\"/>\n </DataTrigger>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}\" Value=\"False\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n </DataTrigger>\n </Style.Triggers>\n</Style>\n</code></pre>\n\n<p></p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
I have a listbox, and I have the following ItemTemplate for it:
```
<DataTemplate x:Key="ScenarioItemTemplate">
<Border Margin="5,0,5,0"
Background="#FF3C3B3B"
BorderBrush="#FF797878"
BorderThickness="2"
CornerRadius="5">
<DockPanel>
<DockPanel DockPanel.Dock="Top"
Margin="0,2,0,0">
<Button HorizontalAlignment="Left"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="White" />
<Label Content="{Binding Path=Name}"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="white" />
<Label HorizontalAlignment="Right"
Background="#FF3C3B3B"
Content="X"
DockPanel.Dock="Left"
FontWeight="Heavy"
Foreground="White" />
</DockPanel>
<ContentControl Name="designerContent"
Visibility="Collapsed"
MinHeight="100"
Margin="2,0,2,2"
Content="{Binding Path=DesignerInstance}"
Background="#FF999898">
</ContentControl>
</DockPanel>
</Border>
</DataTemplate>
```
As you can see the ContentControl has Visibility set to collapsed.
I need to define a trigger that causes the Visibility to be set to "Visible"
when the ListItem is selected, but I can't figure it out.
Any ideas?
UPDATE: Of course I could simply duplicate the DataTemplate and add triggers
to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.
|
You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected:
```
<ContentControl
x:Name="designerContent"
MinHeight="100"
Margin="2,0,2,2"
Content="{Binding Path=DesignerInstance}"
Background="#FF999898">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger
Binding="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
```
Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this:
```
<DataTemplate x:Key="ScenarioItemTemplate">
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Value="True">
<Setter
TargetName="designerContent"
Property="Visibility"
Value="Visible"/>
</DataTrigger>
</DataTemplate.Triggers>
...
</DataTemplate>
```
|
248,557 |
<pre><code>// goal: update Address record identified by "id", with new data in "colVal"
string cstr = ConnectionApi.GetSqlConnectionString("SwDb"); // get connection str
using (DataContext db = new DataContext(cstr)) {
Address addr = (from a in db.GetTable<Address>()
where a.Id == id
select a).Single<Address>();
addr.AddressLine1 = colValue.Trim();
db.SubmitChanges(); // this seems to have no effect!!!
}
</code></pre>
<p>In the debugger, addr has all the current values from the db table, and I can verify that AddressLine1 is changed just before I call db.SubmitChanges()... SQL Profiler shows only a "reset connection" when the SubmitChanges line executes. Anyone got a clue why this isn't working? THANKS!</p>
|
[
{
"answer_id": 248586,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 3,
"selected": false,
"text": "<p>You can get a quick view of the changes to be submitted using the <a href=\"http://msdn.microsoft.com/en-us/library/bb882650.aspx\" rel=\"nofollow noreferrer\">GetChangeSet</a> method. </p>\n\n<p>Also make sure that your table has a primary key defined and that the mapping knows about this primary key. Otherwise you won't be able to perform updates.</p>\n"
},
{
"answer_id": 248591,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>Funny, to use GetTable and Single. I would have expected the code to look like this:</p>\n\n<pre><code>string cstr = ConnectionApi.GetSqlConnectionString(\"SwDb\"); // get connection str\nusing (DataContext db = new DataContext(cstr)) \n{ \n Address addr = (from a in db.Address where a.Id == id select a).Single(); \n addr.AddressLine1 = colValue.Trim(); \n db.SubmitChanges(); // this seems to have no effect!!!\n}\n</code></pre>\n\n<p>I got no idea what GetTable will do to you.</p>\n\n<p>Another thing, for debugging Linq2SQL try adding</p>\n\n<pre><code>db.Log = Console.Out;\n</code></pre>\n\n<p>before SubmitChanges(), this will show you the executed SQL.</p>\n"
},
{
"answer_id": 250321,
"author": "Steve L",
"author_id": 32584,
"author_profile": "https://Stackoverflow.com/users/32584",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks -- your comments will help me sort this out I'm sure! I didn't have the \"Id\" column defined as the PrimaryKey so that's an obvious non-starter. I would have expected that LinqToSQL would have thrown an error when the update fails. -- S.</p>\n"
},
{
"answer_id": 250822,
"author": "Steve L",
"author_id": 32584,
"author_profile": "https://Stackoverflow.com/users/32584",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, here's the result. I can't use the form db.Address, because I didn't use the designer to create my database objects, instead I defined them as classes like this:</p>\n\n<pre><code>[Table(Name = \"Addresses\")]\npublic class Address\n{\n [Column(Name = \"Id\",IsPrimaryKey=true)]\n public int Id { get; set; }\n [Column(Name = \"AddressLine1\")]\n public string AddressLine1 { get; set; }\n ...\n</code></pre>\n\n<p>Originally, I didn't have the \"Id\" column set as PK in the database, nor did I have it identified using IsPrimaryKey=true in the [Column...] specifier above. BOTH are required! Once I made that change, the ChangeSet found the update I wanted to do, and did it, but before that it told me that 0 rows needed to be updated and refused to commit the changes. </p>\n\n<p>Thanks for your help! -- S.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32584/"
] |
```
// goal: update Address record identified by "id", with new data in "colVal"
string cstr = ConnectionApi.GetSqlConnectionString("SwDb"); // get connection str
using (DataContext db = new DataContext(cstr)) {
Address addr = (from a in db.GetTable<Address>()
where a.Id == id
select a).Single<Address>();
addr.AddressLine1 = colValue.Trim();
db.SubmitChanges(); // this seems to have no effect!!!
}
```
In the debugger, addr has all the current values from the db table, and I can verify that AddressLine1 is changed just before I call db.SubmitChanges()... SQL Profiler shows only a "reset connection" when the SubmitChanges line executes. Anyone got a clue why this isn't working? THANKS!
|
You can get a quick view of the changes to be submitted using the [GetChangeSet](http://msdn.microsoft.com/en-us/library/bb882650.aspx) method.
Also make sure that your table has a primary key defined and that the mapping knows about this primary key. Otherwise you won't be able to perform updates.
|
248,562 |
<p>I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way? </p>
<p>I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead? </p>
<pre><code> @RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
</code></pre>
|
[
{
"answer_id": 252096,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 2,
"selected": false,
"text": "<p>For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.</p>\n\n<p>At least then it's only in once place if you need to later refactor.</p>\n"
},
{
"answer_id": 253395,
"author": "Pavel Rodionov",
"author_id": 29487,
"author_profile": "https://Stackoverflow.com/users/29487",
"pm_score": 2,
"selected": false,
"text": "<p>You could use Spring AOP aproach.\nFor example if you have some service, that needs to know current principal. You could introduce custom annotation i.e. @Principal , which indicate that this Service should be principal dependent.</p>\n\n<pre><code>public class SomeService {\n private String principal;\n @Principal\n public setPrincipal(String principal){\n this.principal=principal;\n }\n}\n</code></pre>\n\n<p>Then in your advice, which I think needs to extend MethodBeforeAdvice, check that particular service has @Principal annotation and inject Principal name, or set it to 'ANONYMOUS' instead.</p>\n"
},
{
"answer_id": 327318,
"author": "cliff.meyers",
"author_id": 41754,
"author_profile": "https://Stackoverflow.com/users/41754",
"pm_score": 2,
"selected": false,
"text": "<p>The only problem is that even after authenticating with Spring Security, the user/principal bean doesn't exist in the container, so dependency-injecting it will be difficult. Before we used Spring Security we would create a session-scoped bean that had the current Principal, inject that into an \"AuthService\" and then inject that Service into most of the other services in the Application. So those Services would simply call authService.getCurrentUser() to get the object. If you have a place in your code where you get a reference to the same Principal in the session, you can simply set it as a property on your session-scoped bean.</p>\n"
},
{
"answer_id": 480503,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 5,
"selected": false,
"text": "<p>I agree that having to query the SecurityContext for the current user stinks, it seems a very un-Spring way to handle this problem.</p>\n\n<p>I wrote a static \"helper\" class to deal with this problem; it's dirty in that it's a global and static method, but I figured this way if we change anything related to Security, at least I only have to change the details in one place:</p>\n\n<pre><code>/**\n* Returns the domain User object for the currently logged in user, or null\n* if no User is logged in.\n* \n* @return User object for the currently logged in user, or null if no User\n* is logged in.\n*/\npublic static User getCurrentUser() {\n\n Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal()\n\n if (principal instanceof MyUserDetails) return ((MyUserDetails) principal).getUser();\n\n // principal object is either null or represents anonymous user -\n // neither of which our domain User object can represent - so return null\n return null;\n}\n\n\n/**\n * Utility method to determine if the current user is logged in /\n * authenticated.\n * <p>\n * Equivalent of calling:\n * <p>\n * <code>getCurrentUser() != null</code>\n * \n * @return if user is logged in\n */\npublic static boolean isLoggedIn() {\n return getCurrentUser() != null;\n}\n</code></pre>\n"
},
{
"answer_id": 885168,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 6,
"selected": false,
"text": "<p>A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.</p>\n\n<hr/>\n\n<p>This is the solution I've ended up going with. Instead of using <code>SecurityContextHolder</code> in my controller, I want to inject something which uses <code>SecurityContextHolder</code> under the hood but abstracts away that singleton-like class from my code. I've found no way to do this other than rolling my own interface, like so:</p>\n\n<pre><code>public interface SecurityContextFacade {\n\n SecurityContext getContext();\n\n void setContext(SecurityContext securityContext);\n\n}\n</code></pre>\n\n<p>Now, my controller (or whatever POJO) would look like this:</p>\n\n<pre><code>public class FooController {\n\n private final SecurityContextFacade securityContextFacade;\n\n public FooController(SecurityContextFacade securityContextFacade) {\n this.securityContextFacade = securityContextFacade;\n }\n\n public void doSomething(){\n SecurityContext context = securityContextFacade.getContext();\n // do something w/ context\n }\n\n}\n</code></pre>\n\n<p>And, because of the interface being a point of decoupling, unit testing is straightforward. In this example I use Mockito:</p>\n\n<pre><code>public class FooControllerTest {\n\n private FooController controller;\n private SecurityContextFacade mockSecurityContextFacade;\n private SecurityContext mockSecurityContext;\n\n @Before\n public void setUp() throws Exception {\n mockSecurityContextFacade = mock(SecurityContextFacade.class);\n mockSecurityContext = mock(SecurityContext.class);\n stub(mockSecurityContextFacade.getContext()).toReturn(mockSecurityContext);\n controller = new FooController(mockSecurityContextFacade);\n }\n\n @Test\n public void testDoSomething() {\n controller.doSomething();\n verify(mockSecurityContextFacade).getContext();\n }\n\n}\n</code></pre>\n\n<p>The default implementation of the interface looks like this:</p>\n\n<pre><code>public class SecurityContextHolderFacade implements SecurityContextFacade {\n\n public SecurityContext getContext() {\n return SecurityContextHolder.getContext();\n }\n\n public void setContext(SecurityContext securityContext) {\n SecurityContextHolder.setContext(securityContext);\n }\n\n}\n</code></pre>\n\n<p>And, finally, the production Spring config looks like this:</p>\n\n<pre><code><bean id=\"myController\" class=\"com.foo.FooController\">\n ...\n <constructor-arg index=\"1\">\n <bean class=\"com.foo.SecurityContextHolderFacade\">\n </constructor-arg>\n</bean>\n</code></pre>\n\n<p>It seems more than a little silly that Spring, a dependency injection container of all things, has not supplied a way to inject something similar. I understand <code>SecurityContextHolder</code> was inherited from acegi, but still. The thing is, they're so close - if only <code>SecurityContextHolder</code> had a getter to get the underlying <code>SecurityContextHolderStrategy</code> instance (which is an interface), you could inject that. In fact, I even <a href=\"http://jira.springsource.org/browse/SEC-1188\" rel=\"noreferrer\">opened a Jira issue</a> to that effect.</p>\n\n<p>One last thing - I've just substantially changed the answer I had here before. Check the history if you're curious but, as a coworker pointed out to me, my previous answer would not work in a multi-threaded environment. The underlying <code>SecurityContextHolderStrategy</code> used by <code>SecurityContextHolder</code> is, by default, an instance of <code>ThreadLocalSecurityContextHolderStrategy</code>, which stores <code>SecurityContext</code>s in a <code>ThreadLocal</code>. Therefore, it is not necessarily a good idea to inject the <code>SecurityContext</code> directly into a bean at initialization time - it may need to be retrieved from the <code>ThreadLocal</code> each time, in a multi-threaded environment, so the correct one is retrieved.</p>\n"
},
{
"answer_id": 2199815,
"author": "Michael Bushe",
"author_id": 256312,
"author_profile": "https://Stackoverflow.com/users/256312",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, statics are generally bad - generally, but in this case, the static is the most secure code you can write. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection in the signed code would be overridable with external XML. Such XML could inject the running system with a rogue principal. This is probably why Spring is doing something so un-Spring-like in this case.</p>\n"
},
{
"answer_id": 2563189,
"author": "Dan",
"author_id": 307215,
"author_profile": "https://Stackoverflow.com/users/307215",
"pm_score": 3,
"selected": false,
"text": "<p>I would just do this:</p>\n\n<pre><code>request.getRemoteUser();\n</code></pre>\n"
},
{
"answer_id": 3200513,
"author": "digz6666",
"author_id": 386213,
"author_profile": "https://Stackoverflow.com/users/386213",
"pm_score": 4,
"selected": false,
"text": "<p>I get authenticated user by\nHttpServletRequest.getUserPrincipal();</p>\n\n<p>Example:</p>\n\n<pre><code>import javax.servlet.http.HttpServletRequest;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.support.RequestContext;\n\nimport foo.Form;\n\n@Controller\n@RequestMapping(value=\"/welcome\")\npublic class IndexController {\n\n @RequestMapping(method=RequestMethod.GET)\n public String getCreateForm(Model model, HttpServletRequest request) {\n\n if(request.getUserPrincipal() != null) {\n String loginName = request.getUserPrincipal().getName();\n System.out.println(\"loginName : \" + loginName );\n }\n\n model.addAttribute(\"form\", new Form());\n return \"welcome\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5351828,
"author": "tsunade21",
"author_id": 598327,
"author_profile": "https://Stackoverflow.com/users/598327",
"pm_score": 9,
"selected": true,
"text": "<p>If you are using <a href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments\" rel=\"noreferrer\">Spring 3</a>, the easiest way is:</p>\n\n<pre><code> @RequestMapping(method = RequestMethod.GET) \n public ModelAndView showResults(final HttpServletRequest request, Principal principal) {\n\n final String currentUser = principal.getName();\n\n }\n</code></pre>\n"
},
{
"answer_id": 8179949,
"author": "Tito",
"author_id": 441902,
"author_profile": "https://Stackoverflow.com/users/441902",
"pm_score": 1,
"selected": false,
"text": "<p>Try this</p>\n\n<blockquote>\n <p>Authentication authentication =\n SecurityContextHolder.getContext().getAuthentication();<br>\n String userName = authentication.getName();</p>\n</blockquote>\n"
},
{
"answer_id": 8441306,
"author": "Mark",
"author_id": 656962,
"author_profile": "https://Stackoverflow.com/users/656962",
"pm_score": 2,
"selected": false,
"text": "<p>The best solution if you are using Spring 3 and need the authenticated principal in your controller is to do something like this:</p>\n\n<pre><code>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.userdetails.User;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\n\n @Controller\n public class KnoteController {\n @RequestMapping(method = RequestMethod.GET)\n public java.lang.String list(Model uiModel, UsernamePasswordAuthenticationToken authToken) {\n\n if (authToken instanceof UsernamePasswordAuthenticationToken) {\n user = (User) authToken.getPrincipal();\n }\n ...\n\n }\n</code></pre>\n"
},
{
"answer_id": 9763427,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 5,
"selected": false,
"text": "<p>To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:</p>\n\n<p><a href=\"http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html\">http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html</a></p>\n\n<p>To use any of the tags, you must have the security taglib declared in your JSP:</p>\n\n<pre class=\"lang-jsp prettyprint-override\"><code><%@ taglib prefix=\"security\" uri=\"http://www.springframework.org/security/tags\" %>\n</code></pre>\n\n<p>Then in a jsp page do something like this:</p>\n\n<pre class=\"lang-jsp prettyprint-override\"><code><security:authorize access=\"isAuthenticated()\">\n logged in as <security:authentication property=\"principal.username\" /> \n</security:authorize>\n\n<security:authorize access=\"! isAuthenticated()\">\n not logged in\n</security:authorize>\n</code></pre>\n\n<p>NOTE: As mentioned in the comments by @SBerg413, you'll need to add </p>\n\n<blockquote>\n <p>use-expressions=\"true\"</p>\n</blockquote>\n\n<p>to the \"http\" tag in the security.xml config for this to work.</p>\n"
},
{
"answer_id": 17381820,
"author": "Valknut",
"author_id": 2000539,
"author_profile": "https://Stackoverflow.com/users/2000539",
"pm_score": -1,
"selected": false,
"text": "<p>I like to share my way of supporting user details on freemarker page.\nEverything is very simple and working perfectly!</p>\n\n<p>You just have to place Authentication rerequest on <code>default-target-url</code> (page after form-login)\nThis is my Controler method for that page:</p>\n\n<pre><code>@RequestMapping(value = \"/monitoring\", method = RequestMethod.GET)\npublic ModelAndView getMonitoringPage(Model model, final HttpServletRequest request) {\n showRequestLog(\"monitoring\");\n\n\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String userName = authentication.getName();\n //create a new session\n HttpSession session = request.getSession(true);\n session.setAttribute(\"username\", userName);\n\n return new ModelAndView(catalogPath + \"monitoring\");\n}\n</code></pre>\n\n<p>And this is my ftl code:</p>\n\n<pre><code><@security.authorize ifAnyGranted=\"ROLE_ADMIN, ROLE_USER\">\n<p style=\"padding-right: 20px;\">Logged in as ${username!\"Anonymous\" }</p>\n</@security.authorize> \n</code></pre>\n\n<p>And that's it, username will appear on every page after authorisation.</p>\n"
},
{
"answer_id": 22823381,
"author": "Farm",
"author_id": 286588,
"author_profile": "https://Stackoverflow.com/users/286588",
"pm_score": 3,
"selected": false,
"text": "<p>In Spring 3+ you have have following options.</p>\n\n<p>Option 1 : </p>\n\n<pre><code>@RequestMapping(method = RequestMethod.GET) \npublic String currentUserNameByPrincipal(Principal principal) {\n return principal.getName();\n}\n</code></pre>\n\n<p>Option 2 : </p>\n\n<pre><code>@RequestMapping(method = RequestMethod.GET)\npublic String currentUserNameByAuthentication(Authentication authentication) {\n return authentication.getName();\n}\n</code></pre>\n\n<p>Option 3:</p>\n\n<pre><code>@RequestMapping(method = RequestMethod.GET) \npublic String currentUserByHTTPRequest(HttpServletRequest request) {\n return request.getUserPrincipal().getName();\n\n}\n</code></pre>\n\n<p>Option 4 : Fancy one : <a href=\"https://stackoverflow.com/a/8769670/286588\">Check this out for more details</a></p>\n\n<pre><code>public ModelAndView someRequestHandler(@ActiveUser User activeUser) {\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 31735844,
"author": "EliuX",
"author_id": 3233398,
"author_profile": "https://Stackoverflow.com/users/3233398",
"pm_score": 1,
"selected": false,
"text": "<p>I am using the <code>@AuthenticationPrincipal</code> annotation in <code>@Controller</code> classes as well as in <code>@ControllerAdvicer</code> annotated ones. Ex.:</p>\n\n<pre><code>@ControllerAdvice\npublic class ControllerAdvicer\n{\n private static final Logger LOGGER = LoggerFactory.getLogger(ControllerAdvicer.class);\n\n\n @ModelAttribute(\"userActive\")\n public UserActive currentUser(@AuthenticationPrincipal UserActive currentUser)\n {\n return currentUser;\n }\n}\n</code></pre>\n\n<p>Where <code>UserActive</code> is the class i use for logged users services, and extends from <code>org.springframework.security.core.userdetails.User</code>. Something like:</p>\n\n<pre><code>public class UserActive extends org.springframework.security.core.userdetails.User\n{\n\n private final User user;\n\n public UserActive(User user)\n {\n super(user.getUsername(), user.getPasswordHash(), user.getGrantedAuthorities());\n this.user = user;\n }\n\n //More functions\n}\n</code></pre>\n\n<p>Really easy.</p>\n"
},
{
"answer_id": 33628957,
"author": "Imrank",
"author_id": 1164714,
"author_profile": "https://Stackoverflow.com/users/1164714",
"pm_score": 1,
"selected": false,
"text": "<p>Define <code>Principal</code> as a dependency in your controller method and spring will inject the current authenticated user in your method at invocation.</p>\n"
},
{
"answer_id": 37446096,
"author": "matsev",
"author_id": 303598,
"author_profile": "https://Stackoverflow.com/users/303598",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using Spring Security ver >= 3.2, you can use the <code>@AuthenticationPrincipal</code> annotation:</p>\n\n<pre><code>@RequestMapping(method = RequestMethod.GET)\npublic ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {\n String currentUsername = currentUser.getUsername();\n // ...\n}\n</code></pre>\n\n<p>Here, <code>CustomUser</code> is a custom object that implements <code>UserDetails</code> that is returned by a custom <code>UserDetailsService</code>.</p>\n\n<p>More information can be found in the <a href=\"http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#mvc-authentication-principal\" rel=\"noreferrer\">@AuthenticationPrincipal</a> chapter of the Spring Security reference docs.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2495576/"
] |
I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?
I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?
```
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
```
|
If you are using [Spring 3](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments), the easiest way is:
```
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request, Principal principal) {
final String currentUser = principal.getName();
}
```
|
248,569 |
<p>Is this possible? I want to have the To:, Body, and an Attachment all pre-populated so all the user has to do is click send. Thanks!</p>
|
[
{
"answer_id": 248598,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": true,
"text": "<p>Open a new mail message (<code>ipm.note</code> is the <a href=\"https://msdn.microsoft.com/en-gb/en-en/library/office/ff861573.aspx\" rel=\"nofollow noreferrer\">message class</a> for emails)</p>\n\n<pre><code>outlook.exe /c ipm.note\n</code></pre>\n\n<p>Open a new mail message and populate sender: </p>\n\n<pre><code>outlook.exe /c ipm.note /m [email protected]\n</code></pre>\n\n<p>Open a new mail message with attachment: </p>\n\n<pre><code> outlook.exe /c ipm.note /a filename\n</code></pre>\n\n<p>Combination: (First one below didn't work in Office 2016, second did)</p>\n\n<pre><code> outlook.exe /c ipm.note /m [email protected]&subject=test%20subject&body=test%20body\n outlook.exe /c ipm.note /m \"[email protected]&subject=test%20subject&body=test%20body\"\n</code></pre>\n\n<p>The %20 has to be used to produce a blank space.</p>\n\n<ul>\n<li>More details at <a href=\"https://support.microsoft.com/en-gb/help/287573/how-to-use-command-line-switches-to-create-a-pre-addressed-e-mail-message-in-outlook\" rel=\"nofollow noreferrer\">Command Line for Creating a Pre-Addressed E-mail Message</a></li>\n<li>Command-line switches can be found <a href=\"https://support.office.com/en-gb/article/Command-line-switches-for-Outlook-for-Windows-079164cd-4ef5-4178-b235-441737deb3a6\" rel=\"nofollow noreferrer\">here</a></li>\n</ul>\n\n<p>This works for instance with a classic Outlook 2016 (build 16.0.4849.1000).</p>\n\n<p>But, as <a href=\"https://stackoverflow.com/users/2294031/snozzlebert\">Snozzlebert</a> notes <a href=\"https://stackoverflow.com/questions/248569/starting-outlook-and-having-an-email-pre-populated-from-command-line/248598#comment106314209_248598\">in the comments</a>, for a Outlook 365 Version 2001 (Build 12430.20184) the syntax would be:</p>\n\n<pre><code>outlook.exe /c ipm.note /m \"[email protected]?subject=test\"\n</code></pre>\n\n<blockquote>\n <p>the culprit was the <code>&</code> after the email-address - replacing it with <code>?</code> solved the problem.<br>\n It seems that Microsoft changed the syntax to the HTML mailto syntax.</p>\n</blockquote>\n"
},
{
"answer_id": 413774,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 2,
"selected": false,
"text": "<p>VonC's solution works, but as stated in the comments by skbergam it doesn't allow for attachments.</p>\n\n<p>If, like me, that's a biggie then the following WSH code does it.</p>\n\n<pre><code>Set olApp = CreateObject(\"Outlook.Application\")\nSet olMsg = olApp.CreateItem(0)\n\nWith olMsg\n .To = \"[email protected]\"\n '.CC = \"[email protected]\"\n '.BCC = \"[email protected]\"\n .Subject = \"Subject\"\n .Body = \"Body\"\n .Attachments.Add \"C:\\path\\to\\attachment\\test.txt\" \n\n .Display\nEnd With\n</code></pre>\n\n<p>I've tried it with Outlook2003</p>\n"
},
{
"answer_id": 9059255,
"author": "Dial-IN",
"author_id": 1177312,
"author_profile": "https://Stackoverflow.com/users/1177312",
"pm_score": 3,
"selected": false,
"text": "<p>You can attach files AND pre-fill in the To/Body if you simply place \" \" quotes around the command after the <code>/m</code> </p>\n\n<p>Example: </p>\n\n<pre><code>outlook.exe /c ipm.note /m \"[email protected]&subject=test%20subject&body=test%20body\" /a test.txt\n</code></pre>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] |
Is this possible? I want to have the To:, Body, and an Attachment all pre-populated so all the user has to do is click send. Thanks!
|
Open a new mail message (`ipm.note` is the [message class](https://msdn.microsoft.com/en-gb/en-en/library/office/ff861573.aspx) for emails)
```
outlook.exe /c ipm.note
```
Open a new mail message and populate sender:
```
outlook.exe /c ipm.note /m [email protected]
```
Open a new mail message with attachment:
```
outlook.exe /c ipm.note /a filename
```
Combination: (First one below didn't work in Office 2016, second did)
```
outlook.exe /c ipm.note /m [email protected]&subject=test%20subject&body=test%20body
outlook.exe /c ipm.note /m "[email protected]&subject=test%20subject&body=test%20body"
```
The %20 has to be used to produce a blank space.
* More details at [Command Line for Creating a Pre-Addressed E-mail Message](https://support.microsoft.com/en-gb/help/287573/how-to-use-command-line-switches-to-create-a-pre-addressed-e-mail-message-in-outlook)
* Command-line switches can be found [here](https://support.office.com/en-gb/article/Command-line-switches-for-Outlook-for-Windows-079164cd-4ef5-4178-b235-441737deb3a6)
This works for instance with a classic Outlook 2016 (build 16.0.4849.1000).
But, as [Snozzlebert](https://stackoverflow.com/users/2294031/snozzlebert) notes [in the comments](https://stackoverflow.com/questions/248569/starting-outlook-and-having-an-email-pre-populated-from-command-line/248598#comment106314209_248598), for a Outlook 365 Version 2001 (Build 12430.20184) the syntax would be:
```
outlook.exe /c ipm.note /m "[email protected]?subject=test"
```
>
> the culprit was the `&` after the email-address - replacing it with `?` solved the problem.
>
> It seems that Microsoft changed the syntax to the HTML mailto syntax.
>
>
>
|
248,580 |
<p>I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size.</p>
<p>When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size.</p>
<p>Adding this code after initComponents() does not help:</p>
<pre><code>this.mainPanel.setSize(new Dimension(800,600));
this.mainPanel.setMaximumSize(new Dimension(800,600));
this.mainPanel.setMinimumSize(new Dimension(800,600));
this.mainPanel.repaint();
</code></pre>
<p>I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things.</p>
<p>I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes. </p>
<p>Help is appreciated!</p>
|
[
{
"answer_id": 249459,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 0,
"selected": false,
"text": "<p>I use this method to complete the task, not sure if its the best and you need to wait calling it until the frame is actually on the screen. </p>\n\n<pre><code>protected void growBig()\n {\n int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;\n int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;\n Rectangle rectangle = getFrame().getBounds();\n rectangle.setSize(screenWidth, screenHeight);\n getFrame().setBounds(0, 0, screenWidth, screenHeight);\n getFrame().setSize(screenWidth, screenHeight);\n getFrame().doLayout();\n getFrame().validate();\n updateUI();\n }\n</code></pre>\n"
},
{
"answer_id": 249713,
"author": "Chobicus",
"author_id": 1514822,
"author_profile": "https://Stackoverflow.com/users/1514822",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried <a href=\"http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html\" rel=\"nofollow noreferrer\">java full screen mode</a>?</p>\n"
},
{
"answer_id": 249863,
"author": "Stroboskop",
"author_id": 23428,
"author_profile": "https://Stackoverflow.com/users/23428",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure how your touchscreen device works. But if you use Netbeans preview your panel is put in some outer container like JFrame/JWindow. And just maybe you set the frame to 800x600.</p>\n\n<p>If so, then the problem might be that the frame eats a few pixels for its own border, leaving your panel size < 800x600. And in that case your panel will be unable to use your min/max settings and revert to default sizes.</p>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size.
When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size.
Adding this code after initComponents() does not help:
```
this.mainPanel.setSize(new Dimension(800,600));
this.mainPanel.setMaximumSize(new Dimension(800,600));
this.mainPanel.setMinimumSize(new Dimension(800,600));
this.mainPanel.repaint();
```
I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things.
I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes.
Help is appreciated!
|
Have you tried [java full screen mode](http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html)?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.